Design Record: Trial Runs for Evals
Status: implemented (contracts in @neusym/contract-{evals,tasks,goals,diagnostics}, runtime in @neusym/kit-{evals,tasks,completion-gate,diagnostics,proposals,release-manager}, and acceptance tests in…
Status: implemented (contracts in @neusym/contract-{evals,tasks,goals,diagnostics}, runtime in @neusym/kit-{evals,tasks,completion-gate,diagnostics,proposals,release-manager}, and acceptance tests in scenarios/test/sandbox-trials.test.ts). Line references below were to the tree at design time.
#Problem
Evals tests a candidate only by replay. runSuite switches to a shadow context (kits/assurance/evals/src/port.ts), creates each case's task with only the prompt, context items, an agent definition and an output schema (:525-530), writes a binding document so replay-recorded answers every tool call from the recording (:531-534, :1121-1125), and awaits tasks.runTask (:538). That is cheap and repeatable, but it never sees how a candidate behaves against live tools, and it can only test what already happened in production: a case exists only by captureCase from a recorded run (EvalCase.source, recordedTools and baseline are required, contracts/evals/src/index.ts:199-213).
A naive "paired live-sandbox evaluation" cannot be built directly inside the evals kit for six reasons: evals cannot run a command, baseRef means nothing here, cases can only be captured, live eval tasks leak into worker-pool, diagnostics and proposals, live mode alone limits no spend (replay tasks have no scope, so the budget guard abstains), and nothing re-runs a baseline.
#Decision in short
- A trial is an ordinary live task carrying a trial marker, routed by
workerRoleto a dedicated evaluation workspace at leveldraft. - Every trial run gets its own budget scope
eval:<evalRunId>with limits from the run's options; a trial run without a cost cap, or withoutbudget@1, is refused. - Created cases live in a new suite kind
trial: an input and checks, no source run, no recording, no baseline. startTrialRuncreates the tasks and returns. Atask.changedlistener scores each trial as it ends, and the last one closes the run witheval.completed.- The marker is a field on the task, copied onto the run summary. Diagnostics and proposals leave trials out by default.
#Trial model
A trial is one attempt of one created case: a live task created by evals with
| Field | Value | Why |
|---|---|---|
mode | live (the default) | It must reach live tools and be charged; shadow skips charging and worker-pool skips shadow tasks (the task.changed listener in kits/runtime/worker-pool/src/events.ts) |
workerRole | evals config trialRole, default eval | Routes it to the tasks:eval queue (taskQueueForRole, contracts/workers/src/index.ts:25-27), served only by the evaluation workspace |
scopeId | eval:<evalRunId> | The run's budget (below). No goalId: a goal would win in budgetScopeFor (contracts/budget/src/index.ts:32-52) |
evalTrial | { evalRunId, caseId, attempt } | The marker (below); set at creation, never changed |
agentDefId, procedureInput, prompt, contextItems, outputSchema | from the case and the run options | What is being tested |
sessionId | none | A trial belongs to no person's session; session summaries never count it |
Where it runs. The workspace that starts the run and the evaluation workspace share one store, so the trial is a task of the same tenant. The evaluation workspace runs at level draft: the kernel denies execute and commit effects there (LEVEL_CEILING_DENIED, core/kernel/src/executor.ts:301-311). That ceiling is the sandbox; the platform runtime runs no verification command of its own.
No replay. Evals writes no binding document for a trial, so replay-recorded never answers its calls. record-calls does record them (it records live calls of unbound tasks, :1055-1058), which lets the grounded-number and errors-handled checks read the trial's own tool results. A trial run is never a replay baseline: captureCase and feedback auto-capture refuse a trial-marked run with EVAL_TRIAL_NOT_CAPTURABLE.
Children. A task created from a trial's run inherits evalTrial (the tasks kit reads it from the creating context's task) and gets the trial role; delegation already passes the parent's scope to its children. So every task of a trial is marked, charged to the run and run at draft.
#Budget scope
startTrialRuncallsbudget.setScopeBudget(ctx, 'eval:<evalRunId>', limits)(contracts/budget/src/index.ts:214) before it creates any task.limits.maxCostUsdis required;maxTokensandmaxStepsare optional. WithoutmaxCostUsd, or with nobudget@1bound, the call throwsEVAL_TRIAL_BUDGET_REQUIRED.budget@1joins evals'optionalports.- The scope is fresh per run, so spend cannot leak between runs and the ledger stays afterwards as the run's spend record.
- The step guard,
reserveAttemptand the kill switch apply unchanged: trials are live work on a scope that has a ledger. A trial halted by its budget is a failed attempt with its halt code (BUDGET_COST_EXCEEDED, ...), and the report says the run was budget-bound.
#Created cases and their checks
A suite gets a kind, fixed when it is configured: replay (today's suites, the default for every stored suite) or trial. A trial suite holds only created cases; runSuite refuses it (EVAL_SUITE_IS_TRIAL) and startTrialRun refuses a replay suite. EvalCase stays as it is, so readers of listCases (proposals reads c.source.runId, gather in kits/assurance/proposals/src/gather.ts) are untouched.
// contracts/evals
export interface TrialCaseInput {
readonly prompt: string;
readonly contextItems?: readonly ContextItem[];
readonly procedureInput?: Readonly<Record<string, unknown>>;
readonly outputSchema?: JsonSchema;
}
export interface TrialCheck {
/** The existing deterministic and answer-scorer expectations; `status` defaults to `completed`. */
readonly expect?: EvalExpectation;
/** Field checks on the trial's trusted JSON evidence artifacts, as goals define them (3.2). */
readonly evidence?: readonly EvidenceFieldCheck[];
}
export interface TrialCase {
readonly id: string; // `tcase:<suite>:<seq>`
readonly suite: string;
readonly seq: number;
readonly name: string;
readonly input: TrialCaseInput;
readonly check: TrialCheck; // at least one of `expect`, `evidence`
readonly createdAt: string;
readonly createdBy?: string;
}
export interface EvalsPort {
// existing members
createTrialCase?(ctx: RuntimeContext, suite: string, input: { name: string; input: TrialCaseInput; check: TrialCheck }): Promise<TrialCase>;
listTrialCases?(ctx: RuntimeContext, suite: string): Promise<readonly TrialCase[]>;
}- Text is content. Prompt, context and expected texts are redacted with
secrets@1(warmed first) and refused at capture belowcontent, ascaptureCasedoes. expectreusesscoreOutcomeand the answer scorers (exact,token-overlap,rule,model-judge) unchanged.forbidHaltCodeshas no recorded halt code to default to, so it defaults to none; the cost and token ratio fields need a baseline and are refused on a created case withoutpairWith(below).evidencereads the trial task's artifacts of kindevidencethat aretrusted, JSON and within the size limit, newest first, with the same dotted own-property path rule as the completion gate (kits/safety/completion-gate/src/index.ts:26-38,:127-140). That gate only runs for a task with an active goal (:69-86), and a trial has none, so evals checks the fields itself. The path walker moves from the completion gate intocontracts/goalsas an exported pure function, so both read a path the same way.artifacts@1joins evals'optionalports; a case withevidencechecks is refused when it is not bound.
#Asynchronous trial run
export interface StartTrialRunOptions {
readonly repeats?: number; // 1 to config maxRepeats
readonly agentDefId?: string; // the candidate
readonly pairWith?: string; // a baseline agent definition, run case by case
readonly limits: { readonly maxCostUsd: number; readonly maxTokens?: number; readonly maxSteps?: number };
readonly deadlineMs?: number; // default config trialDeadlineMs, 1 hour
}
export interface EvalsPort {
startTrialRun?(ctx: RuntimeContext, suite: string, options: StartTrialRunOptions): Promise<EvalRunReport>; // state 'running'
cancelTrialRun?(ctx: RuntimeContext, evalRunId: string): Promise<EvalRunReport>;
}- Refuse outside
livemode, for a suite that is nottrialor has no case, and without a budget (above). - Set the scope's ledger, then write the run document (
state: 'running',deadlineAt, one pending attempt per case, repeat and arm), then create every task,queued. Task ids are fixed,trial_+stableHash([evalRunId, caseId, attempt, arm])(CreateTaskInput.id), so creating one again finds the first. A start that stops part-way leaves attempts with no task; the deadline scores them failed withEVAL_TRIAL_NOT_STARTED, so a run never waits on a task nobody created. Return the report withstate: 'running'. - Evals listens to
task.changed(new). For a terminal status of a task whoseevalTrialnames a running run, it reads the task, its run and its evidence, scores the attempt, and writes it into the run document atexpectedVersion. Delivery is at least once; an attempt already scored is left as it is. - The commit that scores the last pending attempt also computes the totals (pass rate, pass^k, cost, and the paired comparison when there is one), sets
state: 'completed', and publisheseval.completedwith the existing payload plustrial: true. Release-manager snapshots the report of every completed run it can read (theeval.completedlistener inkits/assurance/release-manager/src/events.ts); it skipstrial: trueruns until a release gate on trials is designed. - Deadline. With
scheduler@1bound, a timer fires atdeadlineAt; without it, the nextgetReportorlistRunsafter the deadline does the same work. Either one halts every trial still open (EVAL_TRIAL_DEADLINE), scores those attempts as failed, and closes the run.cancelTrialRundoes the same at once, withEVAL_TRIAL_CANCELLED.
runSuite and the release gate keep their synchronous replay path. Gating a release on a trial suite is out of scope here.
#Trial marker and its exclusion
TaskRecord.evalTrial?: { evalRunId: string; caseId: string; attempt: number }and the same field onCreateTaskInput, set once.TaskChangedPayloadcarriesevalRunIdwhen the task has one.- Diagnostics stores
evalRunIdon the run summary fromtask.changed. Every run starts with atask.changedtorunning, so the summary is marked before anything reads it.RunFilterandReportOptionsgetincludeTrials?: boolean, default false;listRuns,reportand the defect report leave marked runs out unless it is set. A trial has no session, so session summaries never see it. - Proposals leaves out a source whose run summary has
evalRunIdor whose task hasevalTrial, beside itsmodechecks (gatherinkits/assurance/proposals/src/gather.ts). It reads runs throughlistRuns, so the diagnostics default already does most of this. - The marker hides a run from default views only. Audit, telemetry, the budget ledger and
includeTrialsall still show it; a task can carry it from creation only, so it cannot be put on a production run afterwards.
#Answers to the open questions
Where the marker lives: a field on the task, copied to the run summary, not a kind on the run summary. The task is the one record every reader already has (worker-pool, tasks, proposals); a field set at creation travels to children and to task.changed without new joins. The stored run summary already uses kind: 'run' as its storage discriminator for the by_kind index (RUN_KIND in kits/assurance/diagnostics/src/constants.ts), so a "kind" marker would collide with it, and diagnostics only sees runs, not the tasks that never started one. A new execution mode was rejected too: modes decide charging and delivery all over the platform, and a trial must be charged and delivered like live work.
Whether the baseline is re-run: only when the run asks, with pairWith. A created case has no recorded run, so there is nothing to compare against for free. Running a baseline doubles spend, which is a product decision per run, not a default. With pairWith, every case and repeat runs once per arm under the same scope and cap, the arms' tasks are created interleaved so a cap or deadline hits both alike, and the report adds a per-case EvalCostComparison and durationDeltaMs. Without it, the report gives absolute results and, for orientation only, the previous completed trial run of the same suite.
A trial that parks: it depends on what it waits for. Waiting on a timer, a delegation or a delegation_barrier resolves without a person, so the trial keeps its place until the deadline. Waiting on an approval or a dispute needs a person, which an unattended run cannot supply: the listener halts the trial at once with EVAL_TRIAL_PARKED and scores the attempt as failed with the wait kind, which frees its budget hold. A case that needs a person is a case to rewrite, and the report says which. Today a parked replay is simply scored on status waiting and its task is left behind, never resumed (replay in kits/assurance/evals/src/replay.ts).
Keeping the evaluation workspace apart from production: configuration on both sides, and one check that does not depend on it.
- The evaluation workspace's worker-pool sets
allowedRoles: ["eval"]andserveDefaultQueue: false, so it never leases a production task; a task of another role is put back on its own queue (WORKER_ROLE_MISMATCH,runJobinkits/runtime/worker-pool/src/job-runner.ts). - Production workspaces leave the trial role out of their
allowedRoles, and only the workspace that starts runs lists it in the tasks kit'sallowedCreateRoles. - The check: the tasks kit's
runTaskrefuses to start a run of a task carryingevalTrialwhen its ownhandles.deployment.levelis abovedraft, and fails the task withEVAL_TRIAL_LEVEL_DENIED. Every executor path goes throughrunTask, so a misconfigured production pool fails a trial visibly in the report instead of running it with real effects.
Whether durationMs joins the outcome: yes, filled for trials only. EvalOutcome gets durationMs? (contracts/evals/src/index.ts:186-197), measured from the run record's createdAt to the updatedAt of the terminal change, so time spent queued before the run began is not counted. A replay leaves it out: its tool calls are answered from the recording, so its time says nothing about live latency, and the recorded baseline has no duration to compare with. durationDeltaMs is reported for paired trial runs only.
#Contract changes
| Package | Change |
|---|---|
contracts/tasks | evalTrial? on TaskRecord and CreateTaskInput; evalRunId? on TaskChangedPayload; codes EVAL_TRIAL_LEVEL_DENIED |
contracts/evals | suite kind; TrialCaseInput, TrialCheck, TrialCase; StartTrialRunOptions; optional members createTrialCase, listTrialCases, startTrialRun, cancelTrialRun; EvalRunReport.state; EvalOutcome.durationMs?; EvalCompletedPayload.trial?; codes EVAL_SUITE_IS_TRIAL, EVAL_TRIAL_BUDGET_REQUIRED, EVAL_TRIAL_NOT_CAPTURABLE, EVAL_TRIAL_NOT_STARTED, EVAL_TRIAL_PARKED, EVAL_TRIAL_DEADLINE, EVAL_TRIAL_CANCELLED |
contracts/goals | export the evidence path walker the completion gate uses today |
contracts/diagnostics | RunSummary.evalRunId?; includeTrials? on RunFilter and ReportOptions |
Kits: evals (optional gains budget@1, artifacts@1, scheduler@1; listens gains task.changed; config trialRole, trialDeadlineMs), tasks (marker, children, level check), completion-gate (uses the shared walker), diagnostics, proposals, release-manager (skips trial runs).
#Tests
- A trial run on a scripted model in a
draftworkspace: tasks are created live with the scope, role and marker;startTrialRunreturnsrunning; scoring each task's end completes the run once, with oneeval.completed, also when everytask.changedis delivered twice. - No binding is written and live tools answer; the trial's recorded calls feed
requireGroundedNumbers;captureCaserefuses the trial run. - A run that would overspend halts its trials at the cap; a run without
maxCostUsd, or withoutbudget@1, is refused. - An
evidencecheck passes and fails on a trusted JSON artifact, and ignores an untrusted one. - A trial that waits on an approval is halted and scored
EVAL_TRIAL_PARKED; one that waits on a timer completes; the deadline closes a run whose trial never ends. - A trial task run by a workspace at
executefails withEVAL_TRIAL_LEVEL_DENIEDand runs no tool. - Diagnostics lists, reports and defect reports leave trials out unless
includeTrials; proposals never gathers a trial run. pairWith: both arms run under one cap, and the report carries cost and duration deltas.
#Out of scope
- Running a verification command or a container directly from the core runtime. A task's own executor or a verifier task handles that in the consuming product workspace.
- A release gate on trial suites, and promoting from a trial run.
- Version-control references (
baseRef): a case gives the task its input, and a workspace reference travels inprocedureInput.