@staix/agent-research 0.2.1 → 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/CHANGELOG.md +107 -0
- package/README.md +255 -24
- package/package.json +2 -2
- package/src/cli.ts +117 -10
- package/src/commands-table.ts +39 -8
- package/src/commands.ts +192 -32
- package/src/exp/attempts.ts +500 -65
- package/src/exp/executor.ts +235 -12
- package/src/exp/final.ts +1 -1
- package/src/exp/logs.ts +25 -12
- package/src/exp/metrics.ts +6 -5
- package/src/exp/pipeline.ts +92 -0
- package/src/exp/protocol.ts +85 -18
- package/src/exp/retention-script.ts +649 -0
- package/src/exp/retention.ts +70 -0
- package/src/exp/reuse-admission.ts +63 -0
- package/src/exp/reuse-contract.ts +48 -0
- package/src/exp/reuse-runtime.ts +87 -0
- package/src/exp/reuse.ts +87 -0
- package/src/exp/selection.ts +1 -1
- package/src/exp/snapshot.ts +3 -3
- package/src/exp/stages.ts +117 -0
- package/src/harness/experience-source.ts +34 -0
- package/src/harness/experience.ts +206 -0
- package/src/harness/hub-guidance.ts +140 -0
- package/src/harness/hub-reference.ts +18 -0
- package/src/harness/lesson-candidates.ts +162 -0
- package/src/harness/limits.ts +2 -0
- package/src/harness/privacy.ts +4 -0
- package/src/harness/receipts.ts +84 -0
- package/src/harness/rounds.ts +198 -0
- package/src/harness/transitions.ts +152 -0
- package/src/lit/candidates.ts +13 -5
- package/src/lit/cards.ts +55 -4
- package/src/lit/flow.ts +82 -0
- package/src/lit/queries.ts +62 -0
- package/src/manifest.ts +13 -6
- package/src/mcp-tools.ts +123 -25
- package/src/mcp.ts +4 -0
- package/src/memory/amem-show.ts +135 -0
- package/src/memory/amem.ts +3 -0
- package/src/memory/archive.ts +17 -8
- package/src/memory/evidence-local.ts +77 -0
- package/src/memory/evidence.ts +39 -0
- package/src/memory/lessons.ts +4 -2
- package/src/memory/skill-check.ts +56 -0
- package/src/memory/skill-format.ts +77 -0
- package/src/memory/skills.ts +72 -26
- package/src/memory/source-budget.ts +11 -0
- package/src/memory/vault-cards.ts +226 -0
- package/src/paper/build.ts +16 -7
- package/src/paper/check.ts +37 -10
- package/src/paper/headings.ts +39 -0
- package/src/paper/hygiene.ts +153 -0
- package/src/paper/placeholders.ts +16 -1
- package/src/paper/plan.ts +170 -0
- package/src/paper/point-evidence.ts +63 -0
- package/src/paper/points.ts +83 -0
- package/src/paper/review.ts +102 -9
- package/src/paper/scopes.ts +51 -0
- package/src/plan/definition.ts +5 -1
- package/src/plan/hub.ts +6 -0
- package/src/plan/state.ts +5 -0
- package/src/playbook.ts +35 -20
- package/src/privacy.ts +9 -0
- package/src/provenance.ts +679 -0
- package/src/scope.ts +24 -3
- package/src/study-export.ts +55 -27
- package/src/study.ts +54 -14
- package/src/ui/panel.css +4 -0
- package/src/ui/panel.js +263 -6
- package/src/ui/plugin.ts +68 -10
package/src/exp/attempts.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { prepareStageReuse } from "./reuse-admission.ts";
|
|
2
|
+
import { executionView, materializePipeline, sealPipeline, pipelinePaths, pipelineInputRoot, type PipelineState, type AttemptReuseState } from "./pipeline.ts";
|
|
3
|
+
import { retainedOperation, RetentionError } from "./retention.ts";
|
|
4
|
+
import { validateStageProtocol } from "./stages.ts";
|
|
1
5
|
import { requireCopilotAccept } from "../copilot.ts";
|
|
2
6
|
import { resolveAutonomy } from "../autonomy.ts";
|
|
3
7
|
import { readFinalSeeds, authorizeFinalAttempt, finalGateBinding, requirePosthocClosed } from "./final.ts";
|
|
@@ -6,25 +10,27 @@ import { hostname } from "node:os";
|
|
|
6
10
|
import { join, posix } from "node:path";
|
|
7
11
|
import { randomUUID } from "node:crypto";
|
|
8
12
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
-
import { boundedText, commit, openStudy, plain, readJsonFile, readTextBounded, requireExperiment, requireGate, sha256, withLock, type Actor, type PendingEvent } from "../study.ts";
|
|
10
|
-
import { designBinding, protocolHash, readDesign, type Protocol } from "./protocol.ts";
|
|
11
|
-
import { buildContainerArgs, checkExecutorInputs, containerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
|
|
13
|
+
import { boundedText, commit, openStudy, plain, readJsonFile, readTextBounded, requireExperiment, requireGate, sha256, withLock, StudyLockBusyError, type Actor, type PendingEvent } from "../study.ts";
|
|
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, containerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
|
|
12
16
|
import { resolveSnapshot, transferSnapshot, transferTask } from "./snapshot.ts";
|
|
13
|
-
import { collectEvaluation as defaultEvaluationCollector, collectStageEvidence as defaultStageCollector, EvidenceError, MetricsError, outputBudget, type StageEvidence } from "./metrics.ts";
|
|
17
|
+
import { collectEvaluation as defaultEvaluationCollector, collectStageEvidence as defaultStageCollector, EvidenceError, MetricsError, OUTPUT_METADATA_BYTES, outputBudget, type StageEvidence } from "./metrics.ts";
|
|
14
18
|
|
|
15
19
|
export type AttemptStatus = "running" | "succeeded" | "failed" | "cancelled" | "unknown";
|
|
16
|
-
export interface AttemptStage { image: string; argv: string[]; mounts: { target: string; readOnly: boolean }[]; network: "none"; limits: Protocol["limits"]; user: string; containerId?: string; startedAt: string; endedAt?: string; exitCode?: number; evidence?: StageEvidence; evidenceError?: { reason: string; message: string } }
|
|
20
|
+
export interface AttemptStage { image: string; argv: string[]; mounts: { target: string; readOnly: boolean }[]; network: "none"; limits: Protocol["limits"]; user: string; containerId?: string; startedAt: string; endedAt?: string; exitCode?: number; evidence?: StageEvidence; evidenceError?: { reason: string; message: string }; launchPending?: true }
|
|
17
21
|
export interface Evaluation { metrics: { name: string; unit: string; value: number; provenance: "ares-observed" }[]; outputs: { path: string; sha256: string; bytes: number }[] }
|
|
18
22
|
export interface Attempt {
|
|
19
|
-
v: 1; id: string; studyId: string; run: string; protocolHash: string; sealBinding: string; commit: string; treeId: string; snapshotSha256?: string; seed: number; label: string; retryOf?: string;
|
|
23
|
+
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;
|
|
20
24
|
executor: Executor; protocol: Protocol; paths: ContainerPaths; status: AttemptStatus; stage: Stage; reason?: string; error?: string; startedAt: string; endedAt?: string;
|
|
21
25
|
stages: Partial<Record<Stage, AttemptStage>>; metrics: Evaluation["metrics"]; outputs: Evaluation["outputs"];
|
|
22
26
|
sealing: { separateContainers: boolean; evaluatorReadOnly: boolean; candidateHasNoEvaluator: boolean; verifiedBy: "ares-observed" };
|
|
23
27
|
launching?: { pid: number; host: string; token: string; claimedAt: string; expiresAt: string };
|
|
28
|
+
verifiedInputs?: Record<string, string>;
|
|
29
|
+
gpuDevices?: string[];
|
|
24
30
|
pendingAutoApproval?: string;
|
|
25
31
|
finalBinding?: string; finalWinner?: string; pendingFinalApproval?: string;
|
|
26
32
|
}
|
|
27
|
-
export interface AttemptOptions { repo: string; commit: string; seed?: number; run?: string; label?: string; retry?: string; detach?: boolean; expectedId?: string }
|
|
33
|
+
export interface AttemptOptions { repo: string; commit: string; seed?: number; run?: string; label?: string; retry?: string; detach?: boolean; expectedId?: string; reuse?: "off" | "eligible"; forceFresh?: boolean }
|
|
28
34
|
/** collectEvaluation is T4's validating adapter; T3 does not parse or validate metric schemas. */
|
|
29
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> }
|
|
30
36
|
export const ATTEMPT_BYTES = 1024 * 1024;
|
|
@@ -69,13 +75,66 @@ function* records(dir: string): Generator<Attempt> {
|
|
|
69
75
|
const path = join(dir, "runs", run, "attempts", name), stat = lstatSync(path);
|
|
70
76
|
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("attempt record: regular file required; restore the record without symlinks");
|
|
71
77
|
const raw = readJsonFile(path, ATTEMPT_BYTES);
|
|
72
|
-
|
|
73
|
-
if (!plain(raw) || raw.v !== 1 || raw.run !== run || raw.id !== name.slice(0, 16) || !STATUSES.includes(raw.status as AttemptStatus) || !["candidate", "evaluator"].includes(raw.stage as string) || !plain(raw.stages) || !plain(raw.protocol) || !plain(raw.executor) || typeof raw.startedAt !== "string" || !Number.isFinite(Date.parse(raw.startedAt))) throw new Error("attempt record: malformed; restore its last valid version before retrying");
|
|
78
|
+
const attempt = validateAttemptRecord(raw, run, name.slice(0, 16));
|
|
74
79
|
if (++count > 1_000_000) throw new Error("attempt store: more than 1000000 records; archive the study and start a new one");
|
|
75
|
-
yield
|
|
80
|
+
yield attempt;
|
|
76
81
|
}
|
|
77
82
|
}
|
|
78
83
|
}
|
|
84
|
+
function reuseMilliseconds(value: unknown): boolean { return typeof value === "number" && Number.isFinite(value) && value >= 0; }
|
|
85
|
+
function reuseContext(value: unknown): boolean {
|
|
86
|
+
if (!plain(value) || typeof value.populationSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.populationSha256) || !plain(value.runtime) || !plain(value.platform)) return false;
|
|
87
|
+
return [value.runtime.semantics, value.runtime.producerVersion, value.platform.os, value.platform.arch, value.platform.abi].every(text => typeof text === "string" && !!text.trim() && Buffer.byteLength(text) <= 128 && !/\p{Cc}/u.test(text));
|
|
88
|
+
}
|
|
89
|
+
function validateReuseState(raw: Record<string, unknown>, definition: import("./stages.ts").ProtocolV2, completed: unknown[], wanted: string, run: string): void {
|
|
90
|
+
const reuse = raw.reuse;
|
|
91
|
+
if (!plain(reuse) || !["off", "eligible"].includes(String(reuse.mode)) || typeof reuse.forceFresh !== "boolean" || !plain(reuse.stages) || Object.keys(reuse.stages).length > 16 || !reuseMilliseconds(reuse.verificationMs) || !reuseMilliseconds(reuse.materializationMs) || (reuse.failureMs !== undefined && !reuseMilliseconds(reuse.failureMs))) throw new Error("reuse: malformed attempt control receipt; restore the last valid attempt record before running ares attempt reconcile <dir>");
|
|
92
|
+
for (const [name, entry] of Object.entries(reuse.stages)) {
|
|
93
|
+
if (!definition.candidate.stages.some(stage => stage.name === name) || !plain(entry) || !["fresh", "reused"].includes(String(entry.outcome)) || typeof entry.reason !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(entry.reason) || !reuseMilliseconds(entry.verificationMs) || !reuseMilliseconds(entry.materializationMs) || (entry.key !== undefined && (typeof entry.key !== "string" || !/^[a-f0-9]{64}$/.test(entry.key) || !reuseContext(entry.context)))) throw new Error("reuse: malformed named stage outcome; restore the last valid attempt record before running ares attempt reconcile <dir>");
|
|
94
|
+
if (entry.outcome === "reused" && !completed.some(parent => plain(parent) && parent.name === name && plain(parent.reuse))) throw new Error("reuse: outcome has no atomic completed-stage receipt; restore the last valid attempt record before running ares attempt reconcile <dir>");
|
|
95
|
+
if (entry.outcome === "fresh" && entry.source !== undefined) throw new Error("reuse: fresh execution cannot carry a reused source; restore the last valid attempt record before running ares attempt reconcile <dir>");
|
|
96
|
+
}
|
|
97
|
+
const measurement = (value: unknown) => value === "unknown" || reuseMilliseconds(value);
|
|
98
|
+
for (const parent of completed) if (plain(parent) && parent.reuse !== undefined) {
|
|
99
|
+
const receipt = parent.reuse, ref = parent.ref, declared = definition.candidate.stages.find(stage => stage.name === parent.name);
|
|
100
|
+
if (reuse.mode !== "eligible" || reuse.forceFresh || ["ablate", "final", "posthoc"].includes(run) || !declared?.reuse || !Object.keys(declared.outputs).length || !plain(ref) || ref.attemptId === wanted || !/^[a-f0-9]{16}$/.test(String(ref.attemptId)) || !plain(receipt) || receipt.v !== 1 || typeof receipt.key !== "string" || !/^[a-f0-9]{64}$/.test(receipt.key) || canonical(receipt.source) !== canonical(ref) || !reuseContext(receipt.context) || !plain(receipt.original) || !measurement(receipt.original.wallSeconds) || !measurement(receipt.original.gpuHours) || receipt.original.cpuSeconds !== "unknown" || !reuseMilliseconds(receipt.verificationMs) || !reuseMilliseconds(receipt.materializationMs)) throw new Error("reuse: malformed source receipt; restore the last valid attempt record before running ares attempt reconcile <dir>");
|
|
101
|
+
const outcome = reuse.stages[parent.name as string];
|
|
102
|
+
if (!plain(outcome) || outcome.outcome !== "reused" || outcome.key !== receipt.key || canonical(outcome.source) !== canonical(ref) || canonical(outcome.context) !== canonical(receipt.context)) throw new Error("reuse: source receipt and admitted outcome differ; restore the last valid attempt record before running ares attempt reconcile <dir>");
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** Shared store validation for provenance snapshots without a second directory traversal. */
|
|
106
|
+
export function validateAttemptRecord(raw: unknown, run: string, wanted: string): Attempt {
|
|
107
|
+
runName(run); id(wanted);
|
|
108
|
+
if (plain(raw) && ((raw.v !== 1 && raw.v !== 2 && raw.v !== 3) || (typeof raw.status === "string" && !STATUSES.includes(raw.status as AttemptStatus)) || (typeof raw.stage === "string" && !["candidate", "evaluator"].includes(raw.stage)))) throw new Error("attempt record: unsupported schema version, status or stage; use an ares version that supports this record, keeping the original file unchanged");
|
|
109
|
+
if (!plain(raw) || (raw.v !== 1 && raw.v !== 2 && raw.v !== 3) || raw.run !== run || raw.id !== wanted || !STATUSES.includes(raw.status as AttemptStatus) || !["candidate", "evaluator"].includes(raw.stage as string) || !plain(raw.stages) || !plain(raw.protocol) || !plain(raw.executor) || typeof raw.startedAt !== "string" || !Number.isFinite(Date.parse(raw.startedAt))) throw new Error("attempt record: malformed; restore its last valid version before retrying");
|
|
110
|
+
if (raw.v === 2 || raw.v === 3) {
|
|
111
|
+
if (!plain(raw.pipeline) || !Number.isSafeInteger(raw.pipeline.index) || !Array.isArray(raw.pipeline.completed)) throw new Error("pipeline: malformed attempt state; restore its last valid record");
|
|
112
|
+
const definition = validateStageProtocol(raw.pipeline.definition);
|
|
113
|
+
if (!plain(raw.pipeline.inputHashes) || typeof raw.pipeline.taskTreeHash !== "string" || !/^[a-f0-9]{64}$/.test(raw.pipeline.taskTreeHash)) throw new Error("pipeline: invalid input snapshot identities");
|
|
114
|
+
if (raw.pipeline.preflightRevision !== undefined && (!Number.isSafeInteger(raw.pipeline.preflightRevision) || (raw.pipeline.preflightRevision as number) < 0)) throw new Error("pipeline: invalid launch revision");
|
|
115
|
+
if (raw.pipeline.reusedSidecarBytes !== undefined && (!reuseMilliseconds(raw.pipeline.reusedSidecarBytes) || (raw.pipeline.reusedSidecarBytes as number) > OUTPUT_METADATA_BYTES)) throw new Error("reuse: invalid retained metadata allowance; restore the last valid attempt record before running ares attempt reconcile <dir>");
|
|
116
|
+
const completed = raw.pipeline.completed;
|
|
117
|
+
if (completed.length !== (raw.pipeline.index as number) + (raw.stage === "evaluator" ? 1 : 0)) throw new Error("pipeline: completed stage receipts do not match current stage");
|
|
118
|
+
for (const [index, parent] of completed.entries()) if (!plain(parent) || parent.name !== definition.candidate.stages[index]?.name || !plain(parent.ref) || (parent.reuse === undefined && parent.ref.attemptId !== wanted) || !/^[a-f0-9]{16}$/.test(String(parent.ref.attemptId)) || parent.ref.stage !== parent.name || typeof parent.ref.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(parent.ref.sha256) || !plain(parent.record) || parent.record.exitCode !== 0 || typeof parent.record.containerId !== "string" || typeof parent.record.endedAt !== "string") throw new Error("pipeline: malformed completed-stage provenance");
|
|
119
|
+
if (canonical(raw.protocol) !== canonical(executionView(definition, raw.pipeline.index as number))) throw new Error("pipeline: execution projection differs from frozen definition");
|
|
120
|
+
if ((raw.pipeline.index as number) < 0 || (raw.pipeline.index as number) >= definition.candidate.stages.length || raw.protocolHash !== protocolHash(definition)) throw new Error("pipeline: invalid frozen identity or stage index");
|
|
121
|
+
if (raw.v === 3) {
|
|
122
|
+
validateReuseState(raw, definition, completed, wanted, run);
|
|
123
|
+
} else if (raw.reuse !== undefined || completed.some(parent => plain(parent) && parent.reuse !== undefined)) throw new Error("reuse: version 3 attempt required; use a compatible ares reader, keeping the original record unchanged");
|
|
124
|
+
} else if (raw.pipeline !== undefined) throw new Error("pipeline: version 2 attempt required");
|
|
125
|
+
if (Object.hasOwn(raw.protocol, "inputs")) {
|
|
126
|
+
const protocol = validateStoredProtocol(raw.protocol);
|
|
127
|
+
const expected = Object.entries(protocol.inputs ?? {}), verified = raw.verifiedInputs;
|
|
128
|
+
if (!plain(verified) || Object.keys(verified).length !== expected.length || expected.some(([name, input]) => verified[name] !== input.sha256)) throw new Error("attempt inputs: verified hashes do not match the frozen input identities; restore the last valid attempt record before retrying");
|
|
129
|
+
}
|
|
130
|
+
if (raw.freshRequest !== undefined && (raw.v !== 1 || !plain(raw.freshRequest) || !["off", "eligible"].includes(String(raw.freshRequest.reuse)) || typeof raw.freshRequest.forceFresh !== "boolean")) throw new Error("attempt request controls: malformed fresh request; restore the last valid record before retrying");
|
|
131
|
+
if (raw.executor.gpu !== undefined && plain(raw.protocol.limits) && typeof raw.protocol.limits.gpus === "number" && raw.protocol.limits.gpus > 0 && raw.gpuDevices === undefined) throw new Error("attempt GPU: frozen assignment missing; restore the chosen GPU UUIDs from the last valid attempt record before retrying");
|
|
132
|
+
if (raw.gpuDevices !== undefined) {
|
|
133
|
+
if (!plain(raw.protocol.limits)) throw new Error("attempt GPU: limits missing; restore the frozen attempt record before retrying");
|
|
134
|
+
validateGpuDevices(raw.gpuDevices, raw.protocol.limits.gpus as number);
|
|
135
|
+
}
|
|
136
|
+
return raw as unknown as Attempt;
|
|
137
|
+
}
|
|
79
138
|
function load(dir: string): Attempt[] { return [...records(dir)]; }
|
|
80
139
|
function studyDir(dirArg: string): string { const { dir, study } = openStudy(dirArg); requireExperiment(study); return dir; }
|
|
81
140
|
/** One pass of regular, byte-bounded records; callers retain only the projections they need. */
|
|
@@ -113,7 +172,9 @@ export function showAttempt(dirArg: string, attemptId: string): Attempt {
|
|
|
113
172
|
return found;
|
|
114
173
|
}
|
|
115
174
|
function save(dir: string, attempt: Attempt, ctx: AttemptContext, event: string, approvals: PendingEvent[] = []): void {
|
|
116
|
-
|
|
175
|
+
if (attempt.pipeline && attempt.status === "running" && Buffer.byteLength(JSON.stringify(attempt, null, 2) + "\n") > ATTEMPT_BYTES - 1024) throw new EvidenceError("artifact-limit", "pipeline: reserve terminal receipt capacity within the 1 MiB attempt record");
|
|
176
|
+
const reused = event === "attempt.stage.reused" ? attempt.pipeline?.completed.at(-1) : undefined;
|
|
177
|
+
commit(dir, [[file(dir, attempt), JSON.stringify(attempt, null, 2) + "\n", ATTEMPT_BYTES]], [...approvals, { actor: ctx.actor, type: event, data: { id: attempt.id, run: attempt.run, stage: attempt.stage, status: attempt.status, ...(attempt.reason ? { reason: attempt.reason } : {}), ...(reused?.reuse ? { candidateStage: reused.name, key: reused.reuse.key, sourceAttemptId: reused.reuse.source.attemptId, sourceStage: reused.reuse.source.stage, sourceSha256: reused.reuse.source.sha256, reuse: reused.reuse } : {}) } }]);
|
|
117
178
|
}
|
|
118
179
|
export function budgetUsage(attempts: Attempt[], time = Date.now()) {
|
|
119
180
|
let wallHours = 0, gpuHours = 0;
|
|
@@ -123,8 +184,7 @@ export function budgetUsage(attempts: Attempt[], time = Date.now()) {
|
|
|
123
184
|
if (!Number.isFinite(elapsed)) throw new Error("attempt timing: malformed; restore valid timestamps before starting an attempt");
|
|
124
185
|
wallHours += elapsed;
|
|
125
186
|
// Unknown kinds cannot be accounted for safely; read-only operations do not call this function.
|
|
126
|
-
for (const
|
|
127
|
-
const stage = attempt.stages[name];
|
|
187
|
+
for (const stage of [...Object.values(attempt.stages), ...(attempt.pipeline?.completed.filter(value => !value.reuse).map(value => value.record) ?? [])]) {
|
|
128
188
|
if (!stage) continue;
|
|
129
189
|
const end = stage.endedAt ? Date.parse(stage.endedAt) : attempt.endedAt ? Date.parse(attempt.endedAt) : time;
|
|
130
190
|
const hours = Math.max(0, end - Date.parse(stage.startedAt)) / 3_600_000;
|
|
@@ -206,23 +266,52 @@ async function command(attempt: Attempt, step: string, executable: string, args:
|
|
|
206
266
|
return result;
|
|
207
267
|
} catch { throw hostError(attempt, step); }
|
|
208
268
|
}
|
|
269
|
+
/** Locators are transient and never copied to an attempt or a second store. */
|
|
270
|
+
function executionProtocol(dir: string, attempt: Attempt): Protocol {
|
|
271
|
+
if (!Object.keys(attempt.protocol.inputs ?? {}).length) return attempt.protocol;
|
|
272
|
+
let current: Protocol | undefined;
|
|
273
|
+
try { const definition = readProtocol(dir); current = definition ? executionView(definition) : undefined; } catch { /* Return safe recovery guidance rather than private parser details. */ }
|
|
274
|
+
if (!current || !sameProtocolInputs(current, attempt.protocol)) throw new InputVerificationError("attempt inputs: current design identities differ from the frozen attempt; restore the matching input names, hashes and mounts in design/protocol.json before reconciling or retrying");
|
|
275
|
+
return { ...attempt.protocol, inputs: current.inputs };
|
|
276
|
+
}
|
|
209
277
|
function stageRecord(attempt: Attempt, stage: Stage, user: string, ctx: AttemptContext): AttemptStage {
|
|
210
|
-
return { image: attempt.protocol[stage].image, argv: attempt.protocol[stage].command, mounts: stage === "candidate" ? [{ target: "/workspace", readOnly: true }, { target: "/out", readOnly: false }] : [{ target: "/eval", readOnly: true }, { target: "/candidate", readOnly: true }, { target: "/result", readOnly: false }], network: "none", limits: attempt.protocol.limits, user, startedAt: at(ctx) };
|
|
278
|
+
return { image: attempt.protocol[stage].image, argv: attempt.protocol[stage].command, mounts: [...(stage === "candidate" ? [{ target: "/workspace", readOnly: true }, { target: "/out", readOnly: false }] : [{ target: "/eval", readOnly: true }, { target: "/candidate", readOnly: true }, { target: "/result", readOnly: false }]), ...(pipelineInputRoot(attempt) ? [{ target: "/in", readOnly: true }] : []), ...Object.values(attempt.protocol.inputs ?? {}).flatMap(input => input.mount[stage] ? [{ target: input.mount[stage]!, readOnly: true }] : [])], network: "none", limits: attempt.protocol.limits, user, startedAt: at(ctx) };
|
|
211
279
|
}
|
|
212
280
|
|
|
213
281
|
/** Validate observed container settings before describing its sealing as ares-observed. */
|
|
214
|
-
function observed(raw: unknown, attempt: Attempt): { id: string; running: boolean; exitCode: number; finishedAt?: string; startedAt?: string } {
|
|
282
|
+
function observed(raw: unknown, attempt: Attempt, protocol: Protocol, ownershipOnly = false): { id: string; running: boolean; exitCode: number; finishedAt?: string; startedAt?: string } {
|
|
215
283
|
const value = Array.isArray(raw) && raw.length === 1 ? raw[0] : undefined;
|
|
216
284
|
if (!plain(value) || typeof value.Id !== "string" || !/^[a-f0-9]{64}$/.test(value.Id) || !plain(value.State) || typeof value.State.Running !== "boolean" || !Number.isSafeInteger(value.State.ExitCode) || !plain(value.Config) || !plain(value.HostConfig) || !Array.isArray(value.Mounts)) throw hostError(attempt, "container inspection");
|
|
217
285
|
const expected = attempt.stages[attempt.stage]!, config = value.Config, settings = value.HostConfig;
|
|
286
|
+
if (ownershipOnly) {
|
|
287
|
+
if (!plain(config.Labels) || config.Labels["ares.study"] !== attempt.studyId || config.Labels["ares.attempt"] !== attempt.id || config.Labels["ares.stage"] !== attempt.stage || (expected?.containerId && value.Id !== expected.containerId)) throw hostError(attempt, "container ownership verification");
|
|
288
|
+
const finishedAt = typeof value.State.FinishedAt === "string" && Number.isFinite(Date.parse(value.State.FinishedAt)) ? value.State.FinishedAt : undefined;
|
|
289
|
+
const startedAt = typeof value.State.StartedAt === "string" && Number.isFinite(Date.parse(value.State.StartedAt)) ? value.State.StartedAt : undefined;
|
|
290
|
+
return { id: value.Id, running: value.State.Running, exitCode: value.State.ExitCode as number, ...(finishedAt ? { finishedAt } : {}), ...(startedAt ? { startedAt } : {}) };
|
|
291
|
+
}
|
|
218
292
|
const mounts = attempt.stage === "candidate" ? [[attempt.paths.snapshot, "/workspace", false], [attempt.paths.output, "/out", true]] : [[attempt.paths.evaluator, "/eval", false], [attempt.paths.output, "/candidate", false], [attempt.paths.result, "/result", true]];
|
|
293
|
+
const inputRoot = pipelineInputRoot(attempt);
|
|
294
|
+
if (inputRoot) mounts.push([inputRoot, "/in", false]);
|
|
219
295
|
const bindMounts = value.Mounts.filter(m => !(plain(m) && m.Type === "tmpfs" && m.Destination === "/tmp"));
|
|
296
|
+
// Input content was verified at launch. A locator relocation must not invalidate an in-flight mount.
|
|
297
|
+
const inputs = Object.values(protocol.inputs ?? {}), visible = inputs.filter(input => input.mount[attempt.stage] !== undefined);
|
|
298
|
+
const privateInputs = inputs.filter(input => input.mount[attempt.stage] === undefined);
|
|
299
|
+
const workspace = Object.values(attempt.paths);
|
|
300
|
+
const inputMountsValid = visible.every(input => {
|
|
301
|
+
const mount = bindMounts.find(m => plain(m) && m.Destination === input.mount[attempt.stage]);
|
|
302
|
+
if (!plain(mount) || mount.Type !== "bind" || mount.RW !== false || typeof mount.Source !== "string" || !mount.Source.startsWith("/") || /[\0\r\n,"]/.test(mount.Source)) return false;
|
|
303
|
+
const source = mount.Source;
|
|
304
|
+
return !workspace.some(path => executionPathsOverlap(source, path)) && !privateInputs.some(other => executionPathsOverlap(source, other.path!));
|
|
305
|
+
});
|
|
220
306
|
const devices = settings.DeviceRequests;
|
|
221
|
-
const
|
|
307
|
+
const capabilitiesMatch = Array.isArray(devices) && devices.length === 1 && plain(devices[0]) && Array.isArray(devices[0].Capabilities) && devices[0].Capabilities.some(c => Array.isArray(c) && c.includes("gpu"));
|
|
308
|
+
const gpuMatches = expected.limits.gpus === 0 ? devices === null || devices === undefined || (Array.isArray(devices) && devices.length === 0)
|
|
309
|
+
: attempt.gpuDevices !== undefined ? capabilitiesMatch && devices[0].Count === 0 && Array.isArray(devices[0].DeviceIDs) && devices[0].DeviceIDs.length === attempt.gpuDevices.length && new Set(devices[0].DeviceIDs).size === attempt.gpuDevices.length && attempt.gpuDevices.every(device => (devices[0].DeviceIDs as unknown[]).includes(device))
|
|
310
|
+
: capabilitiesMatch && devices[0].Count === expected.limits.gpus;
|
|
222
311
|
if (!gpuMatches) throw hostError(attempt, "GPU limit verification");
|
|
223
|
-
if (config.Seed !== `ARES_SEED=${attempt.seed}`) throw hostError(attempt, "selected seed verification");
|
|
224
|
-
if (config.Image !== expected.image || config.User !== expected.user || JSON.stringify(config.Cmd) !== JSON.stringify(expected.argv) || !plain(config.Labels) || config.Labels["ares.study"] !== attempt.studyId || config.Labels["ares.attempt"] !== attempt.id || config.Labels["ares.stage"] !== attempt.stage || settings.NetworkMode !== "none" || settings.ReadonlyRootfs !== true || !Array.isArray(settings.CapDrop) || !settings.CapDrop.some(c => c === "ALL" || c === "all") || !Array.isArray(settings.SecurityOpt) || !settings.SecurityOpt.includes("no-new-privileges") || !plain(settings.Tmpfs) || !("/tmp" in settings.Tmpfs) || settings.Memory !== expected.limits.memoryMb * 1024 * 1024 || settings.PidsLimit !== expected.limits.pidsLimit || settings.NanoCpus !== Math.round(expected.limits.cpus * 1e9) || bindMounts.length !== mounts.length || !mounts.every(([source, target, writable]) => bindMounts.some(m => plain(m) && m.Type === "bind" && m.Source === source && m.Destination === target && m.RW === writable))) throw hostError(attempt, "container isolation verification");
|
|
225
|
-
if (expected
|
|
312
|
+
if (config.Seed !== (attempt.pipeline && attempt.stage === "candidate" && !attempt.pipeline!.definition.candidate.stages[attempt.pipeline!.index]!.seed ? "" : `ARES_SEED=${attempt.seed}`)) throw hostError(attempt, "selected seed verification");
|
|
313
|
+
if (config.Image !== expected.image || config.User !== expected.user || JSON.stringify(config.Cmd) !== JSON.stringify(expected.argv) || !plain(config.Labels) || config.Labels["ares.study"] !== attempt.studyId || config.Labels["ares.attempt"] !== attempt.id || config.Labels["ares.stage"] !== attempt.stage || settings.NetworkMode !== "none" || settings.ReadonlyRootfs !== true || !Array.isArray(settings.CapDrop) || !settings.CapDrop.some(c => c === "ALL" || c === "all") || !Array.isArray(settings.SecurityOpt) || !settings.SecurityOpt.includes("no-new-privileges") || !plain(settings.Tmpfs) || !("/tmp" in settings.Tmpfs) || settings.Memory !== expected.limits.memoryMb * 1024 * 1024 || settings.PidsLimit !== expected.limits.pidsLimit || settings.NanoCpus !== Math.round(expected.limits.cpus * 1e9) || (!inputMountsValid || bindMounts.length !== mounts.length + visible.length) || !mounts.every(([source, target, writable]) => bindMounts.some(m => plain(m) && m.Type === "bind" && m.Source === source && m.Destination === target && m.RW === writable))) throw hostError(attempt, "container isolation verification");
|
|
314
|
+
if (expected?.containerId && value.Id !== expected.containerId) throw hostError(attempt, "container identity verification");
|
|
226
315
|
const finishedAt = typeof value.State.FinishedAt === "string" && Number.isFinite(Date.parse(value.State.FinishedAt)) ? value.State.FinishedAt : undefined;
|
|
227
316
|
const startedAt = typeof value.State.StartedAt === "string" && Number.isFinite(Date.parse(value.State.StartedAt)) ? value.State.StartedAt : undefined;
|
|
228
317
|
return { id: value.Id, running: value.State.Running, exitCode: value.State.ExitCode as number, ...(finishedAt ? { finishedAt } : {}), ...(startedAt ? { startedAt } : {}) };
|
|
@@ -239,7 +328,7 @@ async function recordVerifiedStage(dir: string, attempt: Attempt, state: Observe
|
|
|
239
328
|
if (current.status !== "running" || current.stage !== attempt.stage) return undefined;
|
|
240
329
|
const stage = current.stages[current.stage]!;
|
|
241
330
|
stage.containerId = state.id; if (state.startedAt) stage.startedAt = state.startedAt;
|
|
242
|
-
if (current.reason === "executor-start" || current.reason === "executor-start-uncertain") { delete current.reason; delete current.error; }
|
|
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; }
|
|
243
332
|
delete current.launching;
|
|
244
333
|
if (current.stage === "candidate") {
|
|
245
334
|
current.sealing.candidateHasNoEvaluator = true;
|
|
@@ -254,44 +343,203 @@ async function recordVerifiedStage(dir: string, attempt: Attempt, state: Observe
|
|
|
254
343
|
delete current.pendingAutoApproval; delete current.pendingFinalApproval;
|
|
255
344
|
} else {
|
|
256
345
|
current.sealing.evaluatorReadOnly = true;
|
|
257
|
-
current.sealing.separateContainers = !!current.stages.candidate?.containerId && state.id !== current.stages.candidate.containerId;
|
|
346
|
+
current.sealing.separateContainers = (current.pipeline ? current.pipeline.completed.every(parent => !!parent.record.containerId && state.id !== parent.record.containerId) : !!current.stages.candidate?.containerId && state.id !== current.stages.candidate.containerId);
|
|
258
347
|
}
|
|
259
348
|
return event;
|
|
260
349
|
}, approvals);
|
|
261
350
|
}
|
|
262
|
-
|
|
351
|
+
function attemptContainerName(attempt: Attempt): string {
|
|
352
|
+
const base = containerName(attempt.id, attempt.stage);
|
|
353
|
+
return attempt.pipeline && attempt.stage === "candidate" ? `${base}-${attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name}` : base;
|
|
354
|
+
}
|
|
355
|
+
async function inspect(dir: string, attempt: Attempt, ctx: AttemptContext, ownershipOnly = false) {
|
|
356
|
+
const protocol = ownershipOnly ? attempt.protocol : executionProtocol(dir, attempt);
|
|
263
357
|
let result;
|
|
264
|
-
try { result = await runOnExecutor(attempt.executor, "docker", ["inspect", "--format", INSPECT_FORMAT,
|
|
358
|
+
try { result = await runOnExecutor(attempt.executor, "docker", ["inspect", "--format", INSPECT_FORMAT, attemptContainerName(attempt)], ctx.runner ?? spawnRunner, { maxOutputBytes: ATTEMPT_BYTES }); }
|
|
265
359
|
catch { throw hostError(attempt, "container inspection"); }
|
|
266
360
|
if (result.timedOut || result.truncated) throw hostError(attempt, "container inspection");
|
|
267
361
|
if (result.exitCode === 1) {
|
|
268
362
|
// inspect also exits 1 for daemon outages. Only a successful empty daemon listing confirms absence.
|
|
269
|
-
const probe = await command(attempt, "container absence confirmation", "docker", ["ps", "--all", "--filter", `name=^/${
|
|
363
|
+
const probe = await command(attempt, "container absence confirmation", "docker", ["ps", "--all", "--filter", `name=^/${attemptContainerName(attempt)}$`, "--format", "{{.ID}}"], ctx);
|
|
270
364
|
if (probe.stdout.trim() === "") return undefined;
|
|
271
365
|
throw hostError(attempt, "container inspection");
|
|
272
366
|
}
|
|
273
367
|
if (result.exitCode !== 0) throw hostError(attempt, "container inspection");
|
|
274
368
|
let raw: unknown; try { raw = JSON.parse(result.stdout); } catch { throw hostError(attempt, "container inspection"); }
|
|
275
|
-
return observed(raw, attempt);
|
|
369
|
+
return observed(raw, attempt, protocol, ownershipOnly);
|
|
370
|
+
}
|
|
371
|
+
/** Caller holds a fresh control fence; potentially long input hashing has already completed. */
|
|
372
|
+
const recoveryRunners = new WeakMap<AttemptContext, ProcessRunner>();
|
|
373
|
+
function boundedPipelineContext(dir: string, attempt: Attempt, ctx: AttemptContext): AttemptContext {
|
|
374
|
+
if (!attempt.pipeline) return ctx;
|
|
375
|
+
const runner = ctx.runner ?? spawnRunner;
|
|
376
|
+
const bounded: AttemptContext = { ...ctx, runner: async request => {
|
|
377
|
+
const seconds = remainingWallSeconds(dir, attempt, ctx);
|
|
378
|
+
const result = await runner({ ...request, timeoutMs: Math.min(request.timeoutMs ?? 300_000, seconds * 1000) });
|
|
379
|
+
return result;
|
|
380
|
+
} };
|
|
381
|
+
recoveryRunners.set(bounded, recoveryRunners.get(ctx) ?? runner);
|
|
382
|
+
return bounded;
|
|
383
|
+
}
|
|
384
|
+
function remainingWallSeconds(dir: string, attempt: Attempt, ctx: AttemptContext): number {
|
|
385
|
+
if (!attempt.pipeline) return attempt.protocol.limits.wallSeconds;
|
|
386
|
+
const usage = budgetUsage(load(dir), now(ctx)), budget = attempt.protocol.budget;
|
|
387
|
+
const seconds = Math.floor(Math.min(
|
|
388
|
+
(Date.parse(attempt.startedAt) + attempt.protocol.limits.wallSeconds * 1000 - now(ctx)) / 1000,
|
|
389
|
+
(budget.maxWallHours - usage.wallHours) * 3600,
|
|
390
|
+
attempt.protocol.limits.gpus > 0 ? (budget.maxGpuHours - usage.gpuHours) * 3600 / attempt.protocol.limits.gpus : Infinity,
|
|
391
|
+
));
|
|
392
|
+
if (seconds < 1) throw new EvidenceError("wall-clock", "pipeline: aggregate wall budget exhausted");
|
|
393
|
+
return seconds;
|
|
394
|
+
}
|
|
395
|
+
function pipelineFailure(error: unknown): EvidenceError {
|
|
396
|
+
if (error instanceof EvidenceError) return error;
|
|
397
|
+
const message = error instanceof Error ? error.message : "pipeline verification failed";
|
|
398
|
+
if (/budget exhausted|deadline/i.test(message)) return new EvidenceError("wall-clock", message);
|
|
399
|
+
if (/metadata.*limit|payload.*bound|file.*bound|output budget|reservation exceeded|output.*limit/i.test(message)) return new EvidenceError("artifact-limit", message);
|
|
400
|
+
return new EvidenceError("evidence-read", message);
|
|
401
|
+
}
|
|
402
|
+
function pipelineFailureAt(dir: string, attempt: Attempt, error: unknown, ctx: AttemptContext): EvidenceError {
|
|
403
|
+
try { remainingWallSeconds(dir, attempt, ctx); } catch (budget) { return pipelineFailure(budget); }
|
|
404
|
+
return pipelineFailure(error);
|
|
405
|
+
}
|
|
406
|
+
function retryablePipelineFailure(error: unknown): boolean {
|
|
407
|
+
if (error instanceof RetentionError) return error.retryable;
|
|
408
|
+
const message = error instanceof Error ? error.message : "";
|
|
409
|
+
return /retention operation active|executor operation failed|malformed executor receipt|mismatched executor receipt|process start failed/i.test(message);
|
|
276
410
|
}
|
|
277
|
-
async function
|
|
411
|
+
async function recordPipelinePreflightFailure(dir: string, attempt: Attempt, error: unknown, ctx: AttemptContext, elapsedMs = 0): Promise<Attempt> {
|
|
412
|
+
try { remainingWallSeconds(dir, attempt, ctx); } catch (budget) { error = budget; }
|
|
413
|
+
const failure = pipelineFailure(error), retryable = retryablePipelineFailure(error) && failure.reason !== "wall-clock";
|
|
414
|
+
return update(dir, attempt.id, ctx, current => {
|
|
415
|
+
if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.stages[current.stage]?.containerId) return undefined;
|
|
416
|
+
if ((current.pipeline?.preflightRevision ?? 0) !== (attempt.pipeline?.preflightRevision ?? 0)) return undefined;
|
|
417
|
+
if (attempt.launching) { if (current.launching?.token !== attempt.launching.token) return undefined; }
|
|
418
|
+
else if (!current.stages[current.stage]?.launchPending || current.launching) return undefined;
|
|
419
|
+
current.error = failure.message;
|
|
420
|
+
if (current.reuse) current.reuse.failureMs = (current.reuse.failureMs ?? 0) + elapsedMs;
|
|
421
|
+
delete current.launching;
|
|
422
|
+
if (retryable) {
|
|
423
|
+
current.stages[current.stage]!.launchPending = true; current.reason = "executor-preflight";
|
|
424
|
+
return "attempt.executor-error";
|
|
425
|
+
}
|
|
426
|
+
delete current.stages[current.stage]!.launchPending;
|
|
427
|
+
finish(current, "failed", failure.reason, ctx);
|
|
428
|
+
return "attempt.failed";
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
function addMaterialization(attempt: Attempt, elapsedMs: number): void {
|
|
432
|
+
if (!attempt.reuse || !attempt.pipeline) return;
|
|
433
|
+
const name = attempt.stage === "evaluator" ? "evaluator" : attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name;
|
|
434
|
+
attempt.reuse.materializationMs += elapsedMs;
|
|
435
|
+
(attempt.pipeline.materializationMs ??= {})[name] = (attempt.pipeline.materializationMs?.[name] ?? 0) + elapsedMs;
|
|
436
|
+
}
|
|
437
|
+
async function recordMaterialization(dir: string, attempt: Attempt, elapsedMs: number, ctx: AttemptContext): Promise<Attempt> {
|
|
438
|
+
return update(dir, attempt.id, ctx, current => {
|
|
439
|
+
if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: stage ownership changed during materialization; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
|
|
440
|
+
addMaterialization(current, elapsedMs); return "attempt.reuse.materialized";
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptContext, verifiedProtocol?: Protocol): Promise<Attempt> {
|
|
444
|
+
const preflightStarted = performance.now();
|
|
445
|
+
const recoveryCtx = { ...ctx, runner: recoveryRunners.get(ctx) ?? ctx.runner };
|
|
446
|
+
ctx = boundedPipelineContext(dir, attempt, ctx);
|
|
447
|
+
let args: string[];
|
|
448
|
+
try {
|
|
449
|
+
if (attempt.reuse) {
|
|
450
|
+
attempt = await update(dir, attempt.id, recoveryCtx, current => {
|
|
451
|
+
if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: preflight ownership changed; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
|
|
452
|
+
requireCopilotAccept(dir, "hypotheses");
|
|
453
|
+
if (designBinding(dir) !== current.sealBinding) throw new InputVerificationError("reuse: design changed before preflight; inspect ares gate list <dir>, restore or approve the current design, then run ares attempt reconcile <dir> before retrying");
|
|
454
|
+
requireGate(dir, openStudy(dir).study, "design", () => current.sealBinding);
|
|
455
|
+
if (current.stages[current.stage]!.launchPending) return undefined;
|
|
456
|
+
current.stages[current.stage]!.launchPending = true;
|
|
457
|
+
return "attempt.reuse.preflight";
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
if (attempt.pipeline) {
|
|
461
|
+
if (designBinding(dir) !== attempt.sealBinding) throw new InputVerificationError("pipeline: design changed; restore the frozen approved definition before consumption");
|
|
462
|
+
remainingWallSeconds(dir, attempt, ctx);
|
|
463
|
+
const materialized = await materializePipeline(attempt, ctx), hashes = materialized.inputHashes;
|
|
464
|
+
if (attempt.reuse) attempt = await recordMaterialization(dir, attempt, materialized.materializationMs, ctx);
|
|
465
|
+
remainingWallSeconds(dir, attempt, ctx);
|
|
466
|
+
if (JSON.stringify(hashes) !== JSON.stringify(attempt.pipeline!.inputHashes)) throw new InputVerificationError("pipeline: verified input identities changed before consumption");
|
|
467
|
+
}
|
|
468
|
+
const currentProtocol = executionProtocol(dir, attempt), protocol = attempt.pipeline ? currentProtocol : verifiedProtocol ?? currentProtocol;
|
|
469
|
+
if (!sameProtocolInputs(currentProtocol, protocol)) throw new InputVerificationError("attempt inputs: identities changed after verification; restore the frozen input identities and retry ares attempt reconcile <dir>");
|
|
470
|
+
if (attempt.pipeline && attempt.reuse && attempt.stage === "candidate") {
|
|
471
|
+
requireCopilotAccept(dir, "hypotheses");
|
|
472
|
+
requireGate(dir, openStudy(dir).study, "design", () => designBinding(dir));
|
|
473
|
+
const decision = await prepareStageReuse(dir, attempt, ctx, source => showAttempt(dir, source));
|
|
474
|
+
remainingWallSeconds(dir, attempt, ctx);
|
|
475
|
+
const approvals: PendingEvent[] = [];
|
|
476
|
+
const index = attempt.pipeline.index, name = attempt.pipeline.definition.candidate.stages[index]!.name;
|
|
477
|
+
attempt = await update(dir, attempt.id, ctx, current => {
|
|
478
|
+
if (current.status !== "running" || current.stage !== "candidate" || current.pipeline?.index !== index || current.pipeline.preflightRevision !== attempt.pipeline!.preflightRevision || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: stage ownership changed before admission; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
|
|
479
|
+
if (designBinding(dir) !== current.sealBinding) throw new InputVerificationError("reuse: current design changed before admission; inspect ares gate list <dir>, restore or approve the current design, then run ares attempt reconcile <dir> before retrying");
|
|
480
|
+
requireCopilotAccept(dir, "hypotheses");
|
|
481
|
+
const gate = requireGate(dir, openStudy(dir).study, "design", () => current.sealBinding);
|
|
482
|
+
remainingWallSeconds(dir, current, ctx);
|
|
483
|
+
decision.materializationMs = current.pipeline.materializationMs?.[name] ?? 0;
|
|
484
|
+
if (decision.outcome === "reused") decision.receipt.materializationMs = decision.materializationMs;
|
|
485
|
+
current.reuse!.verificationMs += decision.verificationMs;
|
|
486
|
+
current.reuse!.stages[name] = { outcome: decision.outcome, reason: decision.reason, ...(decision.key ? { key: decision.key, context: decision.context } : {}), verificationMs: decision.verificationMs, materializationMs: decision.materializationMs, ...(decision.outcome === "reused" ? { source: decision.source } : {}) };
|
|
487
|
+
if (decision.outcome === "fresh") return "attempt.reuse.miss";
|
|
488
|
+
const outputs = outputBudget([...current.outputs, ...decision.outputs]);
|
|
489
|
+
const sidecarBytes = (current.pipeline.sidecarBytes ?? 0) + decision.manifestBytes;
|
|
490
|
+
if (Buffer.byteLength(JSON.stringify(outputs, null, 2)) + sidecarBytes > OUTPUT_METADATA_BYTES) throw new EvidenceError("artifact-limit", "reuse: shared output and retained metadata budget exhausted; reduce declared output count or metadata and use ares attempt run <dir> --retry ID");
|
|
491
|
+
current.outputs = outputs; current.pipeline.sidecarBytes = sidecarBytes;
|
|
492
|
+
current.pipeline.reusedSidecarBytes = (current.pipeline.reusedSidecarBytes ?? 0) + decision.manifestBytes;
|
|
493
|
+
current.pipeline.completed.push({ name, record: decision.record, ref: decision.source, reuse: decision.receipt });
|
|
494
|
+
current.sealing.candidateHasNoEvaluator = true;
|
|
495
|
+
if (current.pendingAutoApproval === current.sealBinding) { approvals.push(...gate); delete current.pendingAutoApproval; }
|
|
496
|
+
delete current.stages.candidate;
|
|
497
|
+
if (index + 1 < current.pipeline.definition.candidate.stages.length) { current.pipeline.index++; current.protocol = executionView(current.pipeline.definition, current.pipeline.index); }
|
|
498
|
+
else current.stage = "evaluator";
|
|
499
|
+
current.paths = pipelinePaths(current);
|
|
500
|
+
current.stages[current.stage] = stageRecord(current, current.stage, user, ctx);
|
|
501
|
+
current.stages[current.stage]!.launchPending = true; delete current.launching;
|
|
502
|
+
return "attempt.stage.reused";
|
|
503
|
+
}, approvals);
|
|
504
|
+
if (decision.outcome === "reused") return attempt;
|
|
505
|
+
}
|
|
506
|
+
// Keep configuration refusals outside the uncertain container-start catch.
|
|
507
|
+
args = buildContainerArgs({ protocol, stage: attempt.stage, studyId: openStudy(dir).study.id, attemptId: attempt.id, seed: attempt.seed, user, paths: attempt.paths, ...(attempt.gpuDevices ? { gpuDevices: attempt.gpuDevices } : {}), ...(attempt.pipeline && attempt.stage === "candidate" ? { pipeline: { name: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name, inputRoot: pipelineInputRoot(attempt)!, seed: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.seed } } : {}) });
|
|
508
|
+
if (attempt.reuse) attempt = await update(dir, attempt.id, recoveryCtx, current => {
|
|
509
|
+
if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: container launch ownership changed; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
|
|
510
|
+
requireCopilotAccept(dir, "hypotheses");
|
|
511
|
+
if (designBinding(dir) !== current.sealBinding) throw new InputVerificationError("reuse: design changed before fresh execution; inspect ares gate list <dir>, restore or approve the current design, then run ares attempt reconcile <dir> before retrying");
|
|
512
|
+
requireGate(dir, openStudy(dir).study, "design", () => current.sealBinding);
|
|
513
|
+
delete current.stages[current.stage]!.launchPending;
|
|
514
|
+
return "attempt.reuse.fresh-intent";
|
|
515
|
+
});
|
|
516
|
+
} catch (error) {
|
|
517
|
+
if (attempt.pipeline) return recordPipelinePreflightFailure(dir, attempt, error, recoveryCtx, performance.now() - preflightStarted);
|
|
518
|
+
if (error instanceof InputVerificationError) await update(dir, attempt.id, ctx, current => {
|
|
519
|
+
if (current.status !== "running" || current.stage !== attempt.stage || current.stages[current.stage]?.containerId || current.launching?.token !== attempt.launching?.token) return undefined;
|
|
520
|
+
const stage = current.stages[current.stage]!;
|
|
521
|
+
if (stage.launchPending && !current.launching) return undefined;
|
|
522
|
+
stage.launchPending = true; delete current.launching;
|
|
523
|
+
return "attempt.input-unavailable";
|
|
524
|
+
});
|
|
525
|
+
throw error;
|
|
526
|
+
}
|
|
278
527
|
let startedId: string | undefined;
|
|
279
528
|
try {
|
|
280
|
-
const args = buildContainerArgs({ protocol: attempt.protocol, stage: attempt.stage, studyId: openStudy(dir).study.id, attemptId: attempt.id, seed: attempt.seed, user, paths: attempt.paths });
|
|
281
529
|
const result = await command(attempt, "container start", "docker", args, ctx), cid = result.stdout.trim();
|
|
282
530
|
if (!/^[a-f0-9]{64}$/.test(cid)) throw hostError(attempt, "container start");
|
|
283
531
|
startedId = cid;
|
|
284
532
|
attempt.stages[attempt.stage]!.containerId = cid;
|
|
285
|
-
await startWatchdog(attempt.executor, attempt.id, attempt.stage, attempt
|
|
286
|
-
const state = await inspect(attempt, ctx); if (!state) throw hostError(attempt, "container start verification");
|
|
533
|
+
await startWatchdog(attempt.executor, attempt.id, attempt.stage, remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, cid);
|
|
534
|
+
const state = await inspect(dir, attempt, ctx); if (!state) throw hostError(attempt, "container start verification");
|
|
287
535
|
return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.started");
|
|
288
536
|
} catch {
|
|
289
537
|
if (!startedId) {
|
|
290
538
|
try {
|
|
291
539
|
// A lost response is not proof that Docker rejected the start. Adopt only a verified owned container.
|
|
292
|
-
const state = await inspect(attempt, ctx);
|
|
540
|
+
const state = await inspect(dir, attempt, ctx);
|
|
293
541
|
if (state) {
|
|
294
|
-
if (state.running) await startWatchdog(attempt.executor, attempt.id, attempt.stage, attempt
|
|
542
|
+
if (state.running) await startWatchdog(attempt.executor, attempt.id, attempt.stage, remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, state.id);
|
|
295
543
|
return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered");
|
|
296
544
|
}
|
|
297
545
|
} catch {
|
|
@@ -300,7 +548,7 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
|
|
|
300
548
|
}
|
|
301
549
|
// A name conflict can belong to another study with the same identity. Only clean up our returned container id.
|
|
302
550
|
if (startedId) {
|
|
303
|
-
try { await command(attempt, "failed launch cleanup", "docker", ["kill", startedId],
|
|
551
|
+
try { await command(attempt, "failed launch cleanup", "docker", ["kill", startedId], recoveryCtx); }
|
|
304
552
|
catch { return update(dir, attempt.id, ctx, current => { delete current.launching; current.reason = "executor-start"; current.error = hostError(current, "failed start cleanup").message; return "attempt.executor-error"; }); }
|
|
305
553
|
}
|
|
306
554
|
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"; });
|
|
@@ -322,7 +570,16 @@ async function captureStage(dir: string, attempt: Attempt, ctx: AttemptContext,
|
|
|
322
570
|
}
|
|
323
571
|
}
|
|
324
572
|
|
|
573
|
+
function existingReuseControls(attempt: Attempt, options: AttemptOptions): Attempt {
|
|
574
|
+
const recordedMode = attempt.v === 3 ? attempt.reuse!.mode : attempt.freshRequest?.reuse ?? "off", recordedForceFresh = attempt.v === 3 ? attempt.reuse!.forceFresh : attempt.freshRequest?.forceFresh ?? false;
|
|
575
|
+
if ((options.reuse ?? "off") !== recordedMode || (options.forceFresh ?? false) !== recordedForceFresh) throw new Error(`attempt: existing identity recorded reuse=${recordedMode}, forceFresh=${recordedForceFresh}; resend those controls or use --retry ${attempt.id} for an explicit new attempt`);
|
|
576
|
+
return attempt;
|
|
577
|
+
}
|
|
325
578
|
export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: AttemptContext): Promise<Attempt> {
|
|
579
|
+
if (options.reuse !== undefined && options.reuse !== "off" && options.reuse !== "eligible") throw new Error("reuse: choose off or eligible; select --reuse off|eligible (MCP reuse) and retry");
|
|
580
|
+
if (options.forceFresh !== undefined && typeof options.forceFresh !== "boolean") throw new Error("force-fresh: boolean required; set forceFresh to true/false or use the CLI --force-fresh flag, then retry");
|
|
581
|
+
const controlCtx = ctx;
|
|
582
|
+
const cleanupRunner = ctx.runner ?? spawnRunner;
|
|
326
583
|
const dir = studyDir(dirArg), { study } = openStudy(dir);
|
|
327
584
|
const frozen = await withLock(dir, () => {
|
|
328
585
|
requireCopilotAccept(dir, "hypotheses");
|
|
@@ -331,7 +588,7 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
|
|
|
331
588
|
if (!executor) throw new Error("executor: missing; run ares executor set <dir> --kind local|ssh --workdir PATH before attempt run");
|
|
332
589
|
return { ...design, executor, finalSeeds: readFinalSeeds(dir, design.protocol) };
|
|
333
590
|
});
|
|
334
|
-
const
|
|
591
|
+
const definition = frozen.protocol, protocol = executionView(definition), executor = frozen.executor;
|
|
335
592
|
if (!/^[A-Za-z0-9_-]{1,80}$/.test(study.id)) throw new Error("study id: invalid; restore the id generated by ares init before attempt run");
|
|
336
593
|
const run = runName(options.run ?? "main"), label = boundedText(options.label ?? "baseline", "label", 128), seed = options.seed ?? protocol.seeds[0]!;
|
|
337
594
|
if (!Number.isSafeInteger(seed) || !protocol.seeds.includes(seed)) throw new Error("seed: undeclared; choose a seed from protocol.seeds");
|
|
@@ -340,40 +597,79 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
|
|
|
340
597
|
const finalAuthorization = run === "final" ? await withLock(dir, () => authorizeFinalAttempt(dir, options.commit, seed)) : undefined;
|
|
341
598
|
if (options.retry !== undefined) id(options.retry);
|
|
342
599
|
const initialBinding = frozen.binding;
|
|
343
|
-
const snapshot = await resolveSnapshot(options.repo, options.commit, ctx.runner ?? spawnRunner), hash = protocolHash(
|
|
600
|
+
const snapshot = await resolveSnapshot(options.repo, options.commit, ctx.runner ?? spawnRunner), hash = protocolHash(definition);
|
|
344
601
|
const wanted = attemptId(hash, snapshot.commit, snapshot.treeId, seed, run, options.retry);
|
|
345
602
|
if (options.expectedId !== undefined && wanted !== options.expectedId) throw new Error("attempt identity: changed since plan intent; reconcile the plan node before retrying");
|
|
346
|
-
|
|
347
|
-
|
|
603
|
+
const inputRoot = posix.join(executor.workdir, study.id, wanted);
|
|
604
|
+
validateContainerInputSources(protocol, { snapshot: posix.join(inputRoot, "snapshot"), output: posix.join(inputRoot, "output"), evaluator: posix.join(inputRoot, "task", "evaluator"), result: posix.join(inputRoot, "result") });
|
|
605
|
+
const existingAttempt = await withLock(dir, () => load(dir).find(a => a.id === wanted)), existing = existingAttempt !== undefined;
|
|
606
|
+
if (existingAttempt) existingReuseControls(existingAttempt, options);
|
|
607
|
+
const verifiedInputs = !existing && protocol.inputs !== undefined ? await verifyExecutorInputs(executor, protocol, ctx.runner ?? spawnRunner) : undefined;
|
|
608
|
+
let gpuDevices: string[] | undefined;
|
|
609
|
+
if (!existing && executor.gpu && protocol.limits.gpus > 0) {
|
|
610
|
+
const admission = await probeGpuAdmission(executor, protocol.limits.gpus, ctx.runner ?? spawnRunner);
|
|
611
|
+
if (admission.status === "deferred") {
|
|
612
|
+
// An overlapping duplicate may have admitted the same identity during this read-only probe.
|
|
613
|
+
const duplicate = await withLock(dir, () => load(dir).find(attempt => attempt.id === wanted));
|
|
614
|
+
if (duplicate) return duplicate;
|
|
615
|
+
throw new GpuAdmissionDeferred(admission);
|
|
616
|
+
}
|
|
617
|
+
gpuDevices = admission.devices;
|
|
618
|
+
}
|
|
619
|
+
let created = false, reserved = false;
|
|
620
|
+
let attempt: Attempt;
|
|
621
|
+
try { attempt = await withLock(dir, async () => {
|
|
348
622
|
requireCopilotAccept(dir, "hypotheses");
|
|
349
623
|
if (run === "posthoc") requirePosthocClosed(dir);
|
|
350
624
|
if (finalAuthorization && authorizeFinalAttempt(dir, options.commit, seed).binding !== finalAuthorization.binding) throw new Error("final inputs changed during snapshot resolution; approve the current final gate before retrying");
|
|
351
|
-
const attempts = load(dir), existing = attempts.find(a => a.id === wanted); if (existing) return existing;
|
|
625
|
+
const attempts = load(dir), existing = attempts.find(a => a.id === wanted); if (existing) return existingReuseControls(existing, options);
|
|
352
626
|
if (designBinding(dir) !== initialBinding) throw new Error("design: changed while resolving the snapshot; approve the current design and retry attempt run");
|
|
353
627
|
if (options.retry && !attempts.some(a => a.id === options.retry)) throw new Error("retry: attempt not found; choose an existing id from ares attempt list");
|
|
354
628
|
if (attempts.some(a => a.status === "running")) throw new Error("attempt: another attempt is running; reconcile or cancel it before starting a new one");
|
|
355
629
|
const binding = designBinding(dir), approval = requireGate(dir, openStudy(dir).study, "design", () => binding);
|
|
356
630
|
enforceBudget(protocol, attempts, now(ctx));
|
|
631
|
+
if (definition.v === 2) { await retainedOperation(executor, { op: "reserve", studyId: study.id, attemptId: wanted, ...(executor.retentionCapBytes === undefined ? {} : { capBytes: executor.retentionCapBytes }) }, cleanupRunner); reserved = true; }
|
|
357
632
|
const root = posix.join(executor.workdir, study.id, wanted);
|
|
358
|
-
const
|
|
633
|
+
const controlled = definition.v === 2 && (options.reuse === "eligible" || options.forceFresh === true);
|
|
634
|
+
const record: Attempt = { v: controlled ? 3 : definition.v, ...(definition.v === 1 && (options.reuse !== undefined || options.forceFresh !== undefined) ? { freshRequest: { reuse: options.reuse ?? "off", forceFresh: options.forceFresh ?? false } } : {}), ...(controlled ? { reuse: { mode: options.reuse ?? "off", forceFresh: options.forceFresh ?? false, stages: {}, verificationMs: 0, materializationMs: 0, failureMs: 0 } } : {}), ...(definition.v === 2 ? { pipeline: { definition, index: 0, completed: [], inputHashes: {}, taskTreeHash: frozen.treeHash } } : {}), id: wanted, studyId: study.id, run, protocolHash: hash, sealBinding: binding!, ...snapshot, seed, label, ...(options.retry ? { retryOf: options.retry } : {}), executor, ...(gpuDevices ? { gpuDevices } : {}), protocol: frozenProtocol(protocol), ...(verifiedInputs !== undefined ? { verifiedInputs } : {}), paths: { snapshot: posix.join(root, "snapshot"), output: posix.join(root, "output"), evaluator: posix.join(root, "task", "evaluator"), result: posix.join(root, "result") }, status: "running", stage: "candidate", startedAt: at(ctx), stages: {}, metrics: [], outputs: [], sealing: { separateContainers: false, evaluatorReadOnly: false, candidateHasNoEvaluator: false, verifiedBy: "ares-observed" }, launching: owner(ctx) };
|
|
635
|
+
if (record.pipeline) record.paths = pipelinePaths(record);
|
|
359
636
|
if (approval.length) record.pendingAutoApproval = binding!;
|
|
360
637
|
if (finalAuthorization) { record.finalBinding = finalAuthorization.binding; record.finalWinner = finalAuthorization.winner; if (finalAuthorization.auto) record.pendingFinalApproval = finalAuthorization.binding; }
|
|
361
638
|
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 } }]);
|
|
362
639
|
created = true; return record;
|
|
363
|
-
});
|
|
640
|
+
}); } catch (error) {
|
|
641
|
+
if (reserved) await withLock(dir, async () => {
|
|
642
|
+
if (!load(dir).some(record => record.id === wanted)) await retainedOperation(executor, { op: "release", studyId: study.id, attemptId: wanted }, cleanupRunner);
|
|
643
|
+
});
|
|
644
|
+
throw error;
|
|
645
|
+
}
|
|
646
|
+
if (attempt.pipeline) ctx = boundedPipelineContext(dir, attempt, ctx);
|
|
364
647
|
if (created) {
|
|
365
648
|
let preparationStep = "executor check";
|
|
366
649
|
try {
|
|
367
|
-
const checked = await checkExecutorInputs(attempt.executor, attempt
|
|
650
|
+
const checked = await checkExecutorInputs(attempt.executor, executionProtocol(dir, attempt), ctx.runner ?? spawnRunner);
|
|
368
651
|
const root = posix.dirname(attempt.paths.snapshot), studyRoot = posix.dirname(root), base = executor.workdir;
|
|
369
652
|
// Require a private, owned, physical root. Attempt mkdir is exclusive, never a shared pre-existing directory.
|
|
370
|
-
const
|
|
653
|
+
const stageDirectories = attempt.pipeline ? attempt.pipeline.definition.candidate.stages.map(stage => posix.join(root, "stages", stage.name, "output")) : [];
|
|
654
|
+
const script = `set -eu; umask 077; base=${shellQuote(base)}; test -d "$base"; test ! -L "$base"; test -O "$base"; test "$(cd -P "$base" && pwd -P)" = "$base"; mode=$(stat -c %a "$base" 2>/dev/null || stat -f %Lp "$base"); test "$mode" = 700; study=${shellQuote(studyRoot)}; if test ! -e "$study"; then mkdir -m 700 "$study"; fi; test -d "$study"; test ! -L "$study"; test -O "$study"; mode=$(stat -c %a "$study" 2>/dev/null || stat -f %Lp "$study"); test "$mode" = 700; mkdir -m 700 ${shellQuote(root)}; mkdir -p -m 700 ${stageDirectories.length ? stageDirectories.map(shellQuote).join(" ") : shellQuote(posix.join(root, "stages"))}; mkdir -m 700 ${[attempt.paths.snapshot, ...(!attempt.pipeline ? [attempt.paths.output] : []), attempt.paths.result, posix.dirname(attempt.paths.evaluator)].map(shellQuote).join(" ")}`;
|
|
371
655
|
preparationStep = "private workspace preparation";
|
|
372
656
|
await command(attempt, "private workspace preparation", "sh", ["-c", script], ctx);
|
|
373
657
|
preparationStep = "snapshot transfer";
|
|
374
658
|
const transferred = await transferSnapshot(options.repo, snapshot.commit, executor, attempt.paths.snapshot, ctx.runner ?? spawnRunner);
|
|
659
|
+
if (attempt.pipeline) {
|
|
660
|
+
preparationStep = "code snapshot verification";
|
|
661
|
+
const receipt = await retainedOperation(attempt.executor, { op: "snapshot", studyId: attempt.studyId, attemptId: attempt.id, source: attempt.paths.snapshot }, ctx.runner ?? spawnRunner);
|
|
662
|
+
if (!receipt.sha256 || !/^[a-f0-9]{64}$/.test(receipt.sha256)) throw new Error("pipeline: invalid frozen code snapshot receipt");
|
|
663
|
+
attempt = await update(dir, attempt.id, ctx, current => { current.pipeline!.codeSnapshotHash = receipt.sha256; return "attempt.pipeline.code"; });
|
|
664
|
+
}
|
|
375
665
|
preparationStep = "evaluator transfer";
|
|
376
|
-
await transferTask(join(dir, "task"), executor, posix.dirname(attempt.paths.evaluator), ctx.runner ?? spawnRunner, frozen.treeHash);
|
|
666
|
+
await transferTask(join(dir, "task"), executor, posix.dirname(attempt.paths.evaluator), ctx.runner ?? spawnRunner, frozen.treeHash, !!attempt.pipeline);
|
|
667
|
+
if (attempt.pipeline) {
|
|
668
|
+
for (let index = 1; index < attempt.pipeline.definition.candidate.stages.length; index++) await checkExecutorInputs(executor, executionView(attempt.pipeline.definition, index), ctx.runner ?? spawnRunner);
|
|
669
|
+
const materialized = await materializePipeline(attempt, ctx);
|
|
670
|
+
if (attempt.reuse) attempt = await recordMaterialization(dir, attempt, materialized.materializationMs, ctx);
|
|
671
|
+
attempt = await update(dir, attempt.id, ctx, current => { current.pipeline!.inputHashes = materialized.inputHashes; return "attempt.pipeline.inputs"; });
|
|
672
|
+
}
|
|
377
673
|
preparationStep = "design recheck";
|
|
378
674
|
if (designBinding(dir) !== attempt.sealBinding) throw new Error("design changed during preparation");
|
|
379
675
|
if (attempt.finalBinding && finalGateBinding(dir) !== attempt.finalBinding) throw new Error("final inputs changed during preparation");
|
|
@@ -383,40 +679,93 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
|
|
|
383
679
|
attempt = await withControl(dir, async () => {
|
|
384
680
|
const current = showAttempt(dir, attempt.id);
|
|
385
681
|
if (current.status !== "running" || current.launching?.token !== claim) return current;
|
|
386
|
-
return launch(dir, current, checked.user, ctx);
|
|
682
|
+
return launch(dir, current, checked.user, ctx, protocol);
|
|
387
683
|
});
|
|
388
|
-
} catch {
|
|
389
|
-
|
|
684
|
+
} catch (error) {
|
|
685
|
+
if (!attempt.pipeline && error instanceof InputVerificationError) throw error;
|
|
686
|
+
const failure = attempt.pipeline ? pipelineFailureAt(dir, attempt, error, controlCtx) : undefined;
|
|
687
|
+
attempt = await update(dir, attempt.id, ctx, current => { if (current.status !== "running") return undefined; current.error = failure ? `${preparationStep}: ${failure.message}` : startupError(current, preparationStep); finish(current, "failed", failure?.reason ?? "preparation", ctx); return "attempt.failed"; });
|
|
390
688
|
}
|
|
391
689
|
}
|
|
690
|
+
if (attempt.pipeline && attempt.status === "failed") await reconcileRetentionReservations(dir, controlCtx);
|
|
392
691
|
if (!options.detach) {
|
|
393
692
|
let delay = 1000;
|
|
394
693
|
while (attempt.status === "running") {
|
|
395
694
|
await (ctx.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))))(delay);
|
|
396
695
|
const previousStage = attempt.stage;
|
|
397
|
-
await reconcileAttempts(dir,
|
|
696
|
+
await reconcileAttempts(dir, controlCtx); attempt = showAttempt(dir, wanted);
|
|
398
697
|
delay = attempt.stage === previousStage ? Math.min(delay * 2, 30_000) : 1000;
|
|
399
698
|
}
|
|
400
699
|
}
|
|
401
700
|
return attempt;
|
|
402
701
|
}
|
|
403
702
|
|
|
703
|
+
async function verifyAndLaunchPending(dir: string, pending: Attempt, ctx: AttemptContext): Promise<Attempt | undefined> {
|
|
704
|
+
ctx = boundedPipelineContext(dir, pending, ctx);
|
|
705
|
+
const protocol = executionProtocol(dir, pending);
|
|
706
|
+
let hashes: Record<string, string> | undefined, materializationMs = 0;
|
|
707
|
+
const preflightStarted = performance.now();
|
|
708
|
+
try {
|
|
709
|
+
if (pending.reuse) {
|
|
710
|
+
requireCopilotAccept(dir, "hypotheses");
|
|
711
|
+
if (designBinding(dir) !== pending.sealBinding) throw new InputVerificationError("reuse: design changed before pending consumption; inspect ares gate list <dir>, restore or approve the current design, then run ares attempt reconcile <dir> before retrying");
|
|
712
|
+
requireGate(dir, openStudy(dir).study, "design", () => pending.sealBinding);
|
|
713
|
+
}
|
|
714
|
+
const materialized = pending.pipeline ? await materializePipeline(pending, ctx) : undefined;
|
|
715
|
+
hashes = materialized?.inputHashes; materializationMs = materialized?.materializationMs ?? 0;
|
|
716
|
+
validateContainerInputSources(protocol, pending.paths);
|
|
717
|
+
await verifyExecutorInputs(pending.executor, protocol, ctx.runner ?? spawnRunner);
|
|
718
|
+
} catch (error) {
|
|
719
|
+
if (!pending.pipeline) throw error;
|
|
720
|
+
return withControl(dir, () => recordPipelinePreflightFailure(dir, pending, error, ctx, performance.now() - preflightStarted));
|
|
721
|
+
}
|
|
722
|
+
return withControl(dir, async () => {
|
|
723
|
+
const current = showAttempt(dir, pending.id);
|
|
724
|
+
if (current.status !== "running" || current.stage !== pending.stage || !current.stages[current.stage]?.launchPending || alive(current, ctx)) return undefined;
|
|
725
|
+
if (pending.pipeline && (current.pipeline?.index !== pending.pipeline.index || current.protocolHash !== pending.protocolHash || (current.pipeline?.preflightRevision ?? 0) !== (pending.pipeline.preflightRevision ?? 0) || canonical(current.protocol) !== canonical(protocol))) return undefined;
|
|
726
|
+
executionProtocol(dir, current); // Recheck the frozen identities after hashing, under the fresh launch fence.
|
|
727
|
+
const claimed = await update(dir, current.id, ctx, value => {
|
|
728
|
+
if (hashes) value.pipeline!.inputHashes = hashes;
|
|
729
|
+
if (value.reuse) addMaterialization(value, materializationMs);
|
|
730
|
+
if (value.pipeline) value.pipeline.preflightRevision = (value.pipeline.preflightRevision ?? 0) + 1;
|
|
731
|
+
delete value.stages[value.stage]!.launchPending; value.launching = owner(ctx);
|
|
732
|
+
return "attempt.stage.retry-intent";
|
|
733
|
+
});
|
|
734
|
+
return launch(dir, claimed, claimed.stages[claimed.stage]!.user, ctx, protocol);
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
|
|
404
738
|
export async function reconcileAttempts(dirArg: string, ctx: AttemptContext): Promise<Attempt[]> {
|
|
405
739
|
const dir = studyDir(dirArg);
|
|
406
|
-
|
|
740
|
+
const pending: Attempt[] = [];
|
|
741
|
+
const changed = await withControl(dir, async () => {
|
|
407
742
|
const changed: Attempt[] = [];
|
|
408
743
|
for (let attempt of load(dir).filter(a => a.status === "running")) {
|
|
409
744
|
if (alive(attempt, ctx)) continue;
|
|
745
|
+
let observedState: ObservedStage | undefined;
|
|
410
746
|
try {
|
|
411
|
-
let state = await inspect(attempt, ctx);
|
|
412
|
-
|
|
747
|
+
let state = await inspect(dir, attempt, ctx);
|
|
748
|
+
observedState = state;
|
|
749
|
+
if (!state) {
|
|
750
|
+
if (attempt.stages[attempt.stage]?.launchPending) pending.push(attempt);
|
|
751
|
+
else changed.push(await update(dir, attempt.id, ctx, current => { finish(current, "unknown", "lost", ctx); return "attempt.unknown"; }));
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
413
754
|
const recovered = needsReceipt(attempt, state);
|
|
414
755
|
if (recovered) attempt = await recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered");
|
|
415
756
|
const stage = attempt.stages[attempt.stage];
|
|
416
757
|
if (!stage) throw hostError(attempt, "stage record");
|
|
417
|
-
const deadline = Date.parse(stage.startedAt) + stage.limits.wallSeconds * 1000;
|
|
418
|
-
|
|
419
|
-
|
|
758
|
+
const deadline = (attempt.pipeline ? Date.parse(attempt.startedAt) : Date.parse(stage.startedAt)) + stage.limits.wallSeconds * 1000;
|
|
759
|
+
const usage = attempt.pipeline ? budgetUsage(load(dir), now(ctx)) : undefined;
|
|
760
|
+
const exhausted = usage && (usage.wallHours >= attempt.protocol.budget.maxWallHours || (attempt.protocol.limits.gpus > 0 && usage.gpuHours >= attempt.protocol.budget.maxGpuHours));
|
|
761
|
+
if ((state.running && (now(ctx) >= deadline || exhausted)) || (!state.running && ((attempt.pipeline && (now(ctx) >= deadline || exhausted)) || (state.finishedAt !== undefined && Date.parse(state.finishedAt) >= deadline)))) {
|
|
762
|
+
if (state.running) {
|
|
763
|
+
await command(attempt, "wall-clock kill", "docker", ["kill", state.id], ctx);
|
|
764
|
+
const stopped = await inspect(dir, attempt, ctx);
|
|
765
|
+
if (stopped) state = stopped;
|
|
766
|
+
else if (attempt.pipeline) state = { ...state, running: false, exitCode: 137, finishedAt: at(ctx) };
|
|
767
|
+
if (attempt.pipeline && state.running) throw new EvidenceError("executor-stop", "pipeline: container termination is not yet observed; active attempt and retention reservation remain held");
|
|
768
|
+
}
|
|
420
769
|
attempt = await captureStage(dir, attempt, ctx, true);
|
|
421
770
|
const ended = state;
|
|
422
771
|
changed.push(await update(dir, attempt.id, ctx, current => { if (ended.finishedAt) current.stages[current.stage]!.endedAt = ended.finishedAt; if (!ended.running) current.stages[current.stage]!.exitCode = ended.exitCode; finish(current, "failed", "wall-clock", ctx); return "attempt.failed"; })); continue;
|
|
@@ -426,36 +775,110 @@ export async function reconcileAttempts(dirArg: string, ctx: AttemptContext): Pr
|
|
|
426
775
|
continue;
|
|
427
776
|
}
|
|
428
777
|
if (state.exitCode !== 0) { attempt = await captureStage(dir, attempt, ctx, true); const ended = state; changed.push(await update(dir, attempt.id, ctx, current => { current.stages[current.stage]!.exitCode = ended.exitCode; if (ended.finishedAt) current.stages[current.stage]!.endedAt = ended.finishedAt; finish(current, "failed", `${current.stage}-exit`, ctx); return "attempt.failed"; })); continue; }
|
|
429
|
-
try { attempt = await captureStage(dir, attempt, ctx, false); }
|
|
778
|
+
try { attempt = await captureStage(dir, attempt, boundedPipelineContext(dir, attempt, ctx), false); }
|
|
430
779
|
catch (error) {
|
|
431
|
-
const failure = error as EvidenceError, ended = state;
|
|
780
|
+
const failure = attempt.pipeline ? pipelineFailureAt(dir, attempt, error, ctx) : error as EvidenceError, ended = state;
|
|
432
781
|
changed.push(await update(dir, attempt.id, ctx, current => {
|
|
433
782
|
current.stages[current.stage]!.exitCode = ended.exitCode;
|
|
434
783
|
if (ended.finishedAt) current.stages[current.stage]!.endedAt = ended.finishedAt;
|
|
435
784
|
current.error = failure.message; finish(current, "failed", failure.reason, ctx); return "attempt.failed";
|
|
436
785
|
})); continue;
|
|
437
786
|
}
|
|
438
|
-
if (attempt.stage === "candidate") {
|
|
439
|
-
|
|
440
|
-
|
|
787
|
+
if (attempt.stage === "candidate" && attempt.pipeline) {
|
|
788
|
+
attempt = await update(dir, attempt.id, ctx, current => { current.stages.candidate!.exitCode = 0; current.stages.candidate!.endedAt = state.finishedAt ?? at(ctx); return "attempt.stage.terminated"; });
|
|
789
|
+
const ref = await sealPipeline(attempt, boundedPipelineContext(dir, attempt, ctx));
|
|
790
|
+
const next = await update(dir, attempt.id, ctx, current => {
|
|
791
|
+
const pipeline = current.pipeline!, completed = current.stages.candidate!;
|
|
792
|
+
pipeline.sidecarBytes = attempt.pipeline!.sidecarBytes;
|
|
793
|
+
pipeline.completed.push({ name: pipeline.definition.candidate.stages[pipeline.index]!.name, record: completed, ref });
|
|
794
|
+
delete current.stages.candidate;
|
|
795
|
+
if (pipeline.index + 1 < pipeline.definition.candidate.stages.length) { pipeline.index++; current.protocol = executionView(pipeline.definition, pipeline.index); }
|
|
796
|
+
else current.stage = "evaluator";
|
|
797
|
+
current.paths = pipelinePaths(current);
|
|
798
|
+
current.stages[current.stage] = stageRecord(current, current.stage, stage.user, ctx);
|
|
799
|
+
current.stages[current.stage]!.launchPending = true; delete current.launching;
|
|
800
|
+
return "attempt.stage.changed";
|
|
801
|
+
});
|
|
802
|
+
pending.push(next);
|
|
803
|
+
} else if (attempt.stage === "candidate") {
|
|
804
|
+
const next = await update(dir, attempt.id, ctx, current => {
|
|
805
|
+
current.stages.candidate!.exitCode = 0; current.stages.candidate!.endedAt = state.finishedAt ?? at(ctx); current.stage = "evaluator";
|
|
806
|
+
current.stages.evaluator = stageRecord(current, "evaluator", stage.user, ctx);
|
|
807
|
+
if (Object.keys(current.protocol.inputs ?? {}).length) { current.stages.evaluator.launchPending = true; delete current.launching; }
|
|
808
|
+
else current.launching = owner(ctx);
|
|
809
|
+
return "attempt.stage.changed";
|
|
810
|
+
});
|
|
811
|
+
if (next.stages.evaluator?.launchPending) pending.push(next);
|
|
812
|
+
else changed.push(await launch(dir, next, stage.user, ctx));
|
|
441
813
|
} else {
|
|
442
814
|
let evaluation: Evaluation | undefined, failure: EvidenceError | undefined;
|
|
443
|
-
try {
|
|
444
|
-
|
|
815
|
+
try {
|
|
816
|
+
const bounded = boundedPipelineContext(dir, attempt, ctx);
|
|
817
|
+
evaluation = await (ctx.collectEvaluation ?? defaultEvaluationCollector)(attempt, bounded.runner ?? spawnRunner);
|
|
818
|
+
if (attempt.pipeline) remainingWallSeconds(dir, attempt, ctx);
|
|
819
|
+
}
|
|
820
|
+
catch (error) {
|
|
821
|
+
evaluation = undefined;
|
|
822
|
+
if (attempt.pipeline) failure = pipelineFailureAt(dir, attempt, error, ctx);
|
|
823
|
+
else failure = error instanceof EvidenceError ? error : new MetricsError("invalid-metrics", "evaluator result validation failed");
|
|
824
|
+
}
|
|
445
825
|
changed.push(await update(dir, attempt.id, ctx, current => {
|
|
446
826
|
current.stages.evaluator!.exitCode = 0;
|
|
447
827
|
if (state.finishedAt) current.stages.evaluator!.endedAt = state.finishedAt;
|
|
448
828
|
if (!evaluation) { const rejected = failure ?? new MetricsError("invalid-metrics", "the collector returned no result"); current.error = rejected.message; finish(current, "failed", rejected.reason, ctx); return "attempt.failed"; }
|
|
829
|
+
if (current.pipeline && Buffer.byteLength(JSON.stringify(outputBudget([...current.outputs, ...evaluation.outputs]), null, 2)) + (current.pipeline.sidecarBytes ?? 0) > OUTPUT_METADATA_BYTES) {
|
|
830
|
+
current.error = "pipeline: total output metadata including retained sidecars exceeds the attempt limit"; finish(current, "failed", "artifact-limit", ctx); return "attempt.failed";
|
|
831
|
+
}
|
|
449
832
|
current.metrics = evaluation.metrics; current.outputs = outputBudget([...current.outputs, ...evaluation.outputs]); finish(current, "succeeded", undefined, ctx); return "attempt.succeeded";
|
|
450
833
|
}));
|
|
451
834
|
}
|
|
452
|
-
} catch {
|
|
453
|
-
|
|
835
|
+
} catch (error) {
|
|
836
|
+
if (attempt.pipeline && observedState && !observedState.running) {
|
|
837
|
+
const failure = pipelineFailureAt(dir, attempt, error, ctx);
|
|
838
|
+
const retryable = retryablePipelineFailure(error) && failure.reason !== "wall-clock";
|
|
839
|
+
changed.push(await update(dir, attempt.id, ctx, current => {
|
|
840
|
+
if (current.status !== "running") return undefined;
|
|
841
|
+
const stage = current.stages[current.stage];
|
|
842
|
+
if (stage) { stage.exitCode = observedState!.exitCode; stage.endedAt = observedState!.finishedAt ?? at(ctx); delete stage.launchPending; }
|
|
843
|
+
current.error = failure.message;
|
|
844
|
+
if (retryable) { current.reason = "executor-seal"; return "attempt.executor-error"; }
|
|
845
|
+
finish(current, "failed", failure.reason, ctx); return "attempt.failed";
|
|
846
|
+
}));
|
|
847
|
+
continue;
|
|
848
|
+
}
|
|
849
|
+
if (error instanceof InputVerificationError) throw error;
|
|
850
|
+
await update(dir, attempt.id, ctx, current => { delete current.launching; current.error = error instanceof Error ? error.message : hostError(current, "reconcile").message; if (current.pipeline && error instanceof EvidenceError) current.reason = error.reason; return "attempt.executor-error"; });
|
|
454
851
|
throw hostError(attempt, "reconcile");
|
|
455
852
|
}
|
|
456
853
|
}
|
|
457
854
|
return changed;
|
|
458
855
|
});
|
|
856
|
+
// No control lock or launch claim is held across a potentially 40-minute manifest pass.
|
|
857
|
+
for (const attempt of pending) {
|
|
858
|
+
const launched = await verifyAndLaunchPending(dir, attempt, ctx);
|
|
859
|
+
if (launched) changed.push(launched);
|
|
860
|
+
}
|
|
861
|
+
await reconcileRetentionReservations(dir, ctx);
|
|
862
|
+
return changed;
|
|
863
|
+
}
|
|
864
|
+
/** Explicit reconciliation only frees a hold after the executor confirms no owned live container. */
|
|
865
|
+
async function reconcileRetentionReservations(dir: string, ctx: AttemptContext): Promise<void> {
|
|
866
|
+
const executor = readExecutor(dir), { study } = openStudy(dir);
|
|
867
|
+
if (!executor || (!load(dir).some(attempt => !!attempt.pipeline) && readProtocol(dir)?.v !== 2)) return;
|
|
868
|
+
if (load(dir).some(attempt => attempt.status === "running")) return;
|
|
869
|
+
const view = await retainedOperation(executor, { op: "inspect", studyId: study.id }, ctx.runner ?? spawnRunner);
|
|
870
|
+
for (const reservation of view.reservations ?? []) {
|
|
871
|
+
if (!reservation.active) continue;
|
|
872
|
+
const attempt = load(dir).find(value => value.id === reservation.attemptId);
|
|
873
|
+
if (attempt?.status === "running") continue;
|
|
874
|
+
try { await withControl(dir, () => withLock(dir, async () => {
|
|
875
|
+
const current = load(dir).find(value => value.id === reservation.attemptId);
|
|
876
|
+
if (current?.status === "running") return;
|
|
877
|
+
const live = await runOnExecutor(executor, "docker", ["ps", "--filter", `label=ares.study=${study.id}`, "--filter", `label=ares.attempt=${reservation.attemptId}`, "--format", "{{.ID}}"], ctx.runner ?? spawnRunner);
|
|
878
|
+
if (live.exitCode !== 0 || live.timedOut || live.truncated || live.stdout.trim()) return;
|
|
879
|
+
await retainedOperation(executor, { op: "release", studyId: study.id, attemptId: reservation.attemptId }, ctx.runner ?? spawnRunner);
|
|
880
|
+
})); } catch (error) { if (!(error instanceof StudyLockBusyError)) throw error; }
|
|
881
|
+
}
|
|
459
882
|
}
|
|
460
883
|
export async function cancelAttempt(dirArg: string, wanted: string, reason: string | undefined, ctx: AttemptContext, completion?: (attempt: Attempt) => PendingEvent[]): Promise<Attempt> {
|
|
461
884
|
const dir = studyDir(dirArg), why = reason === undefined ? undefined : boundedText(reason, "reason", 500);
|
|
@@ -469,14 +892,26 @@ export async function cancelAttempt(dirArg: string, wanted: string, reason: stri
|
|
|
469
892
|
});
|
|
470
893
|
if (alive(attempt, ctx)) throw new Error("attempt: another startup operation is active; retry cancel when it finishes (abandoned claims expire after 30 minutes)");
|
|
471
894
|
try {
|
|
472
|
-
let state = await inspect(attempt, ctx);
|
|
473
|
-
if (state && needsReceipt(attempt, state))
|
|
474
|
-
|
|
895
|
+
let state = await inspect(dir, attempt, ctx, true);
|
|
896
|
+
if (state && needsReceipt(attempt, state)) {
|
|
897
|
+
const owned = state;
|
|
898
|
+
attempt = await update(dir, attempt.id, ctx, current => {
|
|
899
|
+
current.stages[current.stage]!.containerId = owned.id;
|
|
900
|
+
if (owned.startedAt) current.stages[current.stage]!.startedAt = owned.startedAt;
|
|
901
|
+
delete current.launching;
|
|
902
|
+
// Ownership permits cancellation; it does not establish isolation or approve any gate.
|
|
903
|
+
return "attempt.stage.recovered";
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
if (state?.running) { await command(attempt, "cancel kill", "docker", ["kill", state.id], ctx); state = await inspect(dir, attempt, ctx, true); }
|
|
907
|
+
if (attempt.pipeline && state?.running) throw hostError(attempt, "cancellation termination confirmation");
|
|
475
908
|
if (state) attempt = await captureStage(dir, attempt, ctx, true);
|
|
909
|
+
if (attempt.pipeline) await retainedOperation(attempt.executor, { op: "release", studyId: attempt.studyId, attemptId: attempt.id }, ctx.runner ?? spawnRunner);
|
|
476
910
|
const ended = state;
|
|
477
911
|
return update(dir, attempt.id, ctx, current => { if (ended && !ended.running) { current.stages[current.stage]!.exitCode = ended.exitCode; if (ended.finishedAt) current.stages[current.stage]!.endedAt = ended.finishedAt; } finish(current, "cancelled", why ?? "cancelled", ctx); return "attempt.cancelled"; }, [], completion);
|
|
478
|
-
} catch {
|
|
912
|
+
} catch (error) {
|
|
479
913
|
await update(dir, attempt.id, ctx, current => { delete current.launching; return "attempt.executor-error"; });
|
|
914
|
+
if (error instanceof InputVerificationError) throw error;
|
|
480
915
|
throw hostError(attempt, "cancel");
|
|
481
916
|
}
|
|
482
917
|
});
|