@staix/agent-research 0.3.1 → 0.5.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/CHANGELOG.md +63 -0
- package/README.md +92 -19
- package/package.json +4 -1
- package/src/cli-output.ts +446 -0
- package/src/cli.ts +210 -67
- package/src/commands-table.ts +213 -93
- package/src/commands.ts +75 -13
- package/src/exp/attempts.ts +66 -13
- package/src/exp/calibrate.ts +125 -0
- package/src/exp/executor.ts +131 -15
- package/src/exp/final.ts +12 -3
- package/src/exp/idea-report.ts +97 -0
- package/src/exp/ideas.ts +90 -6
- package/src/exp/investigate.ts +25 -22
- package/src/exp/protocol.ts +26 -1
- package/src/exp/screen.ts +83 -0
- package/src/exp/selection.ts +110 -4
- package/src/exp/stages.ts +3 -1
- package/src/harness/hub-guidance.ts +16 -11
- package/src/harness/transitions.ts +37 -5
- package/src/manifest.ts +13 -5
- package/src/mcp-tools.ts +79 -24
- package/src/memory/archive.ts +8 -3
- package/src/paper/build.ts +39 -25
- package/src/paper/check.ts +46 -15
- package/src/paper/dependencies.ts +47 -0
- package/src/paper/document.ts +19 -0
- package/src/paper/figures.ts +152 -0
- package/src/paper/hygiene.ts +16 -5
- package/src/paper/plan.ts +71 -29
- package/src/paper/point-evidence.ts +27 -12
- package/src/paper/render.ts +113 -0
- package/src/paper/renderer.ts +128 -0
- package/src/paper/review.ts +41 -5
- package/src/plan/definition.ts +6 -1
- package/src/playbook.ts +20 -10
- package/src/provenance.ts +4 -3
- package/src/study-export.ts +7 -4
- package/src/study.ts +9 -4
- package/src/ui/plugin.ts +3 -1
package/src/exp/attempts.ts
CHANGED
|
@@ -12,8 +12,9 @@ import { randomUUID } from "node:crypto";
|
|
|
12
12
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
13
13
|
import { boundedText, commit, openStudy, plain, readJsonFile, readTextBounded, requireExperiment, requireGate, sha256, withLock, StudyLockBusyError, type Actor, type PendingEvent } from "../study.ts";
|
|
14
14
|
import { canonical, designBinding, sameProtocolInputs, frozenProtocol, validateStoredProtocol, protocolHash, readProtocol, readDesign, type Protocol } from "./protocol.ts";
|
|
15
|
-
import { buildContainerArgs, probeGpuAdmission, GpuAdmissionDeferred, validateGpuDevices, validateContainerInputSources, executionPathsOverlap, verifyExecutorInputs, InputVerificationError, checkExecutorInputs, stageContainerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
|
|
15
|
+
import { buildContainerArgs, dotRemoteGpus, probeGpuAdmission, GpuAdmissionDeferred, validateGpuDevices, validateContainerInputSources, executionPathsOverlap, verifyExecutorInputs, InputVerificationError, checkExecutorInputs, stageContainerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type GpuEnvironment, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
|
|
16
16
|
import { resolveSnapshot, transferSnapshot, transferTask } from "./snapshot.ts";
|
|
17
|
+
import { screenCandidate, type ScreenSummary } from "./screen.ts";
|
|
17
18
|
import { collectEvaluation as defaultEvaluationCollector, collectStageEvidence as defaultStageCollector, EvidenceError, MetricsError, OUTPUT_METADATA_BYTES, outputBudget, type StageEvidence } from "./metrics.ts";
|
|
18
19
|
|
|
19
20
|
export type AttemptStatus = "running" | "succeeded" | "failed" | "cancelled" | "unknown";
|
|
@@ -21,7 +22,7 @@ export interface AttemptStage { image: string; argv: string[]; mounts: { target:
|
|
|
21
22
|
export interface Evaluation { metrics: { name: string; unit: string; value: number; provenance: "ares-observed" }[]; outputs: { path: string; sha256: string; bytes: number }[] }
|
|
22
23
|
export interface Attempt {
|
|
23
24
|
v: 1 | 2 | 3; pipeline?: PipelineState; reuse?: AttemptReuseState; freshRequest?: { reuse: "off" | "eligible"; forceFresh: boolean }; id: string; studyId: string; run: string; protocolHash: string; sealBinding: string; commit: string; treeId: string; snapshotSha256?: string; seed: number; label: string; retryOf?: string;
|
|
24
|
-
executor: Executor; protocol: Protocol; paths: ContainerPaths; status: AttemptStatus; stage: Stage; reason?: string; error?: string; startedAt: string; endedAt?: string;
|
|
25
|
+
executor: Executor; protocol: Protocol; paths: ContainerPaths; status: AttemptStatus; stage: Stage; reason?: string; cause?: StartCause; error?: string; startedAt: string; endedAt?: string;
|
|
25
26
|
stages: Partial<Record<Stage, AttemptStage>>; metrics: Evaluation["metrics"]; outputs: Evaluation["outputs"];
|
|
26
27
|
sealing: { separateContainers: boolean; evaluatorReadOnly: boolean; candidateHasNoEvaluator: boolean; verifiedBy: "ares-observed" };
|
|
27
28
|
launching?: { pid: number; host: string; token: string; claimedAt: string; expiresAt: string };
|
|
@@ -32,13 +33,37 @@ export interface Attempt {
|
|
|
32
33
|
}
|
|
33
34
|
export interface AttemptOptions { repo: string; commit: string; seed?: number; run?: string; label?: string; retry?: string; detach?: boolean; expectedId?: string; reuse?: "off" | "eligible"; forceFresh?: boolean }
|
|
34
35
|
/** collectEvaluation is T4's validating adapter; T3 does not parse or validate metric schemas. */
|
|
35
|
-
export interface AttemptContext { actor: Actor; runner?: ProcessRunner; now?: () => number; sleep?: (ms: number) => Promise<void>; collectEvaluation?: (attempt: Attempt, runner: ProcessRunner) => Promise<Evaluation>; collectStageEvidence?: (attempt: Attempt, stage: Stage, runner: ProcessRunner) => Promise<StageEvidence> }
|
|
36
|
+
export interface AttemptContext { actor: Actor; runner?: ProcessRunner; env?: GpuEnvironment; now?: () => number; sleep?: (ms: number) => Promise<void>; collectEvaluation?: (attempt: Attempt, runner: ProcessRunner) => Promise<Evaluation>; collectStageEvidence?: (attempt: Attempt, stage: Stage, runner: ProcessRunner) => Promise<StageEvidence> }
|
|
36
37
|
export const ATTEMPT_BYTES = 1024 * 1024;
|
|
37
38
|
// Startup includes bounded image pulls and two 5-minute transfers; claims never survive indefinitely after a crash.
|
|
38
39
|
export const CONTROL_STALE_MS = 30 * 60_000;
|
|
39
40
|
// Filesystem mtime has sub-ms precision; Date.now is integral. Tolerate small future skew on live locks.
|
|
40
41
|
export const CONTROL_FUTURE_SKEW_MS = 60_000;
|
|
41
42
|
const controlScope = new AsyncLocalStorage<{ dir: string; token: string }>();
|
|
43
|
+
/** Closed container-start cause classes. Only the class is stored; stderr, command lines and paths never are. */
|
|
44
|
+
export const START_CAUSES = ["image-unavailable", "name-conflict", "daemon-unavailable", "resource-refused", "permission-denied", "other"] as const;
|
|
45
|
+
export type StartCause = typeof START_CAUSES[number];
|
|
46
|
+
export const START_STDERR_PREFIX = 4096;
|
|
47
|
+
/** Classify from the exit status and a bounded stderr prefix. The text is inspected here and discarded. */
|
|
48
|
+
export function classifyStartFailure(exitCode: number, stderr: string): StartCause {
|
|
49
|
+
const text = stderr.slice(0, START_STDERR_PREFIX).toLowerCase();
|
|
50
|
+
// Socket access only: an OCI runtime "exec ... permission denied" is an image problem and stays `other`.
|
|
51
|
+
if (/permission denied.*(docker daemon socket|docker\.sock)/.test(text)) return "permission-denied";
|
|
52
|
+
if (/cannot connect to the docker daemon|is the docker daemon running|error during connect|docker daemon is not running/.test(text)) return "daemon-unavailable";
|
|
53
|
+
if (/conflict\. the container name|is already in use by container/.test(text)) return "name-conflict";
|
|
54
|
+
if (/unable to find image|pull access denied|manifest unknown|manifest for .* not found|repository does not exist|no such image/.test(text)) return "image-unavailable";
|
|
55
|
+
if (/cannot allocate memory|out of memory|no space left on device|insufficient|could not select device driver|resource temporarily unavailable|minimum memory limit|range of cpus|exceeds .*limit/.test(text)) return "resource-refused";
|
|
56
|
+
void exitCode;
|
|
57
|
+
return "other";
|
|
58
|
+
}
|
|
59
|
+
const START_RECOVERY: Record<Exclude<StartCause, "other">, string> = {
|
|
60
|
+
"image-unavailable": "check that the protocol image digest is pulled or pullable on the executor host (docker image inspect)",
|
|
61
|
+
"name-conflict": "run ares attempt reconcile <dir> and remove the stale container with the attempt name on the executor host only if no study owns it",
|
|
62
|
+
"daemon-unavailable": "start the Docker daemon on the executor host and run ares executor check <dir>",
|
|
63
|
+
"resource-refused": "free memory, disk or devices on the executor host or lower the protocol limits",
|
|
64
|
+
"permission-denied": "give the executor user access to the Docker socket and run ares executor check <dir>",
|
|
65
|
+
};
|
|
66
|
+
class StartFailure extends Error { constructor(readonly cause: StartCause) { super("container start failed"); } }
|
|
42
67
|
const STATUSES: AttemptStatus[] = ["running", "succeeded", "failed", "cancelled", "unknown"];
|
|
43
68
|
const inspectFields = (prefix: string, fields: string[]) => fields.map(field => `${JSON.stringify(field)}:{{json ${prefix}.${field}}}`).join(",");
|
|
44
69
|
// Exclude inherited image labels/env and other unbounded Docker metadata from the observation.
|
|
@@ -133,6 +158,7 @@ export function validateAttemptRecord(raw: unknown, run: string, wanted: string)
|
|
|
133
158
|
if (!plain(raw.protocol.limits)) throw new Error("attempt GPU: limits missing; restore the frozen attempt record before retrying");
|
|
134
159
|
validateGpuDevices(raw.gpuDevices, raw.protocol.limits.gpus as number);
|
|
135
160
|
}
|
|
161
|
+
if (raw.cause !== undefined && !START_CAUSES.includes(raw.cause as StartCause)) throw new Error("attempt start cause: unknown class; use an ares version that supports this record, keeping the original file unchanged");
|
|
136
162
|
return raw as unknown as Attempt;
|
|
137
163
|
}
|
|
138
164
|
function load(dir: string): Attempt[] { return [...records(dir)]; }
|
|
@@ -255,7 +281,13 @@ function finish(attempt: Attempt, status: AttemptStatus, reason: string | undefi
|
|
|
255
281
|
function hostError(attempt: Attempt, step: string): Error {
|
|
256
282
|
return new Error(`executor ${attempt.executor.host ?? "local"}: ${step} failed; check that step on the executor host and run ares attempt reconcile <dir>`);
|
|
257
283
|
}
|
|
258
|
-
|
|
284
|
+
/** The failed start's container may still run, so the next step stays reconcile, never --retry. */
|
|
285
|
+
function cleanupError(attempt: Attempt, cause: StartCause): string {
|
|
286
|
+
if (cause === "other") return hostError(attempt, "failed start cleanup").message;
|
|
287
|
+
return `executor ${attempt.executor.host ?? "local"}: failed start cleanup failed (${cause}); ${START_RECOVERY[cause]}, then run ares attempt reconcile <dir>`;
|
|
288
|
+
}
|
|
289
|
+
function startupError(attempt: Attempt, step: string, cause?: StartCause): string {
|
|
290
|
+
if (cause && cause !== "other") return `executor ${attempt.executor.host ?? "local"}: ${step} failed (${cause}); ${START_RECOVERY[cause]}, then retry with the same attempt options and --retry ID`;
|
|
259
291
|
const recovery = step === "private workspace preparation" ? "make the configured executor workdir an owned physical directory with mode 0700" : step === "evaluator transfer" || step === "design recheck" ? "restore the task evaluator files and approve the current design" : step === "snapshot transfer" ? "check the repository commit and executor workspace" : step === "controller lock" ? "wait for the active control operation to finish" : "run ares executor check <dir> and fix the reported host or image setup";
|
|
260
292
|
return `executor ${attempt.executor.host ?? "local"}: ${step} failed; ${recovery}, then retry with the same attempt options and --retry ID`;
|
|
261
293
|
}
|
|
@@ -328,7 +360,7 @@ async function recordVerifiedStage(dir: string, attempt: Attempt, state: Observe
|
|
|
328
360
|
if (current.status !== "running" || current.stage !== attempt.stage) return undefined;
|
|
329
361
|
const stage = current.stages[current.stage]!;
|
|
330
362
|
stage.containerId = state.id; if (state.startedAt) stage.startedAt = state.startedAt;
|
|
331
|
-
if (current.reason === "executor-start" || current.reason === "executor-start-uncertain" || current.reason === "executor-preflight" || current.reason === "executor-seal") { delete current.reason; delete current.error; }
|
|
363
|
+
if (current.reason === "executor-start" || current.reason === "executor-start-uncertain" || current.reason === "executor-preflight" || current.reason === "executor-seal") { delete current.reason; delete current.cause; delete current.error; }
|
|
332
364
|
delete current.launching;
|
|
333
365
|
if (current.stage === "candidate") {
|
|
334
366
|
current.sealing.candidateHasNoEvaluator = true;
|
|
@@ -531,14 +563,17 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
|
|
|
531
563
|
}
|
|
532
564
|
let startedId: string | undefined;
|
|
533
565
|
try {
|
|
534
|
-
const result = await
|
|
566
|
+
const result = await runOnExecutor(attempt.executor, "docker", args, ctx.runner ?? spawnRunner);
|
|
567
|
+
if (result.exitCode !== 0 || result.timedOut || result.truncated) throw new StartFailure(result.timedOut || result.truncated ? "other" : classifyStartFailure(result.exitCode, result.stderr));
|
|
568
|
+
const cid = result.stdout.trim();
|
|
535
569
|
if (!/^[a-f0-9]{64}$/.test(cid)) throw hostError(attempt, "container start");
|
|
536
570
|
startedId = cid;
|
|
537
571
|
attempt.stages[attempt.stage]!.containerId = cid;
|
|
538
572
|
await startWatchdog(attempt.executor, attemptContainerName(attempt), remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, cid);
|
|
539
573
|
const state = await inspect(dir, attempt, ctx); if (!state) throw hostError(attempt, "container start verification");
|
|
540
574
|
return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.started");
|
|
541
|
-
} catch {
|
|
575
|
+
} catch (error) {
|
|
576
|
+
const cause: StartCause = error instanceof StartFailure ? error.cause : "other";
|
|
542
577
|
if (!startedId) {
|
|
543
578
|
try {
|
|
544
579
|
// A lost response is not proof that Docker rejected the start. Adopt only a verified owned container.
|
|
@@ -553,10 +588,17 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
|
|
|
553
588
|
}
|
|
554
589
|
// A name conflict can belong to another study with the same identity. Only clean up our returned container id.
|
|
555
590
|
if (startedId) {
|
|
556
|
-
|
|
557
|
-
|
|
591
|
+
let cleanupCause: StartCause | undefined;
|
|
592
|
+
try {
|
|
593
|
+
const killed = await runOnExecutor(attempt.executor, "docker", ["kill", startedId], recoveryCtx.runner ?? spawnRunner);
|
|
594
|
+
if (killed.exitCode !== 0 || killed.timedOut || killed.truncated) cleanupCause = killed.timedOut || killed.truncated ? "other" : classifyStartFailure(killed.exitCode, killed.stderr);
|
|
595
|
+
} catch { cleanupCause = "other"; }
|
|
596
|
+
if (cleanupCause) {
|
|
597
|
+
const recorded = cleanupCause;
|
|
598
|
+
return update(dir, attempt.id, ctx, current => { delete current.launching; current.reason = "executor-start"; current.cause = recorded; current.error = cleanupError(current, recorded); return "attempt.executor-error"; });
|
|
599
|
+
}
|
|
558
600
|
}
|
|
559
|
-
return update(dir, attempt.id, ctx, current => { if (current.status !== "running") return undefined; current.error = startupError(current, "container start"); finish(current, "failed", "executor-start", ctx); return "attempt.failed"; });
|
|
601
|
+
return update(dir, attempt.id, ctx, current => { if (current.status !== "running") return undefined; current.cause = cause; current.error = startupError(current, "container start", cause); finish(current, "failed", "executor-start", ctx); return "attempt.failed"; });
|
|
560
602
|
}
|
|
561
603
|
}
|
|
562
604
|
|
|
@@ -609,10 +651,21 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
|
|
|
609
651
|
validateContainerInputSources(protocol, { snapshot: posix.join(inputRoot, "snapshot"), output: posix.join(inputRoot, "output"), evaluator: posix.join(inputRoot, "task", "evaluator"), result: posix.join(inputRoot, "result") });
|
|
610
652
|
const existingAttempt = await withLock(dir, () => load(dir).find(a => a.id === wanted)), existing = existingAttempt !== undefined;
|
|
611
653
|
if (existingAttempt) existingReuseControls(existingAttempt, options);
|
|
654
|
+
// The screen runs before any budget, record or container exists, so a hit costs nothing but the read.
|
|
655
|
+
let screened: ScreenSummary | undefined;
|
|
656
|
+
if (!existing && definition.screen !== undefined) {
|
|
657
|
+
const { hits, summary } = await screenCandidate(options.repo, snapshot.commit, definition.screen, protocol.inputs ?? {}, executor, ctx.runner ?? spawnRunner);
|
|
658
|
+
if (hits.length) {
|
|
659
|
+
// Ledger only: the rule and the candidate path stay, the matched text never does.
|
|
660
|
+
await withLock(dir, () => commit(dir, [], [{ actor: ctx.actor, type: "attempt.screen.refused", data: { commit: snapshot.commit, hits } }]));
|
|
661
|
+
throw new Error(`attempt screen: candidate commit ${snapshot.commit} carries material held out from the candidate (${hits.map(hit => `${hit.rule} ${hit.path}${hit.line === undefined ? "" : `:${hit.line}`}`).join(", ")}); remove that material from the candidate commit, or change the screen through an approved design change, then retry ares attempt run`);
|
|
662
|
+
}
|
|
663
|
+
screened = summary;
|
|
664
|
+
}
|
|
612
665
|
const verifiedInputs = !existing && protocol.inputs !== undefined ? await verifyExecutorInputs(executor, protocol, ctx.runner ?? spawnRunner) : undefined;
|
|
613
666
|
let gpuDevices: string[] | undefined;
|
|
614
|
-
if (!existing &&
|
|
615
|
-
const admission = await probeGpuAdmission(executor, protocol.limits.gpus, ctx.runner ?? spawnRunner);
|
|
667
|
+
if (!existing && protocol.limits.gpus > 0 && (executor.gpu || dotRemoteGpus(ctx.env ?? process.env))) {
|
|
668
|
+
const admission = await probeGpuAdmission(executor, protocol.limits.gpus, ctx.runner ?? spawnRunner, ctx.env ?? process.env);
|
|
616
669
|
if (admission.status === "deferred") {
|
|
617
670
|
// An overlapping duplicate may have admitted the same identity during this read-only probe.
|
|
618
671
|
const duplicate = await withLock(dir, () => load(dir).find(attempt => attempt.id === wanted));
|
|
@@ -640,7 +693,7 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
|
|
|
640
693
|
if (record.pipeline) record.paths = pipelinePaths(record);
|
|
641
694
|
if (approval.length) record.pendingAutoApproval = binding!;
|
|
642
695
|
if (finalAuthorization) { record.finalBinding = finalAuthorization.binding; record.finalWinner = finalAuthorization.winner; if (finalAuthorization.auto) record.pendingFinalApproval = finalAuthorization.binding; }
|
|
643
|
-
commit(dir, [[file(dir, record), JSON.stringify(record, null, 2) + "\n", ATTEMPT_BYTES]], [{ actor: ctx.actor, type: "attempt.started", data: { id: wanted, run, seed, commit: record.commit, treeId: record.treeId } }]);
|
|
696
|
+
commit(dir, [[file(dir, record), JSON.stringify(record, null, 2) + "\n", ATTEMPT_BYTES]], [{ actor: ctx.actor, type: "attempt.started", data: { id: wanted, run, seed, commit: record.commit, treeId: record.treeId, ...(screened === undefined ? {} : { screen: screened }) } }]);
|
|
644
697
|
created = true; return record;
|
|
645
698
|
}); } catch (error) {
|
|
646
699
|
if (reserved) await withLock(dir, async () => {
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { commit, openStudy, plain, readLedger, readTextBounded, requireExperiment, sha256, type Actor } from "../study.ts";
|
|
4
|
+
import { listAttempts, type Attempt } from "./attempts.ts";
|
|
5
|
+
import { readFinalSeeds } from "./final.ts";
|
|
6
|
+
import { protocolHash, readProtocol, type ProtocolDefinition } from "./protocol.ts";
|
|
7
|
+
import { observedMetric, readSelection, type Selection } from "./selection.ts";
|
|
8
|
+
|
|
9
|
+
export interface CalibrationOptions { fromRun: string; nullCommit?: string; z?: number }
|
|
10
|
+
interface CalibrationReceipt {
|
|
11
|
+
v: 1; method: "seed-sd" | "aa"; metric: string; commit: string; null?: string;
|
|
12
|
+
seeds: number[]; attempts: string[]; n: number; sd: number; z: number;
|
|
13
|
+
minSeeds: number; recommendedMinDelta: number;
|
|
14
|
+
}
|
|
15
|
+
const CALIBRATION_BYTES = 65_536;
|
|
16
|
+
const RUN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
17
|
+
const COMMIT = /^[a-f0-9]{40}$/;
|
|
18
|
+
const HASH = /^[a-f0-9]{64}$/;
|
|
19
|
+
|
|
20
|
+
function invalid(cause: string): never {
|
|
21
|
+
throw new Error(`selection calibrate: ${cause}; inspect the selected run and retry ares selection calibrate <dir> --from-run RUN`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function receiptPath(dir: string, run: string, hash?: string): string {
|
|
25
|
+
return hash === undefined ? join(dir, "runs", run, "calibration.json")
|
|
26
|
+
: join(dir, "runs", run, "calibrations", `${hash}.json`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function sampleSd(values: number[]): number {
|
|
30
|
+
const scale = Math.max(...values.map(Math.abs));
|
|
31
|
+
if (scale === 0) return 0;
|
|
32
|
+
const scaled = values.map(value => value / scale);
|
|
33
|
+
const mean = scaled.reduce((sum, value) => sum + value, 0) / scaled.length;
|
|
34
|
+
return Math.sqrt(scaled.reduce((sum, value) => sum + (value - mean) ** 2, 0) / (scaled.length - 1)) * scale;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function readBoundCalibration(dir: string, rule: Extract<Selection, { v: 2 }>, protocol: ProtocolDefinition) {
|
|
38
|
+
const hash = rule.calibration?.sha256;
|
|
39
|
+
if (!hash) return undefined;
|
|
40
|
+
const event = readLedger(dir).findLast(entry => entry.type === "selection.calibrated" && entry.data.sha256 === hash);
|
|
41
|
+
const run = event?.data.run;
|
|
42
|
+
const fix = "run ares selection calibrate <dir> --from-run RUN and bind the resulting sha256 in ares selection";
|
|
43
|
+
if (typeof run !== "string" || !RUN.test(run)) throw new Error(`selection.calibration.sha256: no recorded calibration for this digest; ${fix}`);
|
|
44
|
+
if (event?.data.protocolHash !== protocolHash(protocol)) throw new Error(`selection.calibration: protocol differs from the recorded calibration; ${fix}`);
|
|
45
|
+
let text: string, receipt: unknown;
|
|
46
|
+
try {
|
|
47
|
+
text = readTextBounded(receiptPath(dir, run, hash), CALIBRATION_BYTES);
|
|
48
|
+
receipt = JSON.parse(text);
|
|
49
|
+
} catch { throw new Error(`selection.calibration: recorded receipt is unreadable or invalid; restore the bounded receipt or ${fix}`); }
|
|
50
|
+
if (sha256(text) !== hash || !plain(receipt) || receipt.v !== 1) throw new Error(`selection.calibration: receipt bytes do not match the recorded calibration; restore the original receipt or ${fix}`);
|
|
51
|
+
if (receipt.metric !== rule.metric || receipt.commit !== rule.baseline.commit || receipt.minSeeds !== rule.minSeeds) throw new Error(`selection.calibration: the metric, baseline or minimum seed count differs from the recorded calibration; ${fix}`);
|
|
52
|
+
const recommendation = receipt.recommendedMinDelta;
|
|
53
|
+
if (typeof recommendation !== "number" || !Number.isFinite(recommendation) || recommendation < 0) throw new Error(`selection.calibration: recorded recommendation is invalid; ${fix}`);
|
|
54
|
+
return { recommendedMinDelta: recommendation, minDelta: rule.minDelta, belowNoise: rule.minDelta < recommendation };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function validateCalibrationOptions(options: CalibrationOptions) {
|
|
58
|
+
const fromRun = options.fromRun, nullCommit = options.nullCommit?.toLowerCase(), z = options.z ?? 2;
|
|
59
|
+
if (typeof fromRun !== "string" || !RUN.test(fromRun)) invalid("from-run must be a valid run name");
|
|
60
|
+
if (nullCommit !== undefined && !COMMIT.test(nullCommit)) invalid("null commit must be a full 40-hex commit");
|
|
61
|
+
if (typeof z !== "number" || !Number.isFinite(z) || z <= 0) invalid("z must be a finite positive number");
|
|
62
|
+
return { fromRun, ...(nullCommit === undefined ? {} : { nullCommit }), z };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Caller holds the study lock. Only current-protocol, non-reserved earliest successes count. */
|
|
66
|
+
export function calibrateSelection(dirArg: string, options: CalibrationOptions, actor: Actor) {
|
|
67
|
+
const { dir, study } = openStudy(dirArg);
|
|
68
|
+
requireExperiment(study);
|
|
69
|
+
const { fromRun: run, nullCommit: other, z } = validateCalibrationOptions(options);
|
|
70
|
+
const protocol = readProtocol(dir), rule = protocol && readSelection(dir, protocol);
|
|
71
|
+
if (!protocol || !rule) invalid("define a protocol and selection rule first");
|
|
72
|
+
if (other === rule.baseline.commit) invalid("null commit must differ from the baseline commit");
|
|
73
|
+
const hash = protocolHash(protocol), metric = protocol.metrics.find(entry => entry.name === rule.metric)!;
|
|
74
|
+
const reserved = new Set(readFinalSeeds(dir, protocol)?.seeds), seeds = new Set(protocol.seeds);
|
|
75
|
+
const attempts = listAttempts(dir, { run, status: "succeeded" }).attempts;
|
|
76
|
+
const events = readLedger(dir);
|
|
77
|
+
const byId = new Map(attempts.map(attempt => [attempt.id, attempt]));
|
|
78
|
+
const started = new Set<string>();
|
|
79
|
+
const baseline = new Map<number, Attempt>(), nullArm = new Map<number, Attempt>();
|
|
80
|
+
for (const event of events) {
|
|
81
|
+
const { id } = event.data;
|
|
82
|
+
if (event.type !== "attempt.started" || typeof id !== "string") continue;
|
|
83
|
+
const attempt = byId.get(id);
|
|
84
|
+
if (!attempt || attempt.protocolHash !== hash || (attempt.commit !== rule.baseline.commit && attempt.commit !== other)
|
|
85
|
+
|| !seeds.has(attempt.seed) || reserved.has(attempt.seed)) continue;
|
|
86
|
+
if (started.has(id) || attempt.studyId !== study.id || event.data.run !== run || event.data.commit !== attempt.commit || event.data.seed !== attempt.seed) invalid(`attempt ${id} has a duplicate or mismatched start receipt`);
|
|
87
|
+
started.add(id);
|
|
88
|
+
const arm = attempt.commit === rule.baseline.commit ? baseline : nullArm;
|
|
89
|
+
if (!arm.has(attempt.seed)) arm.set(attempt.seed, attempt);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (baseline.size < 3) invalid("at least three non-reserved baseline seeds are required");
|
|
93
|
+
const pairedSeeds = [...baseline.keys()].filter(seed => other === undefined || nullArm.has(seed)).sort((a, b) => a - b);
|
|
94
|
+
if (pairedSeeds.length < 3) invalid("at least three non-reserved paired A/A seeds are required");
|
|
95
|
+
if (other !== undefined) {
|
|
96
|
+
const trees = new Set([...baseline.values(), ...nullArm.values()].map(attempt => attempt.treeId));
|
|
97
|
+
if (trees.size !== 1 || !COMMIT.test(trees.values().next().value ?? "")) invalid("A/A arms must have the same recorded task tree id");
|
|
98
|
+
}
|
|
99
|
+
const evidence: string[] = [];
|
|
100
|
+
const measured = (attempt: Attempt) => {
|
|
101
|
+
const value = observedMetric(attempt, metric);
|
|
102
|
+
if (value === undefined) invalid(`attempt ${attempt.id} lacks the validated primary metric`);
|
|
103
|
+
evidence.push(attempt.id);
|
|
104
|
+
return value;
|
|
105
|
+
};
|
|
106
|
+
const scores = pairedSeeds.map(seed => {
|
|
107
|
+
const value = measured(baseline.get(seed)!);
|
|
108
|
+
return other === undefined ? value : measured(nullArm.get(seed)!) - value;
|
|
109
|
+
});
|
|
110
|
+
if (scores.some(score => !Number.isFinite(score))) invalid("paired deltas overflow; rescale the primary metric");
|
|
111
|
+
const sd = sampleSd(scores), method = other === undefined ? "seed-sd" : "aa";
|
|
112
|
+
const recommendedMinDelta = (sd / Math.sqrt(rule.minSeeds)) * (method === "seed-sd" ? Math.SQRT2 : 1) * z;
|
|
113
|
+
if (!Number.isFinite(sd) || !Number.isFinite(recommendedMinDelta)) invalid("calibration overflows; rescale the metric or reduce z");
|
|
114
|
+
const receipt: CalibrationReceipt = { v: 1, method, metric: rule.metric, commit: rule.baseline.commit, ...(other === undefined ? {} : { null: other }),
|
|
115
|
+
seeds: pairedSeeds, attempts: evidence, n: pairedSeeds.length, sd, z, minSeeds: rule.minSeeds, recommendedMinDelta };
|
|
116
|
+
const text = JSON.stringify(receipt, null, 2) + "\n", sha = sha256(text);
|
|
117
|
+
const latest = receiptPath(dir, run), archived = receiptPath(dir, run, sha);
|
|
118
|
+
const previous = existsSync(latest) ? readTextBounded(latest, CALIBRATION_BYTES) : undefined;
|
|
119
|
+
const recorded = events.some(event => event.type === "selection.calibrated" && event.data.run === run && event.data.sha256 === sha && event.data.protocolHash === hash);
|
|
120
|
+
if (existsSync(archived) && readTextBounded(archived, CALIBRATION_BYTES) !== text) invalid("immutable calibration receipt differs from its digest; restore the original receipt");
|
|
121
|
+
if (previous !== text || !recorded || !existsSync(archived)) {
|
|
122
|
+
commit(dir, [[latest, text, CALIBRATION_BYTES], [archived, text, CALIBRATION_BYTES]], [{ actor, type: "selection.calibrated", data: { run, sha256: sha, protocolHash: hash } }]);
|
|
123
|
+
}
|
|
124
|
+
return { ...receipt, sha256: sha, ...(method === "seed-sd" ? { assumption: "Assumes independent arms. This is conservative when pairing by seed removes shared variance." } : {}) };
|
|
125
|
+
}
|
package/src/exp/executor.ts
CHANGED
|
@@ -206,10 +206,31 @@ function gpuProbe(stdout: string): { inventory: GpuInventoryRow[]; loadRatio: nu
|
|
|
206
206
|
return { inventory, loadRatio: Number(parts[0]) / Number(cpu) };
|
|
207
207
|
}
|
|
208
208
|
/** One read-only probe; admission never sleeps, retries or reserves a physical GPU. */
|
|
209
|
-
|
|
209
|
+
/** A refused dot remote hold lease: a usage error raised before any probe, attempt or event. */
|
|
210
|
+
export class GpuLeaseError extends Error {}
|
|
211
|
+
export type GpuEnvironment = Readonly<Record<string, string | undefined>>;
|
|
212
|
+
function leaseRefused(cause: string, next: string): never { throw new GpuLeaseError(`DOT_REMOTE_GPUS: ${cause}; ${next}`); }
|
|
213
|
+
/** The UUIDs a `dot remote hold` lease names, in order, or undefined when unset or empty. */
|
|
214
|
+
export function dotRemoteGpus(env: GpuEnvironment): string[] | undefined {
|
|
215
|
+
const raw = env.DOT_REMOTE_GPUS;
|
|
216
|
+
if (raw === undefined || raw.trim() === "") return undefined;
|
|
217
|
+
const parts = raw.split(",").map(part => part.trim());
|
|
218
|
+
if (parts.length > 64 || parts.some(part => !GPU_UUID.test(part))) leaseRefused("malformed value", "pass 1..64 comma-separated GPU-... UUIDs from dot remote hold, or unset it");
|
|
219
|
+
const devices = parts.map(part => "GPU-" + part.slice(4).toLowerCase());
|
|
220
|
+
if (new Set(devices).size !== devices.length) leaseRefused("duplicate UUID", "pass distinct GPU UUIDs from dot remote hold, or unset it");
|
|
221
|
+
return devices;
|
|
222
|
+
}
|
|
223
|
+
export async function probeGpuAdmission(executorArg: Executor, count: number, runner: ProcessRunner = spawnRunner, env: GpuEnvironment = process.env): Promise<GpuAdmission> {
|
|
210
224
|
const executor = validateExecutor(executorArg);
|
|
211
225
|
if (!Number.isSafeInteger(count) || count < 0 || count > 64) throw new Error("GPU admission count: integer 0..64 required; use the protocol GPU count before retrying");
|
|
212
|
-
if (
|
|
226
|
+
if (count === 0) return { status: "admitted", devices: [] };
|
|
227
|
+
const leased = dotRemoteGpus(env);
|
|
228
|
+
if (leased && !executor.gpu) leaseRefused("set but the executor has no gpu settings", "add executor gpu settings with ares executor set, or unset DOT_REMOTE_GPUS");
|
|
229
|
+
if (!executor.gpu) return { status: "admitted", devices: [] };
|
|
230
|
+
if (leased && leased.length < count) leaseRefused(`fewer UUIDs (${leased.length}) than protocol.limits.gpus (${count})`, "hold at least that many GPUs with dot remote hold --gpus N");
|
|
231
|
+
const indexed = executor.gpu.devices.some(selector => !String(selector).startsWith("GPU-"));
|
|
232
|
+
// With UUID-only allow-lists membership is decided before probing; index entries need the inventory.
|
|
233
|
+
if (leased && !indexed && leased.some(uuid => !executor.gpu!.devices.map(String).includes(uuid))) leaseRefused("UUID not in the executor allow-list", "hold GPUs the executor gpu.devices allow, or widen the allow-list with ares executor set");
|
|
213
234
|
let parsed: ReturnType<typeof gpuProbe>;
|
|
214
235
|
try {
|
|
215
236
|
const result = await runOnExecutor(executor, "sh", ["-c", GPU_ADMISSION_SCRIPT], runner, { timeoutMs: GPU_PROBE_TIMEOUT_MS, maxOutputBytes: GPU_PROBE_OUTPUT_BYTES });
|
|
@@ -218,6 +239,16 @@ export async function probeGpuAdmission(executorArg: Executor, count: number, ru
|
|
|
218
239
|
} catch { return gpuDeferred("probe"); }
|
|
219
240
|
if (parsed.loadRatio > executor.gpu.maxLoadRatio) return gpuDeferred("load");
|
|
220
241
|
const devices: string[] = [];
|
|
242
|
+
if (leased) {
|
|
243
|
+
const allowed = new Set(executor.gpu.devices.flatMap(selector => parsed.inventory.filter(gpu => gpu.index === String(selector) || gpu.uuid === selector).map(gpu => gpu.uuid)));
|
|
244
|
+
if (leased.some(uuid => !allowed.has(uuid))) leaseRefused("UUID not in the executor allow-list", "hold GPUs the executor gpu.devices allow, or widen the allow-list with ares executor set");
|
|
245
|
+
for (const uuid of leased) {
|
|
246
|
+
const gpu = parsed.inventory.find(gpu => gpu.uuid === uuid);
|
|
247
|
+
if (!gpu || gpu.memory < executor.gpu.minFreeMemoryMb) continue;
|
|
248
|
+
devices.push(gpu.uuid); if (devices.length === count) return { status: "admitted", devices };
|
|
249
|
+
}
|
|
250
|
+
return gpuDeferred("devices");
|
|
251
|
+
}
|
|
221
252
|
for (const selector of executor.gpu.devices) {
|
|
222
253
|
const gpu = parsed.inventory.find(gpu => gpu.index === String(selector) || gpu.uuid === selector);
|
|
223
254
|
if (!gpu || gpu.memory < executor.gpu.minFreeMemoryMb || devices.includes(gpu.uuid)) continue;
|
|
@@ -231,7 +262,10 @@ export const INPUT_MANIFEST_FILES = 100_000, INPUT_MANIFEST_TIMEOUT_MS = 300_000
|
|
|
231
262
|
// ponytail: ceiling 100,000 files/directories, depth 64 and 5 minutes; bytes stream in 1 MiB chunks, never into the study.
|
|
232
263
|
export const INPUT_MANIFEST_SCRIPT = String.raw`import os,sys,stat,hashlib,json
|
|
233
264
|
MAX=100000
|
|
265
|
+
mode=sys.argv[2] if len(sys.argv)>2 else 'manifest'
|
|
266
|
+
cap=int(sys.argv[3]) if len(sys.argv)>3 else MAX
|
|
234
267
|
records=[]
|
|
268
|
+
blobs=[]
|
|
235
269
|
entries=0
|
|
236
270
|
directories=0
|
|
237
271
|
total=0
|
|
@@ -257,12 +291,14 @@ def walk(fd,prefix,depth):
|
|
|
257
291
|
walk(child,name,depth+1)
|
|
258
292
|
finally: os.close(child)
|
|
259
293
|
elif stat.S_ISREG(info.st_mode):
|
|
260
|
-
if len(records)>=MAX or info.st_size>9007199254740991-total: raise ValueError()
|
|
294
|
+
if len(records)>=(cap if mode=='hashes' else MAX) or info.st_size>9007199254740991-total: raise ValueError()
|
|
261
295
|
child=os.open(item.name,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
|
|
262
296
|
try:
|
|
263
297
|
opened=os.fstat(child)
|
|
264
298
|
if not stat.S_ISREG(opened.st_mode) or identity(opened)!=identity(info): raise ValueError()
|
|
265
299
|
digest=hashlib.sha256()
|
|
300
|
+
blob=hashlib.sha1()
|
|
301
|
+
if mode=='hashes': blob.update(('blob %d\0' % info.st_size).encode('utf-8'))
|
|
266
302
|
size=0
|
|
267
303
|
while True:
|
|
268
304
|
chunk=os.read(child,1048576)
|
|
@@ -270,10 +306,12 @@ def walk(fd,prefix,depth):
|
|
|
270
306
|
size+=len(chunk)
|
|
271
307
|
if size>info.st_size: raise ValueError()
|
|
272
308
|
digest.update(chunk)
|
|
309
|
+
if mode=='hashes': blob.update(chunk)
|
|
273
310
|
if size!=info.st_size or identity(os.fstat(child))!=identity(opened): raise ValueError()
|
|
274
311
|
finally: os.close(child)
|
|
275
312
|
total+=size
|
|
276
313
|
records.append((name,size,digest.hexdigest()))
|
|
314
|
+
if mode=='hashes': blobs.append(blob.hexdigest())
|
|
277
315
|
else: raise ValueError()
|
|
278
316
|
if identity(os.fstat(fd))!=identity(before): raise ValueError()
|
|
279
317
|
try:
|
|
@@ -289,10 +327,13 @@ try:
|
|
|
289
327
|
fd=child
|
|
290
328
|
walk(fd,'',0)
|
|
291
329
|
finally: os.close(fd)
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
330
|
+
if mode=='hashes':
|
|
331
|
+
print(json.dumps({'files':len(records),'bytes':total,'blobs':sorted(set(blobs))},separators=(',',':')))
|
|
332
|
+
else:
|
|
333
|
+
digest=hashlib.sha256()
|
|
334
|
+
for row in sorted(records,key=lambda row:row[0].encode('utf-8')):
|
|
335
|
+
digest.update((json.dumps(row,ensure_ascii=False,separators=(',',':'))+'\n').encode('utf-8'))
|
|
336
|
+
print(json.dumps({'sha256':digest.hexdigest(),'files':len(records),'bytes':total},separators=(',',':')))
|
|
296
337
|
except Exception:
|
|
297
338
|
sys.stderr.write('input manifest refused\n')
|
|
298
339
|
sys.exit(1)
|
|
@@ -309,6 +350,20 @@ export async function hashExecutorInput(executorArg: Executor, path: string, run
|
|
|
309
350
|
if (!plain(raw) || Object.keys(raw).some(key => !["sha256", "files", "bytes"].includes(key)) || typeof raw.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.sha256) || !Number.isSafeInteger(raw.files) || Number(raw.files)<0 || Number(raw.files)>INPUT_MANIFEST_FILES || !Number.isSafeInteger(raw.bytes) || Number(raw.bytes)<0) throw refuse();
|
|
310
351
|
return {sha256: raw.sha256, files: raw.files as number, bytes: raw.bytes as number};
|
|
311
352
|
}
|
|
353
|
+
export const SCREEN_INPUT_BLOB_BYTES = 1_048_576;
|
|
354
|
+
/** A pre-execution screen reads the same hardened walk, but reports blob ids only: no names, no contents. */
|
|
355
|
+
export async function hashExecutorInputBlobs(executorArg: Executor, path: string, maxFiles: number, runner: ProcessRunner = spawnRunner): Promise<{ files: number; bytes: number; blobs: string[] }> {
|
|
356
|
+
const executor = validateExecutor(executorArg), source = directory(path, "executor input path");
|
|
357
|
+
if (!Number.isSafeInteger(maxFiles) || maxFiles < 1 || maxFiles > INPUT_MANIFEST_FILES) throw new Error(`executor screen: invalid file limit; choose 1..${INPUT_MANIFEST_FILES} files`);
|
|
358
|
+
const refuse = () => new Error(`executor screen: blob list failed; check Python3 and a stable readable regular directory of at most ${maxFiles} files without special files or symlinked ancestors on the executor, or stop screening evaluator inputs through a design change`);
|
|
359
|
+
let result: ProcessResult;
|
|
360
|
+
try {result = await runOnExecutor(executor, "python3", ["-I", "-S", "-c", INPUT_MANIFEST_SCRIPT, source, "hashes", String(maxFiles)], runner, {timeoutMs: INPUT_MANIFEST_TIMEOUT_MS, maxOutputBytes: SCREEN_INPUT_BLOB_BYTES});}
|
|
361
|
+
catch {throw refuse();}
|
|
362
|
+
if (result.exitCode !== 0 || result.timedOut || result.truncated || Buffer.byteLength(result.stdout) > SCREEN_INPUT_BLOB_BYTES) throw refuse();
|
|
363
|
+
let raw: unknown; try {raw = JSON.parse(result.stdout);} catch {throw refuse();}
|
|
364
|
+
if (!plain(raw) || Object.keys(raw).some(key => !["files", "bytes", "blobs"].includes(key)) || !Number.isSafeInteger(raw.files) || Number(raw.files)<0 || Number(raw.files)>maxFiles || !Number.isSafeInteger(raw.bytes) || Number(raw.bytes)<0 || !Array.isArray(raw.blobs) || raw.blobs.length>maxFiles || raw.blobs.some(blob => typeof blob !== "string" || !/^[a-f0-9]{40}$/.test(blob))) throw refuse();
|
|
365
|
+
return {files: raw.files as number, bytes: raw.bytes as number, blobs: raw.blobs as string[]};
|
|
366
|
+
}
|
|
312
367
|
/** Verify every declared input without persisting its host locator or manifest rows. */
|
|
313
368
|
export async function verifyExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<Record<string, string>> {
|
|
314
369
|
const inputs = validateProtocol(protocol).inputs ?? {}, verified: [string, string][] = [];
|
|
@@ -341,21 +396,82 @@ export async function checkExecutor(dir: string, runner: ProcessRunner = spawnRu
|
|
|
341
396
|
}
|
|
342
397
|
return checkExecutorInputs(executor, protocol, runner);
|
|
343
398
|
}
|
|
344
|
-
|
|
345
|
-
export async function checkExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheck> {
|
|
346
|
-
if (Object.keys(protocol.inputs ?? {}).length) await step(executor, "Python3 input manifest runtime", "python3", ["-I", "-S", "-c", "import sys; assert sys.version_info.major == 3"], runner);
|
|
399
|
+
async function dockerVersion(executor: Executor, runner: ProcessRunner): Promise<string> {
|
|
347
400
|
const version = (await step(executor, "Docker server version", "docker", ["version", "--format", "{{.Server.Version}}"], runner)).stdout.trim();
|
|
348
401
|
if (!/^[0-9]+\.[0-9]+(?:\.[0-9]+)?[A-Za-z0-9.+_-]*$/.test(version) || version.length > 128) throw failed(executor, "Docker server version");
|
|
402
|
+
return version;
|
|
403
|
+
}
|
|
404
|
+
async function ensureImage(executor: Executor, image: string, runner: ProcessRunner): Promise<void> {
|
|
405
|
+
let present: ProcessResult;
|
|
406
|
+
try { present = await runOnExecutor(executor, "docker", ["image", "inspect", "--format", "{{.Id}}", image], runner); }
|
|
407
|
+
catch { throw failed(executor, "image availability"); }
|
|
408
|
+
if (present.timedOut || present.truncated) throw failed(executor, "image availability");
|
|
409
|
+
if (present.exitCode !== 0) await step(executor, "image pull", "docker", ["pull", image], runner, { timeoutMs: 300_000 });
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
export interface ExecutorCheckRow { name: string; state: "ok" | "failed" | "skipped"; detail: string }
|
|
413
|
+
export interface ExecutorCheckReport { checks: ExecutorCheckRow[] }
|
|
414
|
+
const PYTHON_RUNTIME = ["-I", "-S", "-c", "import sys; assert sys.version_info.major == 3"];
|
|
415
|
+
|
|
416
|
+
export async function checkExecutorReport(dir: string, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheckReport> {
|
|
417
|
+
const checks: ExecutorCheckRow[] = [];
|
|
418
|
+
const check = async (name: string, operation: () => unknown | Promise<unknown>, prerequisite?: string): Promise<boolean> => {
|
|
419
|
+
if (prerequisite) { checks.push({ name, state: "skipped", detail: prerequisite }); return false; }
|
|
420
|
+
try {
|
|
421
|
+
const detail = await operation();
|
|
422
|
+
checks.push({ name, state: "ok", detail: typeof detail === "string" ? detail : "" });
|
|
423
|
+
return true;
|
|
424
|
+
} catch (error) {
|
|
425
|
+
checks.push({ name, state: "failed", detail: error instanceof Error ? error.message : "Check failed" });
|
|
426
|
+
return false;
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
requireExperiment(openStudy(dir).study);
|
|
430
|
+
const config: { executor?: Executor; protocol?: NonNullable<ReturnType<typeof readProtocol>> } = {};
|
|
431
|
+
await check("Executor configuration", () => {
|
|
432
|
+
const executor = readExecutor(dir);
|
|
433
|
+
if (!executor) throw new Error("Configure the executor with ares executor set <dir>");
|
|
434
|
+
config.executor = executor;
|
|
435
|
+
return executor.kind;
|
|
436
|
+
});
|
|
437
|
+
await check("Protocol", () => {
|
|
438
|
+
const protocol = readProtocol(dir);
|
|
439
|
+
if (!protocol) throw new Error("Set the protocol with ares protocol <dir> --file PATH");
|
|
440
|
+
config.protocol = protocol;
|
|
441
|
+
});
|
|
442
|
+
const { executor, protocol } = config;
|
|
443
|
+
const connected = !!executor && (executor.kind !== "ssh" || await check("SSH connection", () => step(executor!, "SSH connection", "true", [], runner, { timeoutMs: 10_000 })));
|
|
444
|
+
const unavailable = connected ? undefined : "Executor unavailable";
|
|
445
|
+
if (protocol && (protocol.v === 1 ? Object.keys(protocol.inputs ?? {}).length > 0 : protocol.candidate.stages.some(stage => Object.keys(stage.inputs).length > 0))) {
|
|
446
|
+
await check("Python 3", () => step(executor!, "Python3 input manifest runtime", "python3", PYTHON_RUNTIME, runner), unavailable);
|
|
447
|
+
}
|
|
448
|
+
const docker = await check("Docker server version", () => dockerVersion(executor!, runner), unavailable);
|
|
449
|
+
for (const [name, flag] of [["UID", "-u"], ["GID", "-g"]] as const) {
|
|
450
|
+
await check(name, async () => {
|
|
451
|
+
const value = (await step(executor!, `host ${name.toLowerCase()}`, "id", [flag], runner)).stdout.trim();
|
|
452
|
+
if (!/^[1-9][0-9]{0,9}$/.test(value)) throw failed(executor!, `non-root host ${name.toLowerCase()}`);
|
|
453
|
+
return value;
|
|
454
|
+
}, unavailable);
|
|
455
|
+
}
|
|
456
|
+
if (protocol) {
|
|
457
|
+
const candidates = protocol.v === 1 ? [protocol.candidate.image] : protocol.candidate.stages.map(stage => stage.image);
|
|
458
|
+
for (const image of new Set([...candidates, protocol.evaluator.image])) {
|
|
459
|
+
await check(`Image ${image}`, () => ensureImage(executor!, image, runner), docker ? undefined : "Docker unavailable");
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
return { checks };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** Check a frozen attempt's configuration rather than mutable study files. */
|
|
466
|
+
export async function checkExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheck> {
|
|
467
|
+
if (Object.keys(protocol.inputs ?? {}).length) await step(executor, "Python3 input manifest runtime", "python3", PYTHON_RUNTIME, runner);
|
|
468
|
+
const version = await dockerVersion(executor, runner);
|
|
349
469
|
const uid = (await step(executor, "host uid", "id", ["-u"], runner)).stdout.trim();
|
|
350
470
|
const gid = (await step(executor, "host gid", "id", ["-g"], runner)).stdout.trim();
|
|
351
471
|
if (!/^[1-9][0-9]{0,9}$/.test(uid) || !/^[1-9][0-9]{0,9}$/.test(gid)) throw failed(executor, "non-root host uid:gid");
|
|
352
472
|
const images: ExecutorCheck["images"] = [];
|
|
353
473
|
for (const image of new Set([protocol.candidate.image, protocol.evaluator.image])) {
|
|
354
|
-
|
|
355
|
-
try { present = await runOnExecutor(executor, "docker", ["image", "inspect", "--format", "{{.Id}}", image], runner); }
|
|
356
|
-
catch { throw failed(executor, "image availability"); }
|
|
357
|
-
if (present.timedOut || present.truncated) throw failed(executor, "image availability");
|
|
358
|
-
if (present.exitCode !== 0) await step(executor, "image pull", "docker", ["pull", image], runner, { timeoutMs: 300_000 });
|
|
474
|
+
await ensureImage(executor, image, runner);
|
|
359
475
|
images.push({ image, available: true });
|
|
360
476
|
}
|
|
361
477
|
return { ...(Object.keys(protocol.inputs ?? {}).length ? { inputRuntime: "python3" as const } : {}), executor, serverVersion: version, user: `${uid}:${gid}`, images, pull: "missing" };
|
package/src/exp/final.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { readDesign, readProtocol, type ProtocolDefinition as Protocol } from ".
|
|
|
5
5
|
import { listAttempts, type Attempt, type AttemptStatus } from "./attempts.ts";
|
|
6
6
|
import { ablateResultPath, ABLATE_BYTES, foldAblations, readClosedAblate } from "./ablate.ts";
|
|
7
7
|
import { INVESTIGATE_BYTES, investigateResultPath, metricValue, pairSamples, readClosedInvestigation, type PairedSamples, type Sample } from "./investigate.ts";
|
|
8
|
-
import { readSelection } from "./selection.ts";
|
|
8
|
+
import { evaluateSelectionConstraints, readSelection, type ConstraintResult } from "./selection.ts";
|
|
9
9
|
|
|
10
10
|
export interface FinalSeeds { v: 1; seeds: number[] }
|
|
11
11
|
export const FINAL_SEEDS_BYTES = 65_536;
|
|
@@ -115,7 +115,7 @@ export function authorizeFinalAttempt(dir: string, commit: string, seed: number)
|
|
|
115
115
|
return { binding: input.binding, auto: approvals.length > 0, winner: input.winner };
|
|
116
116
|
}
|
|
117
117
|
interface FinalAttempt { id: string; commit: string; seed: number; status: AttemptStatus; decisive: boolean; reason?: string; retryOf?: string }
|
|
118
|
-
export interface FinalResult {
|
|
118
|
+
export interface FinalResult extends Omit<ConstraintResult, "reason"> {
|
|
119
119
|
v: 1; status: "qualified" | "not_qualified"; reason?: string; winner: string; baseline: string; seeds: number[];
|
|
120
120
|
pairs: PairedSamples["pairs"]; mean: number | null; baselineMean: number | null; delta: number | null;
|
|
121
121
|
decisive: FinalAttempt[]; attempts: FinalAttempt[]; investigateSha256: string; ablateSha256?: string; sealBinding: string; inputsSha256: string;
|
|
@@ -154,11 +154,20 @@ function calculateFinal(input: ReturnType<typeof requireFinalInputs>): FinalResu
|
|
|
154
154
|
return [{ seed, attempt: a.id, value: metricValue(a, input.investigate.result.metric) }];
|
|
155
155
|
});
|
|
156
156
|
const paired = pairSamples(samples(input.winner), samples(input.baseline), input.investigate.result.metric.direction, input.winner);
|
|
157
|
+
let details: Omit<ConstraintResult, "reason"> = {};
|
|
157
158
|
if (!reason) {
|
|
158
159
|
if (paired.delta === null || paired.delta <= 0 || paired.delta < input.rule.minDelta) reason = "below-margin";
|
|
160
|
+
else if (input.rule.v === 2 && (input.rule.guards?.length || input.rule.cost)) {
|
|
161
|
+
const evaluation = evaluateSelectionConstraints(input.rule, input.design.protocol, paired.pairedSeeds.map(seed => ({
|
|
162
|
+
attempt: chosen.get(`${input.winner}:${seed}`)!, baseline: chosen.get(`${input.baseline}:${seed}`)!,
|
|
163
|
+
})), paired.delta);
|
|
164
|
+
const { reason: rejected, ...measurements } = evaluation;
|
|
165
|
+
reason = rejected;
|
|
166
|
+
details = measurements;
|
|
167
|
+
}
|
|
159
168
|
}
|
|
160
169
|
const result: FinalResult = { v: 1, status: reason ? "not_qualified" : "qualified", ...(reason ? { reason } : {}), winner: input.winner, baseline: input.baseline, seeds: input.final.seeds, pairs: paired.pairs, mean: paired.mean, baselineMean: paired.referenceMean, delta: paired.delta, decisive, attempts: rows, investigateSha256: input.investigate.sha256, ...(input.ablate ? { ablateSha256: input.ablate.sha256 } : {}), sealBinding: input.design.binding,
|
|
161
|
-
inputsSha256: sha256(canonical({ binding: input.binding, attempts: ordered.map(a => ({ record: sha256(canonical(a)), start: starts.get(a.id)?.index ?? null })) })) };
|
|
170
|
+
inputsSha256: sha256(canonical({ binding: input.binding, attempts: ordered.map(a => ({ record: sha256(canonical(a)), start: starts.get(a.id)?.index ?? null })) })), ...details };
|
|
162
171
|
const text = JSON.stringify(result, null, 2) + "\n"; assertWritable(text, FINAL_RESULT_BYTES, "final result; archive the study and start a new bounded run");
|
|
163
172
|
return result;
|
|
164
173
|
}
|