Reference
Optimization search¶
Once you have several candidate interventions, the next question is which ones
to use together. Each might be a reuse pass, a schedule or a cheaper model. Some
help on their own but conflict with each other. Some save time but cost answer
quality. agentloop.optimization_search runs a small, bounded search over them.
It returns a decision for you to review. It never applies or deploys anything.
from agentloop.optimization_search import (
Intervention, Objective, SearchBudget, SearchSpec, run_search,
)
spec = SearchSpec(
interventions=[
Intervention("reuse"),
Intervention("parallel_tools"),
Intervention("smaller_model"),
Intervention("full_cache", conflicts_with={"reuse"}),
],
tuning_cases=["t01", "t02", "t03"],
held_out_cases=["h01", "h02"],
objectives=[Objective("runtime_ms", "min"), Objective("cost_usd", "min")],
quality_floor=0.0,
budget=SearchBudget(max_attempts=80, max_elapsed_s=1800, max_cost_usd=5.0),
seed=7,
)
report = run_search(spec, evaluate)
report["decision"]
You write evaluate(interventions, case_id). It runs your agent on one case
with those interventions applied, for example through an
experiment session or the
transformation registry, and returns:
quality is required and must come from your own independent check. Objective
metrics may be None when unknown. Return {"status": "error", ...} for a run
that failed.
What the search does¶
- Freezes the specification. Tuning and held-out cases must not overlap,
by ID or, when you pass
case_digests, by content. Quality is a constraint, never an objective. - Runs the baseline, with no interventions, on every tuning case.
- Runs each single intervention on every tuning case. Tie order is shuffled with your seed, so runs are reproducible.
- Combines greedily. It starts from the best single intervention that
keeps quality, then adds the next one while the primary objective (the first
listed) improves. It only combines interventions with no declared conflict,
up to
max_combination_size. - Evaluates once on held-out cases. The selected combination and the baseline run on cases the search never saw.
An intervention keeps quality when no tuning case's quality falls more than
quality_floor below the baseline's on that case, and every case ran
successfully. Unknown objective values never win.
Acceptance contract¶
By default, the held-out step recommends any combination whose mean primary gain is positive and whose quality doesn't drop. That's a weak test. Timing noise between identical runs can be larger than a real gain. A tiny gain may not be worth a change. And "quality didn't drop" passes a candidate whose baseline was already wrong.
Pass an AcceptanceContract to require more. It's frozen into the
specification before any candidate is chosen:
from agentloop.acceptance import AcceptanceContract
spec = SearchSpec(
...,
acceptance=AcceptanceContract(
min_improvement_pct=5.0, # smallest gain worth a change
min_quality=0.8, # every candidate run must reach this
max_quality_drop=0.0, # versus its paired baseline run
required_checks=("no_files_written",),
repetitions=3, # paired runs per held-out case
min_tasks=8, # held-out cases needed for a verdict
secondary_limits={"cost_usd": 0.0},
max_tail_regression_pct=10.0, # p90 of the primary metric
),
)
With a contract, each held-out case runs repetitions times as a pair of
baseline and candidate. Which side runs first alternates by case and
repetition, so neither always gets the warm cache. Every pair is judged:
| Check | Fails when |
|---|---|
| Completion | A candidate run fails or errors |
| Absolute quality | A candidate run scores below min_quality, whatever the baseline scored |
| Relative quality | A candidate run scores more than max_quality_drop below its paired baseline |
| Checks | A name in required_checks is false in the candidate's checks result |
| Practical effect | The interval for the improvement lies below min_improvement_pct |
| Secondary limits | A metric's mean paired regression exceeds its limit |
| Tail | The primary metric's tail_quantile regresses more than max_tail_regression_pct |
The practical effect is the percentage improvement over the paired baseline. It's averaged within each case first, then bootstrapped over cases. So 20 repetitions of 2 cases count as 2 tasks, not 40.
The decision is then one of:
recommend_for_review: every check passed, and the whole interval is at or abovemin_improvement_pct.rejected: evidence against. A check failed, or the interval lies below the threshold.indeterminate: not enough evidence either way. A value is missing (unknown cost is never treated as zero), a check wasn't reported, there are fewer thanmin_taskscases, or the interval straddles the threshold. Add cases or repetitions, or reduce noise, and run again.
Report a check with your result: {"quality": 1.0, "runtime_ms": 820,
"checks": {"no_files_written": true}}. The full evaluation is in
held_out.acceptance, and the decision names its policy:
acceptance_contract, or legacy_positive_mean_gain without one.
The interval describes these held-out cases under the conditions they ran in.
It isn't a guarantee about other workloads, machines or load. Freeze the
contract before you look at results, and choose min_improvement_pct from what
a change is worth to you, not from what a run happened to show.
Budgets and stopping¶
| Limit | Stops when |
|---|---|
max_attempts |
That many case evaluations have run |
max_elapsed_s |
That much time has passed, by a monotonic clock |
max_cost_usd |
Counted cost reaches it, the next attempt's declared bound wouldn't fit, or an attempt's cost is unknown and can't be bounded |
cancel event |
You set it. The evaluator sees it too (below). |
KeyboardInterrupt |
Raised inside evaluate. The attempt is recorded as interrupted. |
A stopped search reports stop_reason and returns a decision of incomplete.
An incomplete search is never recommended.
Hard and soft limits¶
A plain evaluate(interventions, case_id) callback is cooperative: the
search checks limits between attempts, so a single slow or expensive attempt
can run past a limit. The report says by how much.
To make limits hard, wrap your evaluator and declare what it enforces:
from agentloop.optimization_search import AttemptFailedError, Evaluator
def run(interventions, case_id, context):
# context.deadline and context.remaining_s(): when the time budget ends.
# context.cancel: set when the search is cancelled.
# context.cost_remaining_usd: cost budget left before this attempt.
...
evaluator = Evaluator(run=run, enforces_deadline=True, max_attempt_cost_usd=0.25)
report = run_search(spec, evaluator)
enforces_deadline=Truepromises the evaluator stops bycontext.deadline. The time limit is then hard. An attempt that still finishes late is recorded (late_s), and the limit is reported as soft.max_attempt_cost_usdis an upper bound on one attempt's cost. Before each attempt the search reserves it, and refuses the attempt if it wouldn't fit in what's left (cost_budget_insufficient_for_next_attempt). The cost limit is then hard as long as no attempt exceeds its bound. One that does is recorded (cost_bound_exceeded), and the limit is reported as soft.
Declare only what your evaluator really guarantees: the report calls a limit hard on the strength of these declarations. A provider that bills without returning a usage figure can't be capped by AgentLoop alone.
process_evaluator(command, cwd=...) runs a command per attempt (an argv, no
shell) that prints the result as JSON on its last output line. It stops the
command and the processes it started when the time budget runs out or the
search is cancelled, so its time limit is hard.
How cost is counted¶
Unknown consumption is never counted as zero:
- Every attempt's cost counts, including failed, errored and interrupted ones.
Report it as
cost_usdin an error result ({"status": "error", "cost_usd": 0.02}), or raiseAttemptFailedError(reason, cost_usd=...). - Any other exception, or a result without
cost_usd, has unknown cost. It counts atmax_attempt_cost_usdwhen you declared one. Without a bound, a cost budget can't be checked, so the search stops withcost_unknown. - An attempt still running when the search is cancelled is kept as
interrupted, with its cost. Its metrics aren't used, and it's never retried.
The report¶
| Field | Contents |
|---|---|
attempts |
Every evaluation in order, with its phase, interventions, case, status, metrics and cost_usd (null when unknown). Includes the baseline, failures, invalid results and interruptions. |
candidates |
Each combination's mean metrics, whether it kept quality, and which cases regressed or failed |
pareto |
Combinations that keep quality and aren't beaten on every objective |
held_out |
Baseline and selected results on held-out cases, and the net gain per objective |
decision |
recommend_for_review, no_improvement, rejected (held-out quality fell, or the gain didn't hold), indeterminate (with an acceptance contract: not enough evidence) or incomplete, and the policy that decided. A recommendation includes the combination's measured interaction: its gain minus the sum of its parts' gains. |
planned_attempts |
Attempts each phase needs, fixed before the search starts. Combinations are adaptive, so only their maximum is known. |
budget |
For attempts, time and cost: the limit, what was used, any overshoot, how it was enforced, whether it was a hard limit, and the stop reason. Cost shows the measured total and an upper bound that includes the bound of each unknown-cost attempt. |
overhead |
Attempts, elapsed time and evaluation time: the cost of searching |
report_sha256 |
A digest of everything except wall-clock times. The same seed and results give the same digest. |
deployed |
Always false |
Limits¶
- Greedy search can miss a combination whose parts look poor alone but work
well together. Raise
max_combination_size, or evaluate that combination directly, if you suspect one. - A handful of tuning and held-out cases is a small sample. Treat a recommendation as a candidate for a proper paired study, not a settled result.
- Keep held-out cases for final checks only. Once a held-out result has influenced a choice, it's no longer held out.