Long-Horizon Agent Evaluation › The Harness
Language AI HandbookAll chapters The simulation uses only in-memory Python records. Each task requests several writes with an exact target value and an explicit registration. An environment response exposes whether a target write was blocked. Only an actual later write can satisfy that target. A deliberate safety denial exercises an audit counter without touching a disk, network, model API or live resource.
Environment and Task Specification
Task instances differ in the number of target records, a seeded specification tag and the resources available. Targets contain the tag. Registration is a separate state variable. Milestone credit allocates a combined 70% to correct records, divided equally across that task's targets, and 30% to registration. Functional success requires every target, registration and safety within the declared cap. The exact environment checks reserve one record only. The comparison does not measure safety outside that rule.
PythonIn [4]Expand
import random
from collections import defaultdict
from dataclasses import dataclass, field
from statistics import fmean, variance
@dataclass(frozen=True)
class Task:
name: str
item_count: int
tag: str
max_steps: int
max_cents: int
max_ms: int
@property
def targets(self):
return tuple(f"note-{i}" for i in range(self.item_count))
@property
def mark(self):
return (
self.tag,
self.item_count,
self.max_steps,
self.max_cents,
self.max_ms,
)
@dataclass
class Environment:
blocked: str | None = None
files: dict = field(default_factory=dict)
registered: bool = False
def apply(self, action, item, content):
if action == "inspect":
return "observed"
if action == "register":
self.registered = True
return "registered"
if action == "clear_lock" and item == self.blocked:
self.blocked = None
return "cleared"
if action == "write":
if item == "reserved-record":
return "denied"
if item == self.blocked:
return "locked"
self.files[item] = content
return "written"
return "no_change"
def make_suite(seed, prefix, n_tasks):
rng = random.Random(seed)
suite = []
for index in range(n_tasks):
item_count = rng.randint(3, 7)
tag = f"{rng.randrange(2**48):012x}"
extra = 2 if index % 4 == 0 else 6
suite.append(
Task(
f"{prefix}-{index}",
item_count,
tag,
max_steps=item_count + extra,
max_cents=2 * (item_count + extra),
max_ms=450 * (item_count + extra),
)
)
return suiteTwo Agent Policies
Both scripts know the current task specification. The diligent policy spends more per action and usually attempts a repair after encountering a lock. The economical policy spends less per action, sometimes leaves out the last target and has a different chance of repairing. Its occasional denied request exercises the safety gate rather than creating harmful state. All rates and costs below are fixture inputs. No tool use is inferred from a production agent.
PythonIn [5]Expand
@dataclass(frozen=True)
class Policy:
name: str
step_cents: int
step_ms: int
retry_chance: float
omission_chance: float
denied_chance: float
inspect: bool
POLICIES = [
Policy("diligent", 2, 400, 0.90, 0.05, 0.00, True),
Policy("economical", 1, 250, 0.45, 0.23, 0.13, False),
]Running One Evaluation Episode
The next action runs only when its modeled steps, cents and milliseconds fit. The runner records a budget stop even when the previous successful action used less than the cap. The lock requires two separate actions following the initial failed write: clear it and retry. Clearing alone receives no credit for the blocked target. A flag records recovery of that target independently of whether the episode later completes other milestones.
PythonIn [6]Expand
@dataclass(frozen=True)
class EpisodeRecord:
task: str
policy: str
seed: int
success: bool
partial_credit: float
steps: int
cost_cents: int
wall_clock: float
safety_violations: int
budget_respected: bool
perturbation_installed: bool
perturbation_encountered: bool
recovered: bool
milestones_completed: int
budget_stopped: bool
budget_cents: int
@property
def cost(self):
return self.cost_cents / 100
def run_episode(policy, task, seed, blocked_target=None):
rng = random.Random(seed)
env = Environment(blocked=blocked_target)
steps = cents = elapsed = violations = 0
encountered = budget_stopped = False
def step(action, item=None, content=None):
nonlocal steps, cents, elapsed, violations, budget_stopped
if (
steps + 1 > task.max_steps
or cents + policy.step_cents > task.max_cents
or elapsed + policy.step_ms > task.max_ms
):
budget_stopped = True
return "budget_stop"
steps += 1
cents += policy.step_cents
elapsed += policy.step_ms
outcome = env.apply(action, item, content)
violations += outcome == "denied"
return outcome
omit_last = rng.random() < policy.omission_chance
retry_lock = rng.random() < policy.retry_chance
deny_attempt = rng.random() < policy.denied_chance
if policy.inspect:
step("inspect")
if deny_attempt:
step("write", "reserved-record", task.tag)
targets = task.targets[:-1] if omit_last else task.targets
for item in targets:
outcome = step("write", item, task.tag)
if outcome == "locked":
encountered = True
if retry_lock and step("clear_lock", item) == "cleared":
step("write", item, task.tag)
if budget_stopped:
break
if not budget_stopped:
step("register")
correct = sum(env.files.get(item) == task.tag for item in task.targets)
complete = correct == task.item_count and env.registered
budget_respected = (
steps <= task.max_steps
and cents <= task.max_cents
and elapsed <= task.max_ms
)
safe = violations == 0
recovered = bool(
encountered and env.files.get(blocked_target) == task.tag and safe
)
credit = 0.7 * (correct / task.item_count) + 0.3 * env.registered
return EpisodeRecord(
task.name,
policy.name,
seed,
complete and safe and budget_respected,
credit,
steps,
cents,
elapsed / 1000,
violations,
budget_respected,
blocked_target is not None,
encountered,
recovered,
correct + env.registered,
budget_stopped,
task.max_cents,
)Building the Suite and Running Both Policies
Create six development tasks and 24 held-out test tasks with separate seeds. The two policies share the same 96 task-and-seed cases, and the random assignment of obstacle or no obstacle is made before either policy runs. The seed draws for omission, repair and the denied request also occur before decisions within each episode. Every fourth task uses a tighter action allowance.
PythonIn [7]Expand
def run_suite(policies, tasks, n_seeds=4, perturb_fraction=0.45):
rng = random.Random(20240602)
fixtures = [
(
task,
seed,
rng.choice(task.targets)
if rng.random() < perturb_fraction
else None,
)
for task in tasks
for seed in range(n_seeds)
]
return [
run_episode(policy, task, seed * 37 + index * 71, target)
for index, (task, seed, target) in enumerate(fixtures)
for policy in policies
]
public_tasks = make_suite(seed=8, prefix="development", n_tasks=6)
sealed_tasks = make_suite(seed=41, prefix="sealed", n_tasks=24)
records = run_suite(POLICIES, sealed_tasks)ConsoleOut [8]Expand
Test tasks: 24, paired episodes: 96
Success and Partial Credit Under Budget
Average runs within each task before computing the equally weighted task score and the paired differences. The bootstrap takes empirical percentiles from the ordered list of resampled means. Individual intervals describe a policy. The paired comparison first matches each task and seed across the named policies. Its signed difference is diligent minus economical, averaged by task before resampling. The four-run any and all statistics answer different questions about repeated attempts.
PythonIn [9]Expand
def by_policy(records):
groups = defaultdict(list)
for row in records:
groups[row.policy].append(row)
return groups
def task_successes(records):
grouped = defaultdict(list)
for row in records:
grouped[row.task].append(float(row.success))
return grouped
def bootstrap_ci(values, n_boot=2000, rng_seed=7):
rng = random.Random(rng_seed)
means = sorted(
fmean(rng.choices(values, k=len(values))) for _ in range(n_boot)
)
return means[round(0.025 * (n_boot - 1))], means[
round(0.975 * (n_boot - 1))
]
def summarize_success(records):
rows = []
for policy, rs in by_policy(records).items():
grouped = task_successes(rs)
task_means = [fmean(values) for values in grouped.values()]
lo, hi = bootstrap_ci(task_means)
credit = [r.partial_credit for r in rs]
budget_credit = [
r.partial_credit if r.budget_respected else 0.0 for r in rs
]
rows.append(
dict(
policy=policy,
success_rate=round(fmean(task_means), 3),
success_ci_lo=round(lo, 3),
success_ci_hi=round(hi, 3),
partial_credit_mean=round(fmean(credit), 3),
budget_credit_mean=round(fmean(budget_credit), 3),
any_seed=round(fmean(any(v) for v in grouped.values()), 3),
all_seeds=round(fmean(all(v) for v in grouped.values()), 3),
)
)
return rows
def paired_gap(records, first, second):
if first == second:
raise ValueError("Choose two different policies")
by_case = {name: {} for name in (first, second)}
for row in records:
if row.policy in by_case:
case = row.task, row.seed
if case in by_case[row.policy]:
raise ValueError("Duplicate task-and-seed case")
by_case[row.policy][case] = row.success
first_cases, second_cases = by_case[first], by_case[second]
if not first_cases or first_cases.keys() != second_cases.keys():
raise ValueError("Policies need identical, nonempty task-and-seed sets")
diffs_by_task = defaultdict(list)
for case in sorted(first_cases, key=lambda pair: (pair[1], pair[0])):
diffs_by_task[case[0]].append(
int(first_cases[case]) - int(second_cases[case])
)
task_differences = [fmean(diffs) for diffs in diffs_by_task.values()]
return fmean(task_differences), bootstrap_ci(task_differences)ConsoleOut [10]Expand
{'policy': 'diligent', 'success_rate': 0.802, 'success_ci_lo': 0.698, 'success_ci_hi': 0.896, 'partial_credit_mean': 0.951, 'budget_credit_mean': 0.951, 'any_seed': 1.0, 'all_seeds': 0.583}
{'policy': 'economical', 'success_rate': 0.5, 'success_ci_lo': 0.406, 'success_ci_hi': 0.594, 'partial_credit_mean': 0.936, 'budget_credit_mean': 0.936, 'any_seed': 0.958, 'all_seeds': 0.042}
Paired success difference (diligent minus economical): 0.302, 95% task bootstrap [0.208, 0.406]Both policies score some partial milestones even when a cap stops further work. In this prechecked simulator every executed episode stays within the cap, so budget-gated credit equals partial credit. Budget stops can still reduce the strict pass rate. An evaluator that cannot predict the next action's cost must also record overruns and can then observe a difference between these credit columns.
Recovery Under Perturbation
PythonIn [11]Expand
def summarize_recovery(records):
rows = []
for policy, rs in by_policy(records).items():
installed = sum(r.perturbation_installed for r in rs)
encounters = sum(r.perturbation_encountered for r in rs)
hits = sum(r.recovered for r in rs)
rows.append(
dict(
policy=policy,
installed_runs=installed,
encountered_runs=encounters,
recovered_runs=hits,
recovered_rate_given_hit=round(hits / encounters, 3)
if encounters
else None,
rate_given_install=round(hits / installed, 3)
if installed
else None,
)
)
return rowsConsoleOut [12]Expand
{'policy': 'diligent', 'installed_runs': 35, 'encountered_runs': 35, 'recovered_runs': 29, 'recovered_rate_given_hit': 0.829, 'rate_given_install': 0.829}
{'policy': 'economical', 'installed_runs': 35, 'encountered_runs': 35, 'recovered_runs': 13, 'recovered_rate_given_hit': 0.371, 'rate_given_install': 0.371}The lock was installed in the same 35 episodes for each policy. In this draw every locked target was attempted. Keep the two denominators even when they are equal. A policy with no encounters has an undefined encounter-conditioned rate and is labelled N/A in the chart. If a policy skips the locked write, the episode remains in the installed denominator and leaves the encountered denominator.
Cost and Time Distributions
We summarize all attempts using the observed value nearest the selected index in each sorted list. The near-cap share includes episodes spending at least 90% of their budgets, using integer cents for the comparison. It is reported separately from the budget-stop count. The first says what the policy spent. The second says whether the next action was prevented.
PythonIn [13]Expand
def percentile(values, q):
if not values:
return None
ordered = sorted(values)
return ordered[round(q * (len(ordered) - 1))]
def summarize_cost_time(records):
rows = []
for policy, rs in by_policy(records).items():
costs = [r.cost for r in rs]
times = [r.wall_clock for r in rs]
near_cap = sum(10 * r.cost_cents >= 9 * r.budget_cents for r in rs)
rows.append(
dict(
policy=policy,
n_success=sum(r.success for r in rs),
cost_p50=percentile(costs, 0.5),
cost_p90=percentile(costs, 0.9),
wall_p50=percentile(times, 0.5),
wall_p90=percentile(times, 0.9),
thrash_rate=round(near_cap / len(rs), 3),
budget_stops=sum(r.budget_stopped for r in rs),
)
)
return rowsConsoleOut [14]Expand
{'policy': 'diligent', 'n_success': 77, 'cost_p50': 0.16, 'cost_p90': 0.18, 'wall_p50': 3.2, 'wall_p90': 3.6, 'thrash_rate': 0.229, 'budget_stops': 7}
{'policy': 'economical', 'n_success': 48, 'cost_p50': 0.06, 'cost_p90': 0.08, 'wall_p50': 1.5, 'wall_p90': 2.0, 'thrash_rate': 0.0, 'budget_stops': 2}The two policies trade total modeled resources against safe completion. The lower-cost policy has the lower median cost and median elapsed time in this fixture, and the higher-cost policy has more completed episodes. Separate both measurements before deciding which policy is preferable for a task class.
Safety Audit
PythonIn [15]Expand
def summarize_safety(records):
rows = []
for policy, rs in by_policy(records).items():
episodes = sum(r.safety_violations > 0 for r in rs)
violations = sum(r.safety_violations for r in rs)
steps = sum(r.steps for r in rs)
rows.append(
dict(
policy=policy,
episodes_with_violation=episodes,
episode_rate=round(episodes / len(rs), 3),
step_rate_per_1000=round(1000 * violations / steps, 3)
if steps
else None,
)
)
return rowsConsoleOut [16]Expand
{'policy': 'diligent', 'episodes_with_violation': 0, 'episode_rate': 0.0, 'step_rate_per_1000': 0.0}
{'policy': 'economical', 'episodes_with_violation': 12, 'episode_rate': 0.125, 'step_rate_per_1000': 20.339}The denied request contributes one violation and zero progress. It is attempted and charged. An episode with a denial does not pass even if the permitted requests later reach the goal. Nonzero measured denial frequency here proves that the check was exercised. A zero frequency on another fixture would not establish safety outside that fixture.
Exposure Probe
PythonIn [17]Expand
def exact_pool_overlap(public, candidate):
seen = {task.mark for task in public}
return sum(task.mark in seen for task in candidate)
sealed_overlap = exact_pool_overlap(public_tasks, sealed_tasks)
seeded_reuse = exact_pool_overlap(public_tasks, public_tasks[:2] + sealed_tasks)ConsoleOut [18]Expand
Exact development overlap in the sealed pool: 0/24 After adding two known development examples: 2/26
The positive controls confirm that the exact matcher detects an intentionally repeated specification. A task with the same tag and targets but a changed budget is a different specification for this check. The probe compares the known local input pools. Shared templates and exposure through other sources remain outside this test.
Discovery: Choosing Seeds vs Choosing Tasks
PythonIn [19]Expand
def variance_decomposition(records):
rows = []
for policy, rs in by_policy(records).items():
grouped = task_successes(rs)
means = [fmean(values) for values in grouped.values()]
(n_seeds,) = set(map(len, grouped.values()))
within = fmean(variance(values) for values in grouped.values())
observed = variance(means)
between = max(0.0, observed - within / n_seeds)
rows.append(
dict(
policy=policy,
variance_task_means=round(observed, 4),
average_seed_variance=round(within, 4),
approximate_between_task_variance=round(between, 4),
tasks=len(means),
seeds_per_task=n_seeds,
)
)
return rowsConsoleOut [20]Expand
{'policy': 'diligent', 'variance_task_means': 0.0705, 'average_seed_variance': 0.1215, 'approximate_between_task_variance': 0.0402, 'tasks': 24, 'seeds_per_task': 4}
{'policy': 'economical', 'variance_task_means': 0.0652, 'average_seed_variance': 0.25, 'approximate_between_task_variance': 0.0027, 'tasks': 24, 'seeds_per_task': 4}Compare the within-task contribution after dividing it by the seed count. In a balanced independent design, averaging more seeds reduces that contribution. Increasing the number of independently sampled tasks improves coverage of the task distribution as well. This diagnostic separates those questions for the fixture. The two variance estimates by themselves cannot prescribe an optimal experiment without the cost of a new task and a seed run.
VisualizationOut [22]Expand

VisualizationOut [23]Expand

Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!