Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

fix(tier3): reserve measured usage for in-flight attempts (#595)

Christopher Kevineba433872a46
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b0b9339e..0671f9c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -470,6 +470,12 @@ All notable changes to SkillEvaluator are documented in this file.
errors, instead of only the top-level `result.json`. A report re-rendered by
`tier3 view` reads the status from the run's `result.json`. Scores from the
completed trials are kept.
+- Concurrent Tier 3 budget admission now serializes one calibration unit,
+ reserves in-flight work using the largest measured per-attempt usage, and
+ waits for fresh accounting before admitting more work. Units whose estimates
+ exceed remaining capacity are denied even below the measured cap; budget
+ summaries and metadata distinguish estimate-based exhaustion. An attempt can
+ still exceed its estimate, so caps are not hard ceilings.
- Skill activation now credits a SKILL.md read wrapped in a shell, such as
`/bin/bash -lc 'cat skills/x/SKILL.md'`, which some agent harnesses record
instead of the bare command. Searches inside a wrapper (`bash -c 'grep SKILL
diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx
index c532b79c..cd484692 100644
--- a/docs/tier3-live-evaluation.mdx
+++ b/docs/tier3-live-evaluation.mdx
@@ -997,6 +997,37 @@ logical units of work. Already admitted work can take measured usage above a
cap, including on the final unit. These are admission boundaries, so a priced
cost budget does not guarantee a hard dollar cap.
+Concurrent admission reserves each in-flight attempt using the largest measured
+per-attempt usage seen so far in this run, separately for agent tokens, judge
+calls, and priced cost. Estimates come only from real telemetry. When a bounded
+dimension has no measurement yet, only one logical calibration unit (such as a
+with-skill/baseline pair) may be in flight across the run. Other workers wait
+until every admitted attempt in that unit finishes, even if its first attempt
+already provided a measurement. If bounded usage is unmeasured, admission stops
+under the existing unknown-usage rule.
+For each bounded dimension with an estimate, admission checks
+`used + (in-flight attempts + proposed attempts) × estimate` against the cap.
+If that projection exceeds a cap while work is in flight, the worker waits for
+completion and re-checks fresh usage; waiting alone does not mark attempts
+`not_run`. If the projection still exceeds a cap with nothing in flight, the
+unit is denied, even when measured usage is below the cap. Its members retain
+`reason: budget_exhausted` and add `basis: estimate`; `budget.exhausted_basis`
+also identifies estimate-based exhaustion. The budget summary shows measured
+usage and the estimated next unit, rather than implying usage reached the cap.
+Attempt-count limits and stopping on unknown bounded usage are unchanged.
+
+Reservation reduces but does not eliminate in-flight overshoot. Estimates can
+grow, an attempt can exceed its estimate, and the calibration unit is
+unestimated. A run can also stop below its cap because of an estimate. Caps
+remain admission boundaries, not hard ceilings; there is no
+hard currency ceiling. `budget.reservation` records the
+`largest_measured_attempt` policy, `estimate_per_attempt` (or `not measured`),
+`in_flight_attempts`, `waits` (all condition waits), `calibration_waits` (the
+calibration subset), and `unestimated_admissions` (attempts admitted with at
+least one bounded usage dimension still unmeasured). `estimate_denials` counts
+logical units refused after estimate-based exhaustion; `denied_unit_size`
+records the size of the unit that first caused that exhaustion.
+
`budget.status` and `exhausted_limit` describe admission decisions;
`budget.partial` records attempts left not run. Separately,
`budget.observed_overruns` maps each exceeded limit to its measured `used`,
diff --git a/src/skillevaluator/tier3/harbor/run_budget.py b/src/skillevaluator/tier3/harbor/run_budget.py
index 15f716d5..7c5fe1a5 100644
--- a/src/skillevaluator/tier3/harbor/run_budget.py
+++ b/src/skillevaluator/tier3/harbor/run_budget.py
@@ -17,6 +17,10 @@ class BudgetConfigurationError(ValueError):
"""Raised when a run budget or price file is invalid."""
+class BudgetCancelledError(BaseException):
+ """A cancelled run cannot admit more work."""
+
+
@dataclass(frozen=True)
class Price:
input_per_mtok: float
@@ -111,8 +115,19 @@ class BudgetController:
unmeasured_judge_attempts: int = 0
unmeasured_cost_attempts: int = 0
_lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
+ _condition: threading.Condition = field(init=False, repr=False)
+ _in_flight: dict[tuple[Any, ...], None] = field(default_factory=dict, repr=False)
+ _estimates: dict[str, int | float] = field(default_factory=dict, repr=False)
+ _waits: int = 0
+ _unestimated_admissions: int = 0
+ _calibration: set[tuple[Any, ...]] = field(default_factory=set, repr=False)
+ _calibration_waits: int = 0
+ _estimate_denials: int = 0
+ _denied_unit_size: int = 0
+ _cancelled: bool = False
def __post_init__(self) -> None:
+ self._condition = threading.Condition(self._lock)
for name in ("max_agent_tokens", "max_judge_calls", "max_attempts_total"):
value = getattr(self, name)
if value is not None and (not isinstance(value, int) or isinstance(value, bool) or value < 0):
@@ -127,87 +142,115 @@ class BudgetController:
return self.admit_many([{"agent": agent, "arm": arm, "case_id": case_id, "attempt": attempt}])
def admit_many(self, attempts: list[dict[str, Any]]) -> bool:
- """Atomically admit a logical unit, or record every member as not run."""
+ """Reserve a logical unit, waiting for measured in-flight work when necessary."""
if not attempts:
return True
- with self._lock:
- if self.exhausted_limit is not None:
- self.not_run.extend(
- self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts
- )
- return False
- if self.max_attempts_total is not None and self._started + len(attempts) > self.max_attempts_total:
- self.exhausted_limit = "attempts"
- self.not_run.extend(
- self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts
- )
- return False
- if self.max_agent_tokens == 0:
- self.exhausted_limit = "agent_tokens"
- elif self.max_judge_calls == 0:
- self.exhausted_limit = "judge_calls"
- elif self.max_cost_usd == 0:
- self.exhausted_limit = "cost"
- if self.exhausted_limit is not None:
- self.not_run.extend(
- self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts
+ keys = [self._attempt_key(item) for item in attempts]
+ with self._condition:
+ while True:
+ if self._cancelled:
+ raise BudgetCancelledError("Run budget admission cancelled")
+ if len(set(keys)) != len(keys) or any(key in self._in_flight for key in keys):
+ raise ValueError("Attempt is already reserved")
+ self.exhausted_limit = self._admission_limit(len(attempts))
+ if self.exhausted_limit is not None:
+ return self._deny(attempts)
+ bounded = (
+ ("agent_tokens", self.max_agent_tokens, self.used_agent_tokens),
+ ("judge_calls", self.max_judge_calls, self.used_judge_calls),
+ ("cost_usd", self.max_cost_usd, self.used_cost_usd),
)
- return False
- if self._finished and self.max_agent_tokens is not None and self.unmeasured_agent_attempts:
- self.exhausted_limit = "agent_tokens"
- elif self._finished and self.max_judge_calls is not None and self.unmeasured_judge_attempts:
- self.exhausted_limit = "judge_calls"
- elif self._finished and self.max_cost_usd is not None and self.unmeasured_cost_attempts:
- self.exhausted_limit = "cost"
- if self.exhausted_limit is not None:
- self.not_run.extend(
- self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts
- )
- return False
- if (
- self.max_agent_tokens is not None
- and self.used_agent_tokens is not None
- and self.used_agent_tokens >= self.max_agent_tokens
- ):
- self.exhausted_limit = "agent_tokens"
- elif (
- self.max_judge_calls is not None
- and self.used_judge_calls is not None
- and self.used_judge_calls >= self.max_judge_calls
- ):
- self.exhausted_limit = "judge_calls"
- elif (
- self.max_cost_usd is not None
- and self.used_cost_usd is not None
- and self.used_cost_usd >= self.max_cost_usd
- ):
- self.exhausted_limit = "cost"
- if self.exhausted_limit is not None:
- self.not_run.extend(
- self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts
+ unestimated = any(cap is not None and dimension not in self._estimates for dimension, cap, _ in bounded)
+ if self._calibration or (unestimated and self._in_flight):
+ self._waits += 1
+ self._calibration_waits += 1
+ self._condition.wait()
+ continue
+ projected_limit = next(
+ (
+ dimension
+ for dimension, cap, used in bounded
+ if (
+ cap is not None
+ and (estimate := self._estimates.get(dimension)) is not None
+ and (used or 0) + (len(self._in_flight) + len(attempts)) * estimate > cap
+ )
+ ),
+ None,
)
- return False
- self._started += len(attempts)
- return True
+ if projected_limit is not None:
+ if self._in_flight:
+ self._waits += 1
+ self._condition.wait()
+ continue
+ self.exhausted_limit = "cost" if projected_limit == "cost_usd" else projected_limit
+ self._denied_unit_size = len(attempts)
+ return self._deny(attempts)
+ if unestimated:
+ self._unestimated_admissions += len(attempts)
+ self._calibration.update(keys)
+ self._in_flight.update(dict.fromkeys(keys))
+ self._started += len(attempts)
+ return True
+
+ def _deny(self, attempts: list[dict[str, Any]]) -> bool:
+ basis = {"basis": "estimate"} if self._denied_unit_size else {}
+ if basis:
+ self._estimate_denials += 1
+ self.not_run.extend(
+ dict(self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]), **basis)
+ for item in attempts
+ )
+ return False
+
+ def _admission_limit(self, unit_size: int) -> str | None:
+ if self.exhausted_limit is not None:
+ return self.exhausted_limit
+ if self.max_attempts_total is not None and self._started + unit_size > self.max_attempts_total:
+ return "attempts"
+ if self._calibration:
+ return None
+ dimensions = (
+ ("agent_tokens", self.max_agent_tokens, self.used_agent_tokens, self.unmeasured_agent_attempts),
+ ("judge_calls", self.max_judge_calls, self.used_judge_calls, self.unmeasured_judge_attempts),
+ ("cost", self.max_cost_usd, self.used_cost_usd, self.unmeasured_cost_attempts),
+ )
+ for check in (
+ lambda cap, _used, _unmeasured: cap == 0,
+ lambda _cap, _used, unmeasured: self._finished and unmeasured,
+ lambda cap, used, _unmeasured: used is not None and used >= cap,
+ ):
+ for dimension, cap, used, unmeasured in dimensions:
+ if cap is not None and check(cap, used, unmeasured):
+ return dimension
+ return None
- def record_usage(self, usage: dict[str, Any] | None, *, model: str | None = None) -> None:
- with self._lock:
+ @staticmethod
+ def _attempt_key(attempt: dict[str, Any]) -> tuple[Any, ...]:
+ return tuple(attempt[key] for key in ("agent", "arm", "case_id", "attempt"))
+
+ def cancel(self) -> None:
+ with self._condition:
+ self._cancelled = True
+ self._condition.notify_all()
+
+ def release(self, attempt: dict[str, Any]) -> None:
+ """Finish an otherwise unrecorded reservation with unknown usage, at most once."""
+ self.record_usage(None, attempt=attempt)
+
+ def record_usage(
+ self, usage: dict[str, Any] | None, *, model: str | None = None, attempt: dict[str, Any] | None = None
+ ) -> None:
+ with self._condition:
+ key = self._attempt_key(attempt) if attempt is not None else next(iter(self._in_flight), None)
+ if attempt is not None and key not in self._in_flight:
+ return
input_tokens = _usage_number(usage, "input_tokens", "prompt_tokens", "total_prompt_tokens")
output_tokens = _usage_number(usage, "output_tokens", "completion_tokens", "total_completion_tokens")
tokens = _usage_number(usage, "total_tokens")
if tokens is None and input_tokens is not None and output_tokens is not None:
tokens = input_tokens + output_tokens
- if tokens is None:
- self.unmeasured_agent_attempts += 1
- else:
- self.used_agent_tokens = (self.used_agent_tokens or 0) + int(tokens)
- self._agent_usage_seen = True
judge_calls = _usage_number(usage, "judge_calls", "llm_call_count")
- if judge_calls is None:
- self.unmeasured_judge_attempts += 1
- else:
- self.used_judge_calls = (self.used_judge_calls or 0) + int(judge_calls)
- self._judge_usage_seen = True
cost = None
if self.price_book is not None and model and input_tokens is not None and output_tokens is not None:
price = self.price_book.price_for(model)
@@ -224,12 +267,29 @@ class BudgetController:
) / 1_000_000
if cost is None:
cost = _usage_number(usage, "cost_usd", "total_cost_usd")
+ if tokens is None:
+ self.unmeasured_agent_attempts += 1
+ else:
+ self.used_agent_tokens = (self.used_agent_tokens or 0) + int(tokens)
+ self._agent_usage_seen = True
+ if judge_calls is None:
+ self.unmeasured_judge_attempts += 1
+ else:
+ self.used_judge_calls = (self.used_judge_calls or 0) + int(judge_calls)
+ self._judge_usage_seen = True
if cost is None:
self.unmeasured_cost_attempts += 1
else:
self.used_cost_usd = (self.used_cost_usd or 0.0) + float(cost)
self._cost_usage_seen = True
+ for dimension, value in (("agent_tokens", tokens), ("judge_calls", judge_calls), ("cost_usd", cost)):
+ if value is not None:
+ self._estimates[dimension] = max(self._estimates.get(dimension, 0), value)
+ if key is not None:
+ self._in_flight.pop(key)
+ self._calibration.discard(key)
self._finished += 1
+ self._condition.notify_all()
def mark_remaining(self, attempts: list[dict[str, Any]]) -> None:
with self._lock:
@@ -261,8 +321,22 @@ class BudgetController:
"status": "exhausted" if self.exhausted_limit else "ok",
"partial": bool(self.not_run),
"exhausted_limit": self.exhausted_limit,
+ "exhausted_basis": "estimate" if self._denied_unit_size else None,
"attempts_not_run": len(self.not_run),
"not_run": list(self.not_run),
+ "reservation": {
+ "policy": "largest_measured_attempt",
+ "estimate_per_attempt": {
+ dimension: self._estimates.get(dimension, "not measured")
+ for dimension in ("agent_tokens", "judge_calls", "cost_usd")
+ },
+ "in_flight_attempts": len(self._in_flight),
+ "waits": self._waits,
+ "unestimated_admissions": self._unestimated_admissions,
+ "calibration_waits": self._calibration_waits,
+ "estimate_denials": self._estimate_denials,
+ "denied_unit_size": self._denied_unit_size,
+ },
}
metadata["observed_overruns"] = _budget_observations(metadata)[0]
return metadata
@@ -370,7 +444,24 @@ def budget_line(metadata: dict[str, Any]) -> str:
value = metadata.get("started_attempts") if key == "attempts" else used.get(key)
shown = _budget_number(value, cost=key == "cost_usd")
cap = _budget_number(limits.get(limit_key), cost=key == "cost_usd", missing="not configured")
- line = f"Budget exhausted ({label} {shown} of {cap})"
+ estimate_detail = ""
+ if metadata.get("exhausted_basis") == "estimate":
+ reservation = metadata.get("reservation")
+ reservation = reservation if isinstance(reservation, dict) else {}
+ estimates = reservation.get("estimate_per_attempt")
+ estimates = estimates if isinstance(estimates, dict) else {}
+ estimate = _measured_number(estimates.get(key))
+ size = _measured_number(reservation.get("denied_unit_size"))
+ if estimate is not None and size is not None and size > 0:
+ amount = _budget_number(estimate * size, cost=key == "cost_usd")
+ estimate_detail = (
+ f"; next attempt estimated {amount}"
+ if size == 1
+ else f"; next unit estimated {amount} for {_budget_number(size)} attempts"
+ )
+ else:
+ estimate_detail = "; next unit denied using estimated usage"
+ line = f"Budget exhausted ({label} {shown} of {cap}{estimate_detail})"
elif observations:
line = f"Budget overrun observed ({observations})"
elif incomplete:
diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py
index 586b1b0b..1aeecf74 100644
--- a/src/skillevaluator/tier3/harbor/runner.py
+++ b/src/skillevaluator/tier3/harbor/runner.py
@@ -25,7 +25,7 @@ import threading
import time
import tomllib
import unicodedata
-from collections.abc import Iterable, Iterator, Mapping, Sequence
+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, as_completed, wait
from contextlib import ExitStack, contextmanager, suppress
from dataclasses import dataclass, field, replace
@@ -878,6 +878,30 @@ class _HarborRunCancelledError(BaseException):
"""
+class _HarborCancellationEvent(threading.Event):
+ def __init__(self) -> None:
+ super().__init__()
+ self._callbacks: list[Callable[[], None]] = []
+ self._callback_lock = threading.Lock()
+
+ def add_callback(self, callback: Callable[[], None]) -> None:
+ with self._callback_lock:
+ self._callbacks.append(callback)
+ if self.is_set():
+ callback()
+
+ def remove_callback(self, callback: Callable[[], None]) -> None:
+ with self._callback_lock:
+ self._callbacks.remove(callback)
+
+ def set(self) -> None:
+ super().set()
+ with self._callback_lock:
+ callbacks = tuple(self._callbacks)
+ for callback in callbacks:
+ callback()
+
+
@dataclass(frozen=True, eq=False)
class _HarborRunCancellation:
"""Cross-thread stop request for the Harbor jobs of an interrupted run.
@@ -887,7 +911,7 @@ class _HarborRunCancellation:
setting ``forced`` (a second Ctrl+C) ends that grace period early.
"""
- requested: threading.Event = field(default_factory=threading.Event)
+ requested: _HarborCancellationEvent = field(default_factory=_HarborCancellationEvent)
forced: threading.Event = field(default_factory=threading.Event)
def raise_if_requested(self) -> None:
@@ -4769,10 +4793,16 @@ def _run_budgeted_variants(
admissions = [
{"agent": agent, "arm": variant, "case_id": task_name, "attempt": attempt} for variant, _, _ in jobs
]
- if not budget.admit_many(admissions):
- return False
+ with ExitStack() as reservations:
+ if not budget.admit_many(admissions):
+ return False
+ for admission in admissions:
+ reservations.callback(budget.release, admission)
+ return run_admitted(task_index, task_name, attempt, admissions)
+
+ def run_admitted(task_index: int, task_name: str, attempt: int, admissions: list[dict[str, Any]]) -> bool:
passed = True
- for variant, dataset, job_import_path in jobs:
+ for admission, (variant, dataset, job_import_path) in zip(admissions, jobs, strict=True):
if cancellation is not None:
cancellation.raise_if_requested()
job_name = f"{skill_name}-{agent}-{variant}-{task_name}-attempt{attempt:03d}"
@@ -4798,7 +4828,7 @@ def _run_budgeted_variants(
cancellation=cancellation,
)
job_dir = jobs_dir / job_name
- budget.record_usage(_budget_usage(job_dir), model=model)
+ budget.record_usage(_budget_usage(job_dir), model=model, attempt=admission)
with result_lock:
attempt_job_dirs[variant][(task_index, attempt)] = job_dir
if ok:
@@ -4824,17 +4854,21 @@ def _run_budgeted_variants(
break
worker_count = max(1, min(n_concurrent, len(task_names) or 1))
- with ThreadPoolExecutor(max_workers=worker_count) as executor:
- if stop_on_pass:
- futures = [executor.submit(run_case, index, task_name) for index, task_name in enumerate(task_names)]
- else:
- futures = [
- executor.submit(run_unit, index, task_name, attempt)
- for index, task_name in enumerate(task_names)
- for attempt in range(1, n_attempts + 1)
- ]
- for future in as_completed(futures):
- future.result()
+ with ExitStack() as callbacks:
+ if cancellation is not None:
+ cancellation.requested.add_callback(budget.cancel)
+ callbacks.callback(cancellation.requested.remove_callback, budget.cancel)
+ with ThreadPoolExecutor(max_workers=worker_count) as executor:
+ if stop_on_pass:
+ futures = [executor.submit(run_case, index, task_name) for index, task_name in enumerate(task_names)]
+ else:
+ futures = [
+ executor.submit(run_unit, index, task_name, attempt)
+ for index, task_name in enumerate(task_names)
+ for attempt in range(1, n_attempts + 1)
+ ]
+ for future in as_completed(futures):
+ future.result()
for variant, _, _ in jobs:
_merge_attempt_jobs(
[attempt_job_dirs[variant][key] for key in sorted(attempt_job_dirs[variant])],
diff --git a/tests/tier3/test_budget_reservation.py b/tests/tier3/test_budget_reservation.py
new file mode 100644
index 00000000..21dafd53
--- /dev/null
+++ b/tests/tier3/test_budget_reservation.py
@@ -0,0 +1,374 @@
+import threading
+from concurrent.futures import ThreadPoolExecutor
+
+import pytest
+
+from skillevaluator.tier3.harbor import runner
+from skillevaluator.tier3.harbor.run_budget import (
+ BudgetCancelledError,
+ BudgetConfigurationError,
+ BudgetController,
+ Price,
+ PriceBook,
+ budget_line,
+)
+
+
+def unit(name, size=2):
+ return [{"agent": "a", "arm": str(index), "case_id": name, "attempt": 1} for index in range(size)]
+
+
+def observe_wait(monkeypatch, budget):
+ waiting = threading.Event()
+ woke = threading.Event()
+ original = budget._condition.wait
+
+ def wait(timeout=None):
+ waiting.set()
+ result = original(timeout)
+ woke.set()
+ return result
+
+ monkeypatch.setattr(budget._condition, "wait", wait)
+ return waiting, woke
+
+
[email protected]("dimension", ["agent_tokens", "judge_calls", "cost_usd"])
+def test_reservation_projection_includes_in_flight_and_whole_unit(monkeypatch, dimension):
+ kwargs = {f"max_{dimension}": 50}
+ if dimension == "cost_usd":
+ kwargs["price_book"] = PriceBook({"model": Price(1_000_000, 1_000_000)})
+ budget = BudgetController(**kwargs)
+
+ def usage(value):
+ return {"input_tokens": value, "output_tokens": 0} if dimension != "judge_calls" else {"judge_calls": value}
+
+ budget.record_usage(usage(10), model="model")
+ active = unit("active", 4)
+ assert budget.admit_many(active)
+ waiting, _ = observe_wait(monkeypatch, budget)
+ proposed = unit("proposed", 1)
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(budget.admit_many, proposed)
+ try:
+ assert waiting.wait(5)
+ assert not future.done()
+ assert budget.metadata()["not_run"] == []
+ budget.record_usage(usage(0), model="model", attempt=active[0])
+ assert future.result(timeout=5)
+ metadata = budget.metadata()["reservation"]
+ assert metadata["estimate_per_attempt"][dimension] == 10
+ assert metadata["in_flight_attempts"] == 4
+ assert metadata["waits"] >= 1
+ finally:
+ budget.cancel()
+ for attempt in active + proposed:
+ budget.release(attempt)
+
+
+def test_wait_rechecks_usage_and_only_then_marks_not_run(monkeypatch):
+ budget = BudgetController(max_agent_tokens=25)
+ budget.record_usage({"total_tokens": 10})
+ active = unit("active", 1)
+ assert budget.admit_many(active)
+ waiting, _ = observe_wait(monkeypatch, budget)
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(budget.admit_many, unit("next"))
+ try:
+ assert waiting.wait(5)
+ assert budget.metadata()["status"] == "ok"
+ assert budget.metadata()["attempts_not_run"] == 0
+ budget.record_usage({"total_tokens": 15}, attempt=active[0])
+ assert future.result(timeout=5) is False
+ assert budget.metadata()["exhausted_limit"] == "agent_tokens"
+ assert budget.metadata()["attempts_not_run"] == 2
+ finally:
+ budget.cancel()
+
+
[email protected]("dimension", ["agent_tokens", "judge_calls", "cost_usd"])
+def test_idle_projection_denial_has_estimate_basis_and_honest_budget_line(dimension):
+ kwargs = {f"max_{dimension}": 25}
+ if dimension == "cost_usd":
+ kwargs["price_book"] = PriceBook({})
+ budget = BudgetController(**kwargs, planned=6)
+ usage_key = {"agent_tokens": "total_tokens"}.get(dimension, dimension)
+ budget.record_usage({usage_key: 10})
+ assert not budget.admit_many(unit("next"))
+ metadata = budget.metadata()
+ assert metadata["exhausted_limit"] == ("cost" if dimension == "cost_usd" else dimension)
+ assert metadata["exhausted_basis"] == "estimate"
+ assert all(row["basis"] == "estimate" and row["reason"] == "budget_exhausted" for row in metadata["not_run"])
+ assert metadata["reservation"]["waits"] == 0
+ assert metadata["reservation"]["estimate_denials"] == 1
+ assert metadata["observed_overruns"] == {}
+ label = {"agent_tokens": "agent tokens", "judge_calls": "judge calls", "cost_usd": "cost"}[dimension]
+ used, cap, estimate = ("$10.00", "$25.00", "$20.00") if dimension == "cost_usd" else ("10", "25", "20")
+ assert budget_line(metadata) == (
+ f"Budget exhausted ({label} {used} of {cap}; next unit estimated {estimate} for 2 attempts)"
+ ": 2 of 6 attempts not run; results are partial"
+ )
+ assert not budget.admit_many(unit("later", 1))
+ assert budget.metadata()["reservation"]["estimate_denials"] == 2
+ assert budget.metadata()["reservation"]["denied_unit_size"] == 2
+ assert budget.metadata()["not_run"][-1]["basis"] == "estimate"
+
+
[email protected]("dimension", ["agent_tokens", "judge_calls", "cost_usd"])
+def test_calibration_serializes_whole_unit_and_builds_largest_estimate(monkeypatch, dimension):
+ kwargs = {f"max_{dimension}": 100}
+ if dimension == "cost_usd":
+ kwargs["price_book"] = PriceBook({})
+ budget = BudgetController(**kwargs)
+ usage_key = {"agent_tokens": "total_tokens"}.get(dimension, dimension)
+ active = unit("first")
+ assert budget.admit_many(active)
+ assert budget.metadata()["reservation"] == {
+ "policy": "largest_measured_attempt",
+ "estimate_per_attempt": dict.fromkeys(["agent_tokens", "judge_calls", "cost_usd"], "not measured"),
+ "in_flight_attempts": 2,
+ "waits": 0,
+ "unestimated_admissions": 2,
+ "calibration_waits": 0,
+ "estimate_denials": 0,
+ "denied_unit_size": 0,
+ }
+ waiting, _ = observe_wait(monkeypatch, budget)
+ proposed = unit("next")
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(budget.admit_many, proposed)
+ try:
+ assert waiting.wait(5)
+ assert budget.metadata()["started_attempts"] == 2
+ assert budget.metadata()["not_run"] == []
+ waiting.clear()
+ budget.record_usage({usage_key: 5}, attempt=active[0])
+ assert waiting.wait(5)
+ assert not future.done()
+ budget.record_usage({usage_key: 10}, attempt=active[1])
+ assert future.result(timeout=5)
+ for attempt, value in zip(proposed, [0, 7], strict=True):
+ budget.record_usage({usage_key: value}, attempt=attempt)
+ budget.release(attempt)
+ finally:
+ budget.cancel()
+ metadata = budget.metadata()
+ assert metadata["finished_attempts"] == 4
+ assert metadata["used"][dimension] == 22
+ assert metadata["reservation"]["estimate_per_attempt"][dimension] == 10
+ assert metadata["reservation"]["in_flight_attempts"] == 0
+ assert metadata["reservation"]["calibration_waits"] >= 1
+ assert metadata["reservation"]["waits"] >= metadata["reservation"]["calibration_waits"]
+ assert metadata["reservation"]["unestimated_admissions"] == 2
+
+
+def test_unknown_calibration_usage_wakes_waiter_and_stops_admission(monkeypatch):
+ budget = BudgetController(max_agent_tokens=100)
+ active = unit("first")
+ assert budget.admit_many(active)
+ waiting, _ = observe_wait(monkeypatch, budget)
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(budget.admit_many, unit("next"))
+ try:
+ assert waiting.wait(5)
+ waiting.clear()
+ budget.release(active[0])
+ assert waiting.wait(5)
+ assert not future.done()
+ budget.release(active[1])
+ assert future.result(timeout=5) is False
+ finally:
+ budget.cancel()
+ metadata = budget.metadata()
+ assert metadata["unmeasured_attempts"]["agent_tokens"] == 2
+ assert metadata["reservation"]["estimate_denials"] == 0
+ assert all("basis" not in row for row in metadata["not_run"])
+
+
[email protected]("reservation", [None, {}, {"estimate_per_attempt": []}])
+def test_estimate_budget_line_remains_honest_with_missing_reservation_details(reservation):
+ budget = BudgetController(max_agent_tokens=15)
+ budget.record_usage({"total_tokens": 10})
+ assert not budget.admit_many(unit("next", 1))
+ metadata = budget.metadata()
+ assert "next attempt estimated 10" in budget_line(metadata)
+ metadata["reservation"] = reservation
+ assert "next unit denied using estimated usage" in budget_line(metadata)
+
+
[email protected]("dimension", ["agent_tokens", "judge_calls", "cost_usd"])
+def test_unknown_bounded_usage_stops_admission(dimension):
+ kwargs = {f"max_{dimension}": 100}
+ if dimension == "cost_usd":
+ kwargs["price_book"] = PriceBook({})
+ budget = BudgetController(**kwargs)
+ active = unit("first")
+ assert budget.admit_many(active)
+ budget.release(active[0])
+ budget.release(active[1])
+ assert not budget.admit_many(unit("next"))
+ assert budget.metadata()["unmeasured_attempts"][dimension] == 2
+ assert budget.metadata()["reservation"]["in_flight_attempts"] == 0
+
+
[email protected]("token_cap", [None, 100])
+def test_attempt_cap_is_atomic_and_does_not_wait_for_in_flight_attempts(token_cap):
+ budget = BudgetController(max_attempts_total=3, max_agent_tokens=token_cap)
+ assert budget.admit_many(unit("first"))
+ assert not budget.admit_many(unit("next"))
+ assert budget.metadata()["started_attempts"] == 2
+ assert budget.metadata()["reservation"]["waits"] == 0
+ assert budget.metadata()["exhausted_limit"] == "attempts"
+
+
+def test_each_dimension_keeps_its_own_largest_measurement():
+ budget = BudgetController()
+ budget.record_usage({"total_tokens": 3, "judge_calls": 5, "cost_usd": 0.4})
+ budget.record_usage({"total_tokens": 10, "judge_calls": 2, "cost_usd": 0.1})
+ assert budget.metadata()["reservation"]["estimate_per_attempt"] == {
+ "agent_tokens": 10,
+ "judge_calls": 5,
+ "cost_usd": 0.4,
+ }
+
+
+def test_measured_zero_is_an_estimate_not_unknown():
+ budget = BudgetController(max_judge_calls=5)
+ budget.record_usage({"judge_calls": 0})
+ assert budget.admit_many(unit("first"))
+ assert budget.admit_many(unit("next"))
+ assert budget.metadata()["reservation"]["unestimated_admissions"] == 0
+ assert budget.metadata()["reservation"]["estimate_per_attempt"]["judge_calls"] == 0
+
+
+def test_usage_exception_can_be_released_without_partial_accounting():
+ budget = BudgetController(max_cost_usd=1, price_book=PriceBook({}))
+ attempt = unit("first", 1)[0]
+ assert budget.admit_many([attempt])
+ with pytest.raises(BudgetConfigurationError):
+ budget.record_usage({"input_tokens": 10, "output_tokens": 10}, model="missing", attempt=attempt)
+ budget.release(attempt)
+ budget.release(attempt)
+ metadata = budget.metadata()
+ assert metadata["finished_attempts"] == 1
+ assert metadata["used"]["agent_tokens"] == "not measured"
+ assert metadata["reservation"]["in_flight_attempts"] == 0
+ assert metadata["unmeasured_attempts"]["cost_usd"] == 1
+
+
+def test_several_waiting_threads_make_progress_without_deadlock(monkeypatch):
+ budget = BudgetController(max_agent_tokens=55)
+ budget.record_usage({"total_tokens": 10})
+ active = unit("first")
+ assert budget.admit_many(active)
+ waiting, _ = observe_wait(monkeypatch, budget)
+
+ def work(index):
+ attempts = unit(str(index))
+ if not budget.admit_many(attempts):
+ return False
+ for attempt in attempts:
+ budget.record_usage({"total_tokens": 10}, attempt=attempt)
+ return True
+
+ with ThreadPoolExecutor(max_workers=6) as executor:
+ futures = [executor.submit(work, index) for index in range(6)]
+ try:
+ assert waiting.wait(5)
+ for attempt in active:
+ budget.record_usage({"total_tokens": 10}, attempt=attempt)
+ assert sum(future.result(timeout=5) for future in futures) == 1
+ finally:
+ budget.cancel()
+ assert budget.metadata()["reservation"]["in_flight_attempts"] == 0
+ assert budget.metadata()["attempts_not_run"] == 10
+
+
+def run_pairs(tmp_path, budget, cancellation=None, **kwargs):
+ return runner._run_budgeted_variants(
+ skill_name="skill",
+ agent="a",
+ jobs=[("with", tmp_path, None), ("without", tmp_path, None)],
+ task_names=kwargs.get("task_names", ["case"]),
+ env_mode="docker",
+ model="model",
+ jobs_dir=tmp_path / "jobs",
+ run_env={},
+ n_attempts=kwargs.get("n_attempts", 1),
+ n_concurrent=2,
+ pass_threshold=0.5,
+ stop_on_pass=False,
+ timeout_multiplier=1,
+ override_cpus=None,
+ override_memory_mb=None,
+ override_storage_mb=None,
+ budget=budget,
+ cancellation=cancellation,
+ )
+
+
[email protected]("path", ["success", "error", "exception", "cancel", "telemetry_exception"])
+def test_runner_releases_every_admitted_attempt_once(monkeypatch, tmp_path, path):
+ budget = BudgetController(max_agent_tokens=100)
+ cancellation = runner._HarborRunCancellation()
+
+ def harbor(**kwargs):
+ if path == "exception":
+ raise RuntimeError("job failure")
+ if path == "cancel":
+ cancellation.requested.set()
+ return path != "error", "failed" if path == "error" else ""
+
+ def usage(_path):
+ if path == "telemetry_exception":
+ raise ValueError("unreadable usage")
+ return {"total_tokens": 10}
+
+ monkeypatch.setattr(runner, "_run_harbor", harbor)
+ monkeypatch.setattr(runner, "_budget_usage", usage)
+ monkeypatch.setattr(runner, "_merge_attempt_jobs", lambda *_args: None)
+ monkeypatch.setattr(runner, "_job_passed", lambda *_args: True)
+ if path in {"success", "error"}:
+ run_pairs(tmp_path, budget, cancellation)
+ else:
+ error = {
+ "exception": RuntimeError,
+ "cancel": runner._HarborRunCancelledError,
+ "telemetry_exception": ValueError,
+ }[path]
+ with pytest.raises(error):
+ run_pairs(tmp_path, budget, cancellation)
+ metadata = budget.metadata()
+ assert metadata["started_attempts"] == metadata["finished_attempts"] == 2
+ assert metadata["reservation"]["in_flight_attempts"] == 0
+ expected_unknown = 2 if path in {"exception", "telemetry_exception"} else int(path == "cancel")
+ assert metadata["unmeasured_attempts"]["agent_tokens"] == expected_unknown
+ assert cancellation.requested._callbacks == []
+
+
+def test_cancellation_wakes_waiter_before_in_flight_job_finishes(monkeypatch, tmp_path):
+ budget = BudgetController(max_agent_tokens=35)
+ budget.record_usage({"total_tokens": 10})
+ cancellation = runner._HarborRunCancellation()
+ waiting, woke = observe_wait(monkeypatch, budget)
+ finish_job = threading.Event()
+
+ def harbor(**_kwargs):
+ assert finish_job.wait(5)
+ cancellation.raise_if_requested()
+
+ monkeypatch.setattr(runner, "_run_harbor", harbor)
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(run_pairs, tmp_path, budget, cancellation, task_names=["case", "other"])
+ try:
+ assert waiting.wait(5)
+ cancellation.requested.set()
+ assert woke.wait(5)
+ assert budget.metadata()["reservation"]["in_flight_attempts"] == 2
+ finally:
+ finish_job.set()
+ budget.cancel()
+ with pytest.raises(BudgetCancelledError):
+ future.result(timeout=5)
+ assert budget.metadata()["reservation"]["in_flight_attempts"] == 0
+ assert budget.metadata()["not_run"] == []
diff --git a/tests/tier3/test_run_budget.py b/tests/tier3/test_run_budget.py
index 3d78a9e3..cdf0c794 100644
--- a/tests/tier3/test_run_budget.py
+++ b/tests/tier3/test_run_budget.py
@@ -236,7 +236,7 @@ def test_budgeted_attempts_run_concurrently_up_to_limit(monkeypatch, tmp_path):
assert peak == 2
-def test_in_flight_agents_are_not_rejected_for_missing_usage(monkeypatch, tmp_path):
+def test_calibrated_agents_can_run_concurrently(monkeypatch, tmp_path):
barrier = threading.Barrier(2)
starts = []
lock = threading.Lock()
@@ -251,6 +251,8 @@ def test_in_flight_agents_are_not_rejected_for_missing_usage(monkeypatch, tmp_pa
monkeypatch.setattr(runner, "_run_harbor", fake_harbor)
monkeypatch.setattr(runner, "_merge_attempt_jobs", lambda *_: None)
budget = BudgetController(max_agent_tokens=100_000)
+ budget.record_usage({"total_tokens": 100})
+ monkeypatch.setattr(runner, "_budget_usage", lambda _path: {"total_tokens": 100})
def run_agent(agent):
return runner._run_budgeted_variant(
@@ -276,7 +278,7 @@ def test_in_flight_agents_are_not_rejected_for_missing_usage(monkeypatch, tmp_pa
with ThreadPoolExecutor(max_workers=2) as executor:
list(executor.map(run_agent, ["first", "second"]))
assert len(starts) == 2
- assert budget.metadata()["finished_attempts"] == 2
+ assert budget.metadata()["finished_attempts"] == 3
def test_budget_admits_both_arms_as_one_case_attempt(monkeypatch, tmp_path):
@@ -441,7 +443,7 @@ def test_partial_budget_run_collects_real_harbor_results(monkeypatch, tmp_path):
jobs_dir / "skill-agent-with",
{case_id: case_id for case_id in ("case-1", "case-2", "case-3")},
)
- assert len(collected) == 3, collected
+ assert len(collected) == 2, collected
results = collect_harbor_results(
"skill",
["agent"],
@@ -457,8 +459,9 @@ def test_partial_budget_run_collects_real_harbor_results(monkeypatch, tmp_path):
agent_result = results["agents"]["agent"]
assert results["partial"] is True
assert agent_result["execution_status"] == "succeeded", agent_result.get("execution_errors") or agent_result
- assert agent_result["num_trials_with"] == 3
- assert len(starts) == 6
+ assert agent_result["num_trials_with"] == 2
+ assert len(starts) == 4
+ assert all(row["basis"] == "estimate" for row in budget.not_run)
def test_fake_attempt_runner_stops_after_token_budget(monkeypatch, tmp_path):
@@ -539,9 +542,8 @@ def test_html_overview_renders_budget_warning():
def test_final_attempt_overrun_is_reported_without_changing_admission_status():
- # Retained A2 shape: all four attempts finished, but no fifth admission
- # happened to update the admission status after usage exceeded 32,000.
- budget = BudgetController(max_agent_tokens=32_000, max_judge_calls=12, max_attempts_total=4, planned=4)
+ # The final attempt can exceed its measured estimate.
+ budget = BudgetController(max_agent_tokens=40_000, max_judge_calls=12, max_attempts_total=4, planned=4)
for attempt, tokens in enumerate([10_000, 10_000, 10_000, 15_236], start=1):
assert budget.admit(agent="a", arm="with", case_id="c", attempt=attempt)
budget.record_usage({"total_tokens": tokens, "judge_calls": 3})
@@ -552,9 +554,9 @@ def test_final_attempt_overrun_is_reported_without_changing_admission_status():
assert metadata["exhausted_limit"] is None
assert metadata["attempts_not_run"] == 0
assert metadata["observed_overruns"] == {
- "agent_tokens": {"used": 45_236, "limit": 32_000, "excess": 13_236},
+ "agent_tokens": {"used": 45_236, "limit": 40_000, "excess": 5_236},
}
- assert budget_line(metadata) == "Budget overrun observed (agent tokens 45,236 of 32,000)"
+ assert budget_line(metadata) == "Budget overrun observed (agent tokens 45,236 of 40,000)"
@pytest.mark.parametrize("cached", [None, {}, {"agent_tokens": {"used": 1, "limit": 0, "excess": 1}}])