diff --git a/apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py b/apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py index ec1145f85..600fb0462 100644 --- a/apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py +++ b/apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py @@ -47,6 +47,7 @@ write_plan_ev, ) from sandbox_executor.plan_paths import plan_file_rel +from sandbox_executor.quota_park import rendered_quota_cause from sandbox_executor.redaction import redact_agent_secrets, redact_command, redact_command_args from sandbox_executor.touch_set import parse_touch_set_section from sandbox_executor.touch_set_overlap import broad_entries @@ -264,6 +265,14 @@ def _api_error_of(outcome: AuthoringOutcome) -> str | None: return detect_api_error(*(text for turn in outcome.turns for text in (turn.stdout, turn.stderr))) +def _quota_stop_of(outcome: AuthoringOutcome) -> str | None: + result = outcome.last + if result.returncode == 0 or (outcome.report is not None and outcome.report.usable): + return None + cause = rendered_quota_cause(result, datetime.now(UTC)) + return f"the planner agent exited with code {result.returncode} ({cause})" if cause else None + + def main(): # noqa: C901, PLR0912, PLR0915 if len(sys.argv) < 4: print("Usage: planner.py ") @@ -439,6 +448,10 @@ def build_agent_cmd(prompt_text: str) -> list[str]: if outcome is None: _fail_plan_attempt(repo_dir, plan_md_rel, agent_error) + quota_stop = _quota_stop_of(outcome) + if quota_stop is not None: + _fail_plan_attempt(repo_dir, plan_md_rel, quota_stop) + result = outcome.last report = outcome.report # why: an API failure is reported as such, never as a budget breach or a metrics failure diff --git a/apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py b/apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py index 83d719dda..1f03751b9 100644 --- a/apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py +++ b/apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py @@ -51,6 +51,8 @@ from sandbox_executor.ledger import build_execution_id from sandbox_executor.naming import MissingTickerError, model_code, ticker_for from sandbox_executor.quota_park import ExhaustedRunner, park_execution +from sandbox_executor.quota_step_down import PAYLOAD_KEY as STEP_DOWNS_KEY +from sandbox_executor.quota_step_down import execution_step_down from sandbox_executor.redaction import redact_agent_secrets @@ -110,6 +112,15 @@ def run(self) -> StageResult: context = self.context context.log("Starting Stage 3: Plan Execution") result = self._run_steps() + step_downs: list[dict[str, Any]] = [] + while result.status == StageStatus.FAILED and (step := execution_step_down(context, self.state.summary_row)): + step_downs.append(step) + # why: the retry continues the failed attempt's partial work on the next ladder model. + self.resume_partial = True + self.state = ExecuteState(start_time=self.state.start_time) + result = self._run_steps() + if step_downs: + result.payload[STEP_DOWNS_KEY] = step_downs if result.status == StageStatus.FAILED: runner = ExhaustedRunner(context.agent, context.model) park_execution(result.payload, self.state.summary_row, runner, _utc_now(), context.log) diff --git a/apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py b/apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py index 17e1bb9c3..4877657f3 100644 --- a/apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py +++ b/apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py @@ -37,6 +37,9 @@ from sandbox_executor.naming import MissingTickerError, model_code, ticker_for from sandbox_executor.plan_attempt import settle_failed_plan_attempt, snapshot_plan_attempt from sandbox_executor.plan_paths import is_row_of_plan, recorded_plan_file +from sandbox_executor.quota_park import RECORD_TIME_FORMAT, ExhaustedRunner, park_plan, read_quota_stop +from sandbox_executor.quota_step_down import PAYLOAD_KEY as STEP_DOWNS_KEY +from sandbox_executor.quota_step_down import step_down_for_quota logger = logging.getLogger(__name__) @@ -53,6 +56,7 @@ class PlanStage: plan_row: dict[str, Any] = field(default_factory=dict) plan_file: str = "" plan_content: str = "" + model_step_downs: list[dict[str, Any]] = field(default_factory=list) @property def no_plan_error(self) -> str: @@ -81,7 +85,7 @@ def adopt_existing(self) -> StageResult | None: def produce(self) -> StageResult | None: if (failure := self.prepare() or self.adopt_existing()) is not None: return failure - steps = () if self.plan_branch else (self.dispatch_planner, self.adopt_plan_branch) + steps = () if self.plan_branch else (self.dispatch_with_step_down, self.adopt_plan_branch) for step in (*steps, self.read_plan): if (failure := step()) is not None: return failure @@ -92,6 +96,9 @@ def prepare(self) -> StageResult | None: return self.fail(SKIP_PUSH_DISPATCH_ERROR) if (failure := at_stage_boundary(self.context, FlowStage.PLAN, SyncBoundary.STAGE_START)) is not None: return failure + return self.snapshot_existing_plans() + + def snapshot_existing_plans(self) -> StageResult | None: existing_plans = _snapshot_child_branches(self.repo_dir, self.intent_prefix, "P") if existing_plans is None: return self.fail( @@ -102,6 +109,23 @@ def prepare(self) -> StageResult | None: self.existing_plans = existing_plans | set(local) return None + def dispatch_with_step_down(self) -> StageResult | None: + while (failure := self.dispatch_planner()) is not None: + stop = read_quota_stop(failure.error) + if stop is None: + return failure + exhausted = ExhaustedRunner(self.context.agent, self.context.model) + record = step_down_for_quota(self.context, exhausted, stop) + if record is None: + recorded_at = datetime.now(UTC).strftime(RECORD_TIME_FORMAT) + park_plan(failure.payload, exhausted, stop, recorded_at, self.context.log) + return failure + self.model_step_downs.append(record) + # why: the refreshed snapshot holds the failed attempt's salvage branch, so it is never adopted. + if (retry_failure := self.resolve_suffix() or self.snapshot_existing_plans()) is not None: + return retry_failure + return None + def dispatch_planner(self) -> StageResult | None: context = self.context replan_feedback = str(context.intent_data.get("replan_feedback") or "").strip() @@ -182,6 +206,8 @@ def run_plan_stage(context: FlowContext) -> StageResult: return dry_run_plan_result(context, start_time, f"{intent_prefix}/{plan_id}/_", consulted_ids) failure = stage.produce() if failure is not None: + if stage.model_step_downs: + failure.payload[STEP_DOWNS_KEY] = stage.model_step_downs return failure metrics = plan_metrics(stage.repo_dir, stage.plan_content, stage.plan_row) @@ -190,6 +216,8 @@ def run_plan_stage(context: FlowContext) -> StageResult: if (end_failure := at_stage_boundary(context, FlowStage.PLAN, SyncBoundary.STAGE_END)) is not None: return end_failure payload = plan_stage_payload(context, stage.plan_branch, stage.plan_file, metrics, consulted_ids) + if stage.model_step_downs: + payload[STEP_DOWNS_KEY] = stage.model_step_downs return stage_success(context, FlowStage.PLAN, "plan", start_time, payload) diff --git a/apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py b/apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py index 3ccf9c37f..71cd93e31 100644 --- a/apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py +++ b/apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py @@ -7,6 +7,7 @@ import logging import os from datetime import UTC, datetime +from typing import Any from sandbox_executor.budgets import format_minutes from sandbox_executor.calibration import is_metadata_path @@ -27,7 +28,9 @@ from sandbox_executor.git import parse_numstat, run_git from sandbox_executor.git_revisions import qualify_branch_revision, revision_args from sandbox_executor.knowledge import ConsultEngine -from sandbox_executor.quota_park import park_review +from sandbox_executor.quota_park import ExhaustedRunner, park_review, review_quota_stop +from sandbox_executor.quota_step_down import PAYLOAD_KEY as STEP_DOWNS_KEY +from sandbox_executor.quota_step_down import step_down_for_quota from sandbox_executor.redaction import redact_agent_secrets from sandbox_executor.review_accounting import accounting_of, render_accounting_lines from sandbox_executor.review_ensemble import ConsensusVerdict @@ -156,7 +159,7 @@ def _run_review_stage_body(context: FlowContext, on_branch: list[str]) -> StageR # One adapter for the whole stage: every PR, CI, mergeability and posting call of the loop goes through it. github = GitHubAdapter(context.target_worktree, review_proxy_env(context)) - loop_res = _run_engine_review_loop(context, github=github) + loop_res, step_downs = _review_loop_with_step_down(context, github) for line in render_accounting_lines(accounting_of(loop_res)): context.log(f"[Review Loop]{line}") # The payload reports the engine's configured budget, not the remaining passes of this run. @@ -278,11 +281,13 @@ def _run_review_stage_body(context: FlowContext, on_branch: list[str]) -> StageR }, error=err_msg, ) + if step_downs: + result.payload[STEP_DOWNS_KEY] = step_downs park_review(result.payload, reviewers, end_time, context.log) context.stage_results["review"] = result return result - return build_review_stage_outcome( + outcome = build_review_stage_outcome( context, ReviewOutcomeContext( start_time=start_time, @@ -295,3 +300,38 @@ def _run_review_stage_body(context: FlowContext, on_branch: list[str]) -> StageR dry_run_simulation=dry_run_simulation, ), ) + if step_downs: + outcome.payload[STEP_DOWNS_KEY] = step_downs + return outcome + + +def _review_loop_with_step_down( + context: FlowContext, github: GitHubAdapter +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + loop_res = _run_engine_review_loop(context, github=github) + step_downs: list[dict[str, Any]] = [] + while _quota_retry_allowed(context, loop_res) and (step_down := _review_step_down(context, loop_res)): + step_downs.append(step_down) + loop_res = _run_engine_review_loop(context, github=github) + return loop_res, step_downs + + +def _quota_retry_allowed(context: FlowContext, loop_res: dict[str, Any]) -> bool: + mergeability = loop_res.get("mergeability") or {} + return not ( + (loop_res.get("consensus") or {}).get("approved") + or mergeability.get("is_dirty") + or mergeability.get("merge_state_status") == "MISSING_REF" + or loop_res.get("error") + or loop_res.get("budget_breach") + or context.review_iterations_done >= context.max_review_iterations + ) + + +def _review_step_down(context: FlowContext, loop_res: dict[str, Any]) -> dict[str, Any] | None: + found = review_quota_stop(loop_res.get("reviewers") or []) + if found is None: + return None + reviewer, stop = found + runner = ExhaustedRunner(str(reviewer.get("agent") or ""), str(reviewer.get("model") or context.model)) + return step_down_for_quota(context, runner, stop) diff --git a/apps/sandbox-executor/src/sandbox_executor/model_tiers.py b/apps/sandbox-executor/src/sandbox_executor/model_tiers.py index 0a7acefbf..982c14564 100644 --- a/apps/sandbox-executor/src/sandbox_executor/model_tiers.py +++ b/apps/sandbox-executor/src/sandbox_executor/model_tiers.py @@ -1,6 +1,9 @@ from __future__ import annotations -from sandbox_executor.agent_defaults import get_model_capabilities, normalise_model_and_effort +from collections.abc import Callable + +from sandbox_executor.agent_defaults import get_model_capabilities, normalise_agent_id, normalise_model_and_effort +from sandbox_executor.runners import runner_spec_for # why: canonical model names embed the family, so a substring match ranks every version of a family together. _FAMILY_RANKS = ("haiku", "sonnet", "opus") @@ -35,3 +38,23 @@ def next_tier(ladder: tuple[str, ...], current: str | None) -> str | None: def start_tier(runner: str, configured_model: str, ladder: tuple[str, ...]) -> str | None: configured = normalise_model_and_effort(runner, configured_model)[0] return configured if configured in ladder else (ladder[0] if ladder else None) + + +def fallback_ladder(runner: str) -> tuple[str, ...]: + spec = runner_spec_for(runner) + return spec.quota_fallback_ladder if spec is not None else () + + +def is_same_runner(runner: str, other: str) -> bool: + return normalise_agent_id(runner) == normalise_agent_id(other) + + +def next_fallback_model( + runner: str, current_model: str, *, is_available: Callable[[str], bool] | None = None +) -> str | None: + ladder = fallback_ladder(runner) + current = normalise_model_and_effort(runner, current_model)[0] + if current not in ladder: + return None + lower_rungs = ladder[ladder.index(current) + 1 :] + return next((rung for rung in lower_rungs if is_available is None or is_available(rung)), None) diff --git a/apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py b/apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py index 2c6a9e88d..1dcc98ba7 100644 --- a/apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py +++ b/apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py @@ -13,7 +13,7 @@ from typing import Any from sandbox_executor import local_llm -from sandbox_executor.agent_defaults import AGENT_IMAGE_MAPPING, normalise_agent_id +from sandbox_executor.agent_defaults import AGENT_IMAGE_MAPPING, normalise_agent_id, normalise_model_and_effort from sandbox_executor.preflight_result import PreflightResult, PreflightStatus, redact_output logger = logging.getLogger(__name__) @@ -74,10 +74,21 @@ def cooldown_dir() -> str: return os.path.join(home, *_COOLDOWN_DIR_PARTS) +def _safe_filename(name: str) -> str: + return _SAFE_FILENAME_RE.sub("_", name).strip("._") or "unknown" + + def marker_path(agent: str) -> str: - provider = normalise_agent_id(agent) - safe_name = _SAFE_FILENAME_RE.sub("_", provider).strip("._") or "unknown" - return os.path.join(cooldown_dir(), f"{safe_name}.json") + return os.path.join(cooldown_dir(), f"{_safe_filename(normalise_agent_id(agent))}.json") + + +def _canonical_model(agent: str, model: str) -> str: + return normalise_model_and_effort(normalise_agent_id(agent), model)[0] + + +def model_marker_path(agent: str, model: str) -> str: + provider = _safe_filename(normalise_agent_id(agent)) + return os.path.join(cooldown_dir(), f"{provider}--{_safe_filename(_canonical_model(agent, model))}.json") def _clamp_ttl(seconds: float) -> float: @@ -173,7 +184,14 @@ def _unlink_best_effort(path: str) -> None: def read_active_cooldown(agent: str, *, now: float | None = None) -> CooldownMarker | None: - path = marker_path(agent) + return _read_marker_at(marker_path(agent), now=now) + + +def read_active_model_cooldown(agent: str, model: str, *, now: float | None = None) -> CooldownMarker | None: + return _read_marker_at(model_marker_path(agent, model), now=now) + + +def _read_marker_at(path: str, *, now: float | None) -> CooldownMarker | None: try: with open(path, encoding="utf-8") as fh: payload = json.load(fh) @@ -213,18 +231,35 @@ def record_cooldown( now: float | None = None, ttl_seconds: float | None = None, ) -> CooldownMarker | None: + return _write_marker(marker_path(agent), _build_marker(agent, model, output, now, ttl_seconds)) + + +def record_model_cooldown( + agent: str, + model: str, + output: str, + *, + now: float | None = None, + ttl_seconds: float | None = None, +) -> CooldownMarker | None: + marker = _build_marker(agent, _canonical_model(agent, model), output, now, ttl_seconds) + return _write_marker(model_marker_path(agent, model), marker) + + +def _build_marker(agent: str, model: str, output: str, now: float | None, ttl_seconds: float | None) -> CooldownMarker: current_now = time.time() if now is None else now ttl = _clamp_ttl(ttl_seconds) if ttl_seconds is not None else parse_cooldown_ttl(output, current_now) - excerpt = redact_output(output)[-_EXCERPT_CHARS:].strip() - marker = CooldownMarker( + return CooldownMarker( provider=normalise_agent_id(agent), model=model, recorded_at=current_now, expires_at=current_now + ttl, reason="quota_exhausted", - output_excerpt=excerpt, + output_excerpt=redact_output(output)[-_EXCERPT_CHARS:].strip(), ) - path = marker_path(agent) + + +def _write_marker(path: str, marker: CooldownMarker) -> CooldownMarker | None: try: _write_marker_atomic(path, marker) except OSError as exc: @@ -237,6 +272,10 @@ def clear_cooldown(agent: str) -> None: _unlink_best_effort(marker_path(agent)) +def clear_model_cooldown(agent: str, model: str) -> None: + _unlink_best_effort(model_marker_path(agent, model)) + + def build_cooldown_result( marker: CooldownMarker, agent: str, @@ -274,7 +313,7 @@ def active_cooldown_result( # why: host-local pi mode has no cloud provider quota to enforce; keep parity with preflight._early_probe_result. if agent_id == "pi" and local_llm.local_llm_requested(): return None - marker = read_active_cooldown(agent, now=now) + marker = read_active_cooldown(agent, now=now) or read_active_model_cooldown(agent, model, now=now) if marker is None: return None resolved_image = image or AGENT_IMAGE_MAPPING.get(agent_id, f"holon/agent-{agent_id}") @@ -290,3 +329,4 @@ def sync_cooldown_for_result(result: PreflightResult, *, now: float | None = Non record_cooldown(result.agent, result.model, result.output_excerpt, now=now) elif result.ok and not result.skipped: clear_cooldown(result.agent) + clear_model_cooldown(result.agent, result.model) diff --git a/apps/sandbox-executor/src/sandbox_executor/quota_park.py b/apps/sandbox-executor/src/sandbox_executor/quota_park.py index 79366db52..0bf2054b9 100644 --- a/apps/sandbox-executor/src/sandbox_executor/quota_park.py +++ b/apps/sandbox-executor/src/sandbox_executor/quota_park.py @@ -11,6 +11,7 @@ PAYLOAD_KEY = "quota_park" PARKED_QUOTA = "parked_quota" +PLAN_STAGE = "plan" EXECUTE_STAGE = "execute" REVIEW_STAGE = "review" # why: the rendered reset drops the seconds, so the margin keeps the resume time after the real reset @@ -89,18 +90,33 @@ def park_execution( _attach(payload, build_record(EXECUTE_STAGE, runner, stop, recorded_at), log) -def park_review( +def park_plan( payload: MutableMapping[str, Any], - reviewers: Sequence[Mapping[str, Any]], + runner: ExhaustedRunner, + stop: QuotaStop, recorded_at: str, log: Callable[[str], None], ) -> None: + _attach(payload, build_record(PLAN_STAGE, runner, stop, recorded_at), log) + + +def review_quota_stop(reviewers: Sequence[Mapping[str, Any]]) -> tuple[Mapping[str, Any], QuotaStop] | None: quota_failed = [ (reviewer, stop) for reviewer in reviewers if (stop := read_quota_stop(reviewer.get("failure_reason"))) ] - if not quota_failed: + return _latest_reset(quota_failed) if quota_failed else None + + +def park_review( + payload: MutableMapping[str, Any], + reviewers: Sequence[Mapping[str, Any]], + recorded_at: str, + log: Callable[[str], None], +) -> None: + found = review_quota_stop(reviewers) + if found is None: return - reviewer, stop = _latest_reset(quota_failed) + reviewer, stop = found runner = ExhaustedRunner(str(reviewer.get("agent") or ""), str(reviewer.get("model") or "")) _attach(payload, build_record(REVIEW_STAGE, runner, stop, recorded_at), log) diff --git a/apps/sandbox-executor/src/sandbox_executor/quota_step_down.py b/apps/sandbox-executor/src/sandbox_executor/quota_step_down.py new file mode 100644 index 000000000..d8dd0c3df --- /dev/null +++ b/apps/sandbox-executor/src/sandbox_executor/quota_step_down.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +from collections.abc import Mapping +from datetime import UTC, datetime +from typing import Any, Protocol + +from sandbox_executor.model_tiers import is_same_runner, next_fallback_model +from sandbox_executor.preflight_cooldown import read_active_model_cooldown, record_model_cooldown +from sandbox_executor.quota_park import ( + RECORD_TIME_FORMAT, + RENDERED_RESET_FORMAT, + RESUME_MARGIN, + ExhaustedRunner, + QuotaStop, + read_quota_stop, +) + +PAYLOAD_KEY = "model_step_downs" + + +class StepDownTarget(Protocol): + agent: str + model: str + + def log(self, message: str) -> None: ... + + +def step_down_for_quota( + context: StepDownTarget, exhausted: ExhaustedRunner, stop: QuotaStop, *, now: datetime | None = None +) -> dict[str, Any] | None: + if not is_same_runner(exhausted.agent, context.agent): + return None + moment = now or datetime.now(UTC) + _record_exhausted_model(exhausted, stop, moment) + replacement = next_fallback_model( + context.agent, + exhausted.model, + is_available=lambda rung: read_active_model_cooldown(context.agent, rung, now=moment.timestamp()) is None, + ) + if replacement is None: + return None + record = _step_down_record(exhausted, stop, replacement, moment) + context.model = replacement + resume = f"resume after {record['resume_after']}" if record["resume_after"] else "no reset time was named" + context.log( + f"Quota step-down: {exhausted.agent} / {exhausted.model} is out of quota ({resume}); " + f"continuing on {replacement}." + ) + return record + + +def execution_step_down(context: StepDownTarget, summary_row: Mapping[str, Any] | None) -> dict[str, Any] | None: + stop = read_quota_stop(summary_row.get("summary")) if summary_row is not None else None + if summary_row is None or stop is None: + return None + runner = ExhaustedRunner( + str(summary_row.get("agent") or context.agent), str(summary_row.get("model") or context.model) + ) + return step_down_for_quota(context, runner, stop) + + +def _record_exhausted_model(exhausted: ExhaustedRunner, stop: QuotaStop, moment: datetime) -> None: + seconds_to_reset = (stop.reset_at - moment).total_seconds() if stop.reset_at is not None else 0.0 + cause = f"quota (resets {stop.reset_at.strftime(RENDERED_RESET_FORMAT)})" if stop.reset_at else "quota" + record_model_cooldown( + exhausted.agent, + exhausted.model, + cause, + now=moment.timestamp(), + ttl_seconds=seconds_to_reset if seconds_to_reset > 0 else None, + ) + + +def _step_down_record( + exhausted: ExhaustedRunner, stop: QuotaStop, replacement: str, moment: datetime +) -> dict[str, Any]: + resume_after = stop.reset_at + RESUME_MARGIN if stop.reset_at is not None else None + return { + "exhausted_agent": exhausted.agent, + "exhausted_model": exhausted.model, + "reset_at": stop.reset_at.strftime(RECORD_TIME_FORMAT) if stop.reset_at is not None else None, + "resume_after": resume_after.strftime(RECORD_TIME_FORMAT) if resume_after is not None else None, + "replacement_model": replacement, + "recorded_at": moment.strftime(RECORD_TIME_FORMAT), + } diff --git a/apps/sandbox-executor/src/sandbox_executor/runners/antigravity.py b/apps/sandbox-executor/src/sandbox_executor/runners/antigravity.py index e7f49e3d5..a0f828d58 100644 --- a/apps/sandbox-executor/src/sandbox_executor/runners/antigravity.py +++ b/apps/sandbox-executor/src/sandbox_executor/runners/antigravity.py @@ -124,4 +124,5 @@ def _gemini_capability(canonical_model: str, alias: str) -> ModelCapability: harness_marker_priority=50, non_marker_env_vars=frozenset({"AGY_USER_TOKEN", "GOOGLE_API_KEY"}), session_mounts_builder=_session_mounts, + quota_fallback_ladder=("gemini-4-neon", "gemini-4-argon", "gemini-4-hydrogen", "gemini-3.8-flash"), ) diff --git a/apps/sandbox-executor/src/sandbox_executor/runners/claude.py b/apps/sandbox-executor/src/sandbox_executor/runners/claude.py index 73a99be50..bad5e8ad5 100644 --- a/apps/sandbox-executor/src/sandbox_executor/runners/claude.py +++ b/apps/sandbox-executor/src/sandbox_executor/runners/claude.py @@ -61,4 +61,5 @@ def _claude_capability(canonical_model: str, aliases: list[str]) -> ModelCapabil harness_markers=(("CLAUDECODE", "exact"), ("CLAUDE_CODE_ENTRYPOINT", "exact")), harness_marker_priority=20, session_mount_specs=(SessionMountSpec(".config/claude", _CONTAINER_SESSION_PATH),), + quota_fallback_ladder=("claude-fable-5-2", "claude-opus-5-5", "claude-sonnet-4-6", "claude-haiku-4-5"), ) diff --git a/apps/sandbox-executor/src/sandbox_executor/runners/spec.py b/apps/sandbox-executor/src/sandbox_executor/runners/spec.py index eb94c4f73..a19b54ee9 100644 --- a/apps/sandbox-executor/src/sandbox_executor/runners/spec.py +++ b/apps/sandbox-executor/src/sandbox_executor/runners/spec.py @@ -67,6 +67,7 @@ class RunnerSpec: non_marker_env_vars: frozenset[str] = frozenset() session_mount_specs: tuple[SessionMountSpec, ...] = () session_mounts_builder: Callable[[str], list[str]] | None = field(default=None, repr=False, compare=False) + quota_fallback_ladder: tuple[str, ...] = () def check_credentials(self) -> str | None: return self.credential_check(self) diff --git a/apps/sandbox-executor/tests/flow/stages/test_execute_steps.py b/apps/sandbox-executor/tests/flow/stages/test_execute_steps.py index 1d9122a7a..3314512e4 100644 --- a/apps/sandbox-executor/tests/flow/stages/test_execute_steps.py +++ b/apps/sandbox-executor/tests/flow/stages/test_execute_steps.py @@ -22,6 +22,7 @@ SUB_INTENT, SUPERSEDING_WRITER, host_remote_failure, + run_stage3, stage3_context, summary_row, ) @@ -63,11 +64,24 @@ def prepared_stage(context: FlowContext, resume_partial: bool = False, **state: return stage +@pytest.fixture(autouse=True) +def isolated_cooldown_home(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path / "home")) + + @pytest.fixture def ctx(tmp_path) -> FlowContext: return stage3_context(tmp_path) +LAST_RUNG = "claude-haiku-4-5" + + +@pytest.fixture +def last_rung_ctx(tmp_path) -> FlowContext: + return stage3_context(tmp_path, model=LAST_RUNG) + + def test_steps_run_in_the_documented_order(ctx): stage = ExecuteStage(ctx) assert [step.__name__ for step in stage.steps()] == [ @@ -378,34 +392,36 @@ def parked_lines(ctx: FlowContext) -> list[str]: (("check_container_outcome",), "failure", 1), ], ) -def test_failed_quota_run_records_the_park_on_each_path(ctx, steps, row_status, exit_code): +def test_failed_quota_run_records_the_park_on_each_path(last_rung_ctx, steps, row_status, exit_code): row = summary_row(row_status, summary=QUOTA_SUMMARY) - result = run_only(prepared_stage(ctx, summary_row=row, exit_code=exit_code), *steps) + result = run_only(prepared_stage(last_rung_ctx, summary_row=row, exit_code=exit_code), *steps) record = result.payload["quota_park"] assert result.status == StageStatus.FAILED assert (record["status"], record["stage"]) == ("parked_quota", "execute") assert (record["reset_at"], record["resume_after"]) == ("2026-11-27T10:30:00Z", "2026-11-27T10:31:00Z") assert re.fullmatch(SECONDS_STAMP, record["recorded_at"]) - assert ctx.stage_results["execute"].payload["quota_park"] is record - assert len(parked_lines(ctx)) == 1 + assert last_rung_ctx.stage_results["execute"].payload["quota_park"] is record + assert len(parked_lines(last_rung_ctx)) == 1 -def test_recorded_status_error_text_is_unchanged_by_the_park(ctx): - result = run_only(prepared_stage(ctx, summary_row=summary_row("failure", summary=QUOTA_SUMMARY))) +def test_recorded_status_error_text_is_unchanged_by_the_park(last_rung_ctx): + result = run_only(prepared_stage(last_rung_ctx, summary_row=summary_row("failure", summary=QUOTA_SUMMARY))) assert result.error == RECORDED_STATUS_ERROR @pytest.mark.parametrize("exit_code", [3, 1]) -def test_exit_code_error_text_is_unchanged_by_the_park(ctx, exit_code): +def test_exit_code_error_text_is_unchanged_by_the_park(last_rung_ctx, exit_code): row = summary_row("failure", summary=QUOTA_SUMMARY) - result = run_only(prepared_stage(ctx, summary_row=row, exit_code=exit_code), "check_container_outcome") + result = run_only(prepared_stage(last_rung_ctx, summary_row=row, exit_code=exit_code), "check_container_outcome") assert result.error == f"Execute stage failed: executor agent exited with code {exit_code}." def test_empty_diff_error_text_is_unchanged_by_the_park(tmp_path): row = summary_row("failure", summary=QUOTA_SUMMARY) - parked = run_only(prepared_stage(stage3_context(tmp_path / "a"), summary_row=row), "guard_empty_diff") - unparked_stage = prepared_stage(stage3_context(tmp_path / "b"), summary_row=row) + parked = run_only( + prepared_stage(stage3_context(tmp_path / "a", model=LAST_RUNG), summary_row=row), "guard_empty_diff" + ) + unparked_stage = prepared_stage(stage3_context(tmp_path / "b", model=LAST_RUNG), summary_row=row) with ( patch(f"{EXECUTE}._resolve_branch_ref", return_value="plan-sha"), patch(f"{EXECUTE}.changed_paths", return_value=[]), @@ -416,25 +432,25 @@ def test_empty_diff_error_text_is_unchanged_by_the_park(tmp_path): assert parked.error == unparked.error -def test_bare_quota_summary_records_null_times(ctx): +def test_bare_quota_summary_records_null_times(last_rung_ctx): row = summary_row("failure", summary="Plan execution failed with exit code 3 (quota)") - record = run_only(prepared_stage(ctx, summary_row=row)).payload["quota_park"] + record = run_only(prepared_stage(last_rung_ctx, summary_row=row)).payload["quota_park"] assert (record["reset_at"], record["resume_after"]) == (None, None) - assert "no reset time was named" in parked_lines(ctx)[0] + assert "no reset time was named" in parked_lines(last_rung_ctx)[0] @pytest.mark.parametrize( ("named", "expected"), [ ({"agent": "codex-agent", "model": "gpt-9"}, ("codex-agent", "gpt-9")), - ({}, ("claude-agent", "claude-opus-5-5")), + ({}, ("claude-agent", LAST_RUNG)), ], ) -def test_exhausted_runner_comes_from_the_row_then_the_context(ctx, named, expected): +def test_exhausted_runner_comes_from_the_row_then_the_context(last_rung_ctx, named, expected): row = summary_row("failure", summary=QUOTA_SUMMARY, **named) - record = run_only(prepared_stage(ctx, summary_row=row)).payload["quota_park"] + record = run_only(prepared_stage(last_rung_ctx, summary_row=row)).payload["quota_park"] assert (record["exhausted_agent"], record["exhausted_model"]) == expected - line = parked_lines(ctx)[0] + line = parked_lines(last_rung_ctx)[0] assert all(part in line for part in (*expected, "2026-11-27T10:31:00Z")) @@ -462,3 +478,73 @@ def test_successful_run_has_no_park(ctx): assert result.status == StageStatus.SUCCESS assert "quota_park" not in result.payload assert parked_lines(ctx) == [] + + +def test_quota_failure_steps_down_and_retries_from_the_partial_work(ctx): + stage = prepared_stage(ctx, summary_row=summary_row("failure", summary=QUOTA_SUMMARY)) + start_time = stage.state.start_time + attempts: list[tuple[str, bool, str, Any]] = [] + + def run_steps() -> StageResult: + attempts.append((ctx.model, stage.resume_partial, stage.state.start_time, stage.state.summary_row)) + if len(attempts) == 1: + return stage._fail(RECORDED_STATUS_ERROR) + return StageResult(stage=FlowStage.EXECUTE, status=StageStatus.SUCCESS, payload={"status": "success"}) + + stage._run_steps = run_steps # type: ignore[method-assign] + result = stage.run() + + assert result.status == StageStatus.SUCCESS + assert [attempt[:3] for attempt in attempts] == [ + ("claude-opus-5-5", False, start_time), + ("claude-sonnet-4-6", True, start_time), + ] + assert attempts[1][3] is None + [step_down] = result.payload["model_step_downs"] + assert (step_down["exhausted_model"], step_down["replacement_model"]) == ("claude-opus-5-5", "claude-sonnet-4-6") + assert "quota_park" not in result.payload + assert parked_lines(ctx) == [] + + +def test_step_down_redispatches_the_executor_on_the_next_rung_with_its_partial_head(ctx): + partial = f"{PLAN_PREFIX}/E-2-claude-agent-CO5.5/_" + rows = [[summary_row("failure", summary=QUOTA_SUMMARY)], [summary_row()]] + result, mocks = run_stage3( + ctx, + _read_ledger_rows={"side_effect": rows}, + _republish_recorded_execution={"return_value": (None, None)}, + _newest_partial_head={"return_value": (partial, "partial-sha")}, + ) + + assert result.status == StageStatus.SUCCESS, result.error + dispatched = [call.args[2] for call in mocks["_dispatch_role"].call_args_list] + assert dispatched == [ + [PLAN, "claude-agent", "claude-opus-5-5"], + [PLAN, "claude-agent", "claude-sonnet-4-6", partial], + ] + assert [record["replacement_model"] for record in result.payload["model_step_downs"]] == ["claude-sonnet-4-6"] + + +def test_quota_failures_walk_the_ladder_then_park_on_the_last_rung(ctx): + quota_row = [summary_row("failure", summary=QUOTA_SUMMARY)] + result, mocks = run_stage3(ctx, _read_ledger_rows={"return_value": quota_row}) + + assert result.status == StageStatus.FAILED + assert [call.args[2][2] for call in mocks["_dispatch_role"].call_args_list] == [ + "claude-opus-5-5", + "claude-sonnet-4-6", + LAST_RUNG, + ] + assert len(result.payload["model_step_downs"]) == 2 + assert (result.payload["quota_park"]["stage"], result.payload["quota_park"]["exhausted_model"]) == ( + "execute", + LAST_RUNG, + ) + + +def test_non_quota_failure_makes_exactly_one_attempt(ctx): + result, mocks = run_stage3(ctx, _read_ledger_rows={"return_value": [summary_row("failure")]}) + + assert result.status == StageStatus.FAILED + assert mocks["_dispatch_role"].call_count == 1 + assert "model_step_downs" not in result.payload diff --git a/apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py b/apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py new file mode 100644 index 000000000..70bdf7716 --- /dev/null +++ b/apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pytest +from sandbox_executor.flow import StageStatus, run_intent_stage, run_plan_stage +from sandbox_executor.flow.context import FlowContext, FlowStage +from sandbox_executor.flow.dispatch import _stage_failure +from sandbox_executor.flow.stages.plan import PlanStage +from sandbox_executor.naming import model_code, ticker_for +from sandbox_executor.plan_attempt import PLAN_FAILURE_DETAIL_REL +from sandbox_executor.preflight_cooldown import model_marker_path, record_model_cooldown +from sandbox_executor.quota_park import PAYLOAD_KEY as QUOTA_PARK_KEY + +from tests.flow.helpers import FakeRoleAgents, _dispatch_context, _git + +QUOTA_DETAIL = "the planner agent exited with code 3 (quota (resets 2099-12-01T05:58Z))" +QUOTA_ERROR = f"Plan stage failed: {QUOTA_DETAIL} (planner agent exited with code 1)" + + +class _QuotaThenPlanPlanner(FakeRoleAgents): + def __init__(self, root: Path, origin: Path, *, quota_attempts: int = 1) -> None: + super().__init__(root, origin) + self.quota_attempts = quota_attempts + self.salvage_branches: list[str] = [] + + def _plan(self, work: Path, args: list[str], kwargs: dict[str, Any]) -> int: + if len(self.salvage_branches) >= self.quota_attempts: + return super()._plan(work, args, kwargs) + intent_branch, agent, model = args + plan_id = f"P-{self.now()}-{ticker_for(agent)}-{model_code(model)}" + salvage_branch = f"{intent_branch.removesuffix('/_')}/{plan_id}/_" + _git(work, "checkout", "-q", "-B", salvage_branch, f"refs/remotes/origin/{intent_branch}") + (work / "plans").mkdir(exist_ok=True) + (work / "plans" / f"{plan_id}.md").write_text("# Partial plan cut off by quota\n", encoding="utf-8") + self._commit(work, f"plan: salvage {plan_id}") + detail = work / PLAN_FAILURE_DETAIL_REL + detail.parent.mkdir(parents=True, exist_ok=True) + detail.write_text(QUOTA_DETAIL, encoding="utf-8") + self.salvage_branches.append(salvage_branch) + return 1 + + +def _run_plan(host: Path, agents: FakeRoleAgents, **overrides: Any): + ctx = _dispatch_context(host, agents, **overrides) + assert run_intent_stage(ctx).status == StageStatus.SUCCESS + return ctx, run_plan_stage(ctx) + + +def test_a_quota_stop_retries_the_planner_on_the_next_rung_and_adopts_only_its_branch(flow_repos, tmp_path): + host, origin = flow_repos + agents = _QuotaThenPlanPlanner(tmp_path, origin) + ctx, result = _run_plan(host, agents) + + assert result.status == StageStatus.SUCCESS, result.error + planner_calls = [call for call in agents.calls if call["role"] == "planner"] + assert [call["args"][2] for call in planner_calls] == ["claude-opus-5-5", "claude-sonnet-4-6"] + assert ctx.model == "claude-sonnet-4-6" + assert ctx.plan_branch.endswith("-CLA-CS4.6/_") + assert ctx.plan_branch not in agents.salvage_branches + [step_down] = result.payload["model_step_downs"] + assert step_down["exhausted_model"] == "claude-opus-5-5" + assert step_down["replacement_model"] == "claude-sonnet-4-6" + assert step_down["reset_at"] == "2099-12-01T05:58:00Z" + assert QUOTA_PARK_KEY not in result.payload + assert Path(model_marker_path("claude-agent", "claude-opus-5-5")).exists() + + +def test_an_exhausted_ladder_parks_the_plan_stage(flow_repos, tmp_path): + host, origin = flow_repos + agents = _QuotaThenPlanPlanner(tmp_path, origin, quota_attempts=2) + _ctx, result = _run_plan(host, agents, model="claude-sonnet-4-6") + + assert result.status == StageStatus.FAILED + park = result.payload[QUOTA_PARK_KEY] + assert (park["stage"], park["exhausted_model"]) == ("plan", "claude-haiku-4-5") + assert park["resume_after"] == "2099-12-01T05:59:00Z" + assert [record["replacement_model"] for record in result.payload["model_step_downs"]] == ["claude-haiku-4-5"] + + +@pytest.fixture +def stage(tmp_path, monkeypatch) -> PlanStage: + monkeypatch.setenv("HOME", str(tmp_path)) + context = FlowContext( + target_worktree=str(tmp_path), intent_branch="I-1-x/_", agent="claude-agent", model="claude-opus-5-5" + ) + plan_stage = PlanStage(context, "2026-12-01T00:00:00Z", "I-1-x", str(tmp_path)) + plan_stage.resolve_suffix() + return plan_stage + + +def _failure(stage: PlanStage, error: str): + return _stage_failure(stage.context, FlowStage.PLAN, stage.start_time, error) + + +def _dispatch_with(stage: PlanStage, outcomes: list[Any]): + models: list[str] = [] + + def dispatch() -> Any: + models.append(stage.context.model) + outcome = outcomes.pop(0) + return _failure(stage, outcome) if isinstance(outcome, str) else outcome + + with ( + patch.object(stage, "dispatch_planner", side_effect=dispatch), + patch.object(stage, "snapshot_existing_plans", return_value=None) as snapshot, + ): + result = stage.dispatch_with_step_down() + return result, models, snapshot.call_count + + +def test_a_rung_in_model_cooldown_is_skipped(stage: PlanStage): + record_model_cooldown("claude-agent", "claude-sonnet-4-6", "quota", ttl_seconds=600.0) + result, models, snapshots = _dispatch_with(stage, [QUOTA_ERROR, None]) + + assert result is None + assert models == ["claude-opus-5-5", "claude-haiku-4-5"] + assert stage.preferred_suffix == "-CLA-CH4.5" + assert snapshots == 1 + + +def test_a_non_quota_failure_neither_steps_down_nor_parks(stage: PlanStage): + result, models, snapshots = _dispatch_with(stage, ["Plan stage failed: boom (planner agent exited with code 1)"]) + + assert result is not None + assert models == ["claude-opus-5-5"] + assert QUOTA_PARK_KEY not in result.payload + assert stage.model_step_downs == [] + assert snapshots == 0 + + +def test_the_last_rung_parks_without_a_retry(stage: PlanStage): + stage.context.model = "claude-haiku-4-5" + result, models, _snapshots = _dispatch_with(stage, [QUOTA_ERROR]) + + assert result is not None + assert models == ["claude-haiku-4-5"] + assert result.payload[QUOTA_PARK_KEY]["stage"] == "plan" + assert stage.context.model == "claude-haiku-4-5" diff --git a/apps/sandbox-executor/tests/flow/stages/test_review.py b/apps/sandbox-executor/tests/flow/stages/test_review.py index b2f151890..df5bcf2f5 100644 --- a/apps/sandbox-executor/tests/flow/stages/test_review.py +++ b/apps/sandbox-executor/tests/flow/stages/test_review.py @@ -11,6 +11,11 @@ from tests.flow.helpers import _verified_diff +@pytest.fixture(autouse=True) +def isolated_cooldown_home(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path / "home")) + + class TestStage4TestEvidence: """Stage 4 never records or approves a test pass that Stage 3 did not measure.""" @@ -318,3 +323,93 @@ def test_an_approved_review_has_no_park(tmp_path): assert res.status == StageStatus.APPROVED assert "quota_park" not in res.payload + + +CLAUDE_QUOTA = "quota (resets 2026-11-27T10:30Z)" + + +def _claude_quota_loop(model: str = "claude-opus-5-5", **loop: Any) -> dict[str, Any]: + from sandbox_executor.review_ensemble import ConsensusVerdict + + reviewer = {**_quota_reviewer(0, "claude-agent", CLAUDE_QUOTA), "model": model} + return { + "consensus": {"approved": False, "status": "failed"}, + "mergeability": {"is_dirty": False}, + "reviewers": [reviewer], + "ensemble_verdict": str(ConsensusVerdict.FAILED), + **loop, + } + + +def _claude_review( + tmp_path: Path, loop_results: list[dict[str, Any]], iterations_per_loop: int = 1, **fields: Any +) -> tuple[FlowContext, Any, Any]: + params: dict[str, Any] = {"agent": "claude-agent", "model": "claude-opus-5-5", **fields} + ctx = FlowContext(repo_dir=str(tmp_path), execution_branch="I-1-x/P-2-a-b/E-3-a-b/_", token_reduce=False, **params) + + def review_loop(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + ctx.review_iterations_done += iterations_per_loop + return loop_results.pop(0) + + with ( + patch("sandbox_executor.flow.stages.review.run_git", return_value=MagicMock(returncode=0, stdout="")), + patch("sandbox_executor.flow.stages.review.at_stage_boundary", return_value=None), + patch("sandbox_executor.flow.stages.review._checkout_execution_branch", return_value=None), + patch("sandbox_executor.flow.review.loop.run_review_loop", side_effect=review_loop) as loop, + ): + res = run_review_stage(ctx) + return ctx, res, loop + + +def test_a_quota_failed_reviewer_of_the_flow_runner_steps_down_and_reruns_the_loop(tmp_path): + approved = { + "consensus": {"approved": True, "status": "approved"}, + "mergeability": {"is_dirty": False}, + "reviewers": [{"status": "COMPLETED", "verdict": "APPROVED"}], + } + ctx, res, loop = _claude_review(tmp_path, [_claude_quota_loop(), approved]) + + assert loop.call_count == 2 + assert res.status == StageStatus.APPROVED + assert ctx.model == "claude-sonnet-4-6" + [step_down] = res.payload["model_step_downs"] + assert (step_down["exhausted_model"], step_down["replacement_model"]) == ("claude-opus-5-5", "claude-sonnet-4-6") + assert step_down["resume_after"] == "2026-11-27T10:31:00Z" + assert "quota_park" not in res.payload + assert any("Quota step-down" in line for line in ctx.logs) + + +def test_an_exhausted_ladder_parks_the_review_with_its_step_downs(tmp_path): + loops = [_claude_quota_loop("claude-sonnet-4-6"), _claude_quota_loop("claude-haiku-4-5")] + ctx, res, loop = _claude_review(tmp_path, loops, model="claude-sonnet-4-6") + + assert loop.call_count == 2 + assert res.status == StageStatus.FAILED + assert [record["replacement_model"] for record in res.payload["model_step_downs"]] == ["claude-haiku-4-5"] + record = res.payload["quota_park"] + assert (record["stage"], record["exhausted_agent"], record["exhausted_model"]) == ( + "review", + "claude-agent", + "claude-haiku-4-5", + ) + assert len(_parked_lines(ctx)) == 1 + + +@pytest.mark.parametrize( + ("loop_fields", "context_fields"), + [ + ({"budget_breach": {"iteration": 1, "budget_seconds": 60}}, {}), + ({"mergeability": {"is_dirty": True}}, {}), + ({"mergeability": {"is_dirty": False, "merge_state_status": "MISSING_REF"}}, {}), + ({"error": "empty_diff"}, {}), + ({}, {"max_review_iterations": 3, "iterations_per_loop": 3}), + ], + ids=["budget-breach", "dirty", "missing-ref", "loop-error", "no-iterations-left"], +) +def test_no_step_down_when_the_review_cannot_be_retried(tmp_path, loop_fields, context_fields): + ctx, res, loop = _claude_review(tmp_path, [_claude_quota_loop(**loop_fields)], **context_fields) + + assert loop.call_count == 1 + assert ctx.model == "claude-opus-5-5" + assert "model_step_downs" not in res.payload + assert res.payload["quota_park"]["exhausted_model"] == "claude-opus-5-5" diff --git a/apps/sandbox-executor/tests/test_planner_quota.py b/apps/sandbox-executor/tests/test_planner_quota.py new file mode 100644 index 000000000..70b364a71 --- /dev/null +++ b/apps/sandbox-executor/tests/test_planner_quota.py @@ -0,0 +1,72 @@ +import pathlib +import unittest +from unittest.mock import patch + +from sandbox_executor.budgets import BudgetBreach +from sandbox_executor.plan_attempt import PLAN_FAILURE_DETAIL_REL +from sandbox_executor.quota_park import read_quota_stop +from sandbox_executor.turns import TurnResult + +from tests.test_planner import API_ERROR_LINE, VALID_PLAN, _PlannerHarness, stdout_only, write_file + +ANTIGRAVITY_QUOTA = "error: Individual quota reached\nAGY_ERROR: RESOURCE_EXHAUSTED (code 429)\nResets in 1h45m23s." +CLAUDE_SPEND_LIMIT = "You've hit your monthly spend limit" + + +def stderr_only(stderr, returncode): + return lambda cmd, watch_path: TurnResult(returncode=returncode, stderr=stderr) + + +@patch.dict("os.environ", {"HOLON_AGENT_KEY": "dummy"}) +class TestPlannerQuotaClassification(unittest.TestCase): + def harness(self, turns, **kwargs): + h = _PlannerHarness(self, turns, **kwargs).run() + self.addCleanup(h.cleanup) + return h + + def failure_detail(self, h): + return (pathlib.Path(h.repo_dir) / PLAN_FAILURE_DETAIL_REL).read_text() + + def test_antigravity_resource_exhausted_names_the_quota_reset(self): + h = self.harness([stderr_only(ANTIGRAVITY_QUOTA, returncode=3)]) + self.assertEqual(h.exit_code, 1) + detail = self.failure_detail(h) + self.assertRegex(detail, r"^the planner agent exited with code 3 \(quota \(resets \S+Z\)\)$") + stop = read_quota_stop(f"Plan stage failed: {detail} (planner agent exited with code 1)") + self.assertIsNotNone(stop) + self.assertIsNotNone(stop.reset_at) + self.assertNotIn("empty or invalid plan", h.stderr) + self.assertEqual(list((pathlib.Path(h.repo_dir) / "plans").rglob("P-*.md")), []) + self.assertEqual(h.ledger_lines("plans.jsonl"), []) + self.assertFalse(h.committed()) + + def test_claude_monthly_spend_limit_reports_bare_quota(self): + h = self.harness([stderr_only(CLAUDE_SPEND_LIMIT, returncode=1)]) + self.assertEqual(h.exit_code, 1) + detail = self.failure_detail(h) + self.assertEqual(detail.strip(), "the planner agent exited with code 1 (quota)") + stop = read_quota_stop(detail) + self.assertIsNotNone(stop) + self.assertIsNone(stop.reset_at) + + def test_api_error_still_reports_the_api_failure(self): + h = self.harness([stdout_only(API_ERROR_LINE, returncode=1)]) + self.assertEqual(h.exit_code, 1) + self.assertIn("API call failed", h.stderr) + self.assertIsNone(read_quota_stop(self.failure_detail(h))) + + def test_budget_breach_keeps_its_budget_message(self): + stage_breach = BudgetBreach("plan", "stage", 2100, 2100) + h = self.harness( + [write_file(None, returncode=-15, breach=stage_breach, stdout=ANTIGRAVITY_QUOTA)], + env={"HOLON_STAGE_BUDGET_SECONDS": "0.000001"}, + ) + self.assertEqual(h.exit_code, 1) + self.assertIn("the plan is not usable", h.stderr) + self.assertEqual(len(h.ledger_lines("executions.jsonl")), 1) + + def test_usable_plan_with_a_quota_exit_still_succeeds(self): + h = self.harness([write_file(VALID_PLAN, returncode=3, stdout=ANTIGRAVITY_QUOTA)]) + self.assertEqual(h.exit_code, 0, h.stderr) + self.assertEqual(len(h.ledger_lines("plans.jsonl")), 1) + self.assertTrue(h.committed()) diff --git a/apps/sandbox-executor/tests/test_preflight_cooldown.py b/apps/sandbox-executor/tests/test_preflight_cooldown.py index 6ef78462f..5cbb13fb2 100644 --- a/apps/sandbox-executor/tests/test_preflight_cooldown.py +++ b/apps/sandbox-executor/tests/test_preflight_cooldown.py @@ -15,12 +15,19 @@ DEFAULT_COOLDOWN_SECONDS, MAX_COOLDOWN_SECONDS, MIN_COOLDOWN_SECONDS, + active_cooldown_result, clear_cooldown, + clear_model_cooldown, marker_path, + model_marker_path, parse_cooldown_ttl, read_active_cooldown, + read_active_model_cooldown, record_cooldown, + record_model_cooldown, + sync_cooldown_for_result, ) +from sandbox_executor.preflight_result import PreflightResult @pytest.fixture @@ -255,3 +262,64 @@ def _imported_dotted_names(module) -> set[str]: @pytest.mark.parametrize("module", [preflight_cooldown, preflight_result], ids=lambda module: module.__name__) def test_modules_below_preflight_never_import_preflight(module): assert "sandbox_executor.preflight" not in _imported_dotted_names(module) + + +def test_model_marker_path_shares_one_file_for_alias_and_canonical_name(isolated_cooldown_home): + expected = os.path.join(str(isolated_cooldown_home), ".holon", "preflight-cooldown", "claude--claude-opus-5-5.json") + assert model_marker_path("claude-agent", "claude-opus-5-5") == expected + assert model_marker_path("claude", "opus") == expected + assert marker_path("claude-agent") == os.path.join(os.path.dirname(expected), "claude.json") + + +def test_model_cooldown_blocks_only_its_own_model(isolated_cooldown_home): + marker = record_model_cooldown("claude-agent", "opus", "quota (resets later)", ttl_seconds=300.0) + assert marker is not None and marker.model == "claude-opus-5-5" + assert read_active_model_cooldown("claude-agent", "claude-opus-5-5") is not None + assert read_active_model_cooldown("claude-agent", "claude-sonnet-4-6") is None + assert read_active_cooldown("claude-agent") is None + assert not os.path.exists(marker_path("claude-agent")) + clear_model_cooldown("claude-agent", "claude-opus-5-5") + assert read_active_model_cooldown("claude-agent", "opus") is None + + +def test_provider_cooldown_still_blocks_every_model(isolated_cooldown_home): + record_cooldown("claude-agent", "claude-opus-5-5", "org spend limit reached", ttl_seconds=300.0) + for model in ("claude-opus-5-5", "claude-sonnet-4-6", "claude-haiku-4-5"): + assert active_cooldown_result("claude-agent", model) is not None + assert not os.path.exists(model_marker_path("claude-agent", "claude-opus-5-5")) + + +def test_model_cooldown_expires_and_corrupt_markers_are_unlinked(isolated_cooldown_home): + now = 1_700_000_000.0 + record_model_cooldown("claude-agent", "claude-opus-5-5", "quota", now=now, ttl_seconds=120.0) + path = model_marker_path("claude-agent", "claude-opus-5-5") + assert read_active_model_cooldown("claude-agent", "claude-opus-5-5", now=now + 60.0) is not None + assert read_active_model_cooldown("claude-agent", "claude-opus-5-5", now=now + 121.0) is None + assert not os.path.exists(path) + Path(path).write_text("{not json", encoding="utf-8") + assert read_active_model_cooldown("claude-agent", "claude-opus-5-5") is None + assert not os.path.exists(path) + + +def test_active_cooldown_result_reports_a_model_cooldown(isolated_cooldown_home): + record_model_cooldown("claude-agent", "claude-opus-5-5", "quota", ttl_seconds=300.0) + blocked = active_cooldown_result("claude-agent", "opus") + assert blocked is not None + assert blocked.status is PreflightStatus.QUOTA_EXHAUSTED + assert blocked.hint.startswith(COOLDOWN_HINT_PREFIX) + assert active_cooldown_result("claude-agent", "claude-sonnet-4-6") is None + + +def test_ok_preflight_clears_the_model_cooldown(isolated_cooldown_home): + record_model_cooldown("claude-agent", "claude-opus-5-5", "quota", ttl_seconds=300.0) + ok = PreflightResult( + status=PreflightStatus.OK, + agent="claude-agent", + model="claude-opus-5-5", + image="holon/agent-claude", + exit_code=0, + output_excerpt="OK", + hint="", + ) + sync_cooldown_for_result(ok) + assert not os.path.exists(model_marker_path("claude-agent", "claude-opus-5-5")) diff --git a/apps/sandbox-executor/tests/test_quota_park.py b/apps/sandbox-executor/tests/test_quota_park.py index fb3a5900d..c6abdad38 100644 --- a/apps/sandbox-executor/tests/test_quota_park.py +++ b/apps/sandbox-executor/tests/test_quota_park.py @@ -17,9 +17,11 @@ QuotaStop, build_record, park_execution, + park_plan, park_review, read_quota_stop, rendered_quota_cause, + review_quota_stop, ) from sandbox_executor.turns import TurnResult @@ -126,6 +128,31 @@ def test_record_without_reset_has_null_times() -> None: def test_stage_names_match_the_flow_stages() -> None: assert FlowStage.EXECUTE.value == quota_park.EXECUTE_STAGE assert FlowStage.REVIEW.value == quota_park.REVIEW_STAGE + assert FlowStage.PLAN.value == quota_park.PLAN_STAGE + + +def test_park_plan_records_the_planner_runner_and_logs_once() -> None: + payload: dict[str, Any] = {"plan_id": None} + logs: list[str] = [] + park_plan(payload, RUNNER, QuotaStop(datetime(2026, 11, 27, 10, 30, tzinfo=UTC)), RECORDED_AT, logs.append) + assert payload[PAYLOAD_KEY] == { + "status": PARKED_QUOTA, + "stage": "plan", + "exhausted_agent": "claude-agent", + "exhausted_model": "claude-fable-5-2", + "reset_at": "2026-11-27T10:30:00Z", + "resume_after": "2026-11-27T10:31:00Z", + "recorded_at": RECORDED_AT, + } + assert len(logs) == 1 + assert PARKED_QUOTA in logs[0] + + +def test_park_plan_with_bare_quota_records_null_times() -> None: + payload: dict[str, Any] = {} + park_plan(payload, RUNNER, QuotaStop(), RECORDED_AT, lambda _line: None) + assert payload[PAYLOAD_KEY]["reset_at"] is None + assert payload[PAYLOAD_KEY]["resume_after"] is None def _quota_row(**fields: Any) -> dict[str, Any]: @@ -207,6 +234,23 @@ def test_park_review_ignores_reviewers_without_quota_reason() -> None: assert payload == {"pr": None} +def test_review_quota_stop_finds_nothing_without_a_quota_reviewer() -> None: + assert review_quota_stop([_reviewer("a", "the reviewer exited with code 1 (timeout)")]) is None + assert review_quota_stop([]) is None + + +def test_review_quota_stop_picks_the_latest_named_reset() -> None: + reviewers = [ + _reviewer("early", _quota_reason("2026-11-27T10:30Z")), + _reviewer("late", _quota_reason("2026-11-27T12:05Z")), + ] + found = review_quota_stop(reviewers) + assert found is not None + reviewer, stop = found + assert reviewer["agent"] == "late" + assert stop.reset_at == datetime(2026, 11, 27, 12, 5, tzinfo=UTC) + + def test_record_survives_a_checkpoint_round_trip(tmp_path: Path) -> None: ctx = FlowContext(repo_dir=str(tmp_path), intent_data={"slug": "quota-park"}, token_reduce=False) ctx.stage_results["intent"] = StageResult(stage=FlowStage.INTENT, status=StageStatus.SUCCESS) diff --git a/apps/sandbox-executor/tests/test_quota_step_down.py b/apps/sandbox-executor/tests/test_quota_step_down.py new file mode 100644 index 000000000..4ecd1ae9b --- /dev/null +++ b/apps/sandbox-executor/tests/test_quota_step_down.py @@ -0,0 +1,135 @@ +import ast +import os +from dataclasses import dataclass, field +from datetime import UTC, datetime +from pathlib import Path + +import pytest +from sandbox_executor import quota_step_down +from sandbox_executor.preflight_cooldown import model_marker_path, read_active_model_cooldown, record_model_cooldown +from sandbox_executor.quota_park import ExhaustedRunner, QuotaStop +from sandbox_executor.quota_step_down import execution_step_down, step_down_for_quota + +NOW = datetime(2026, 12, 1, 4, 13, 0, tzinfo=UTC) +RESET = datetime(2026, 12, 1, 5, 58, tzinfo=UTC) +NAMED_STOP = QuotaStop(RESET) + + +@dataclass +class _Context: + agent: str + model: str + lines: list[str] = field(default_factory=list) + + def log(self, message: str) -> None: + self.lines.append(message) + + +@pytest.fixture(autouse=True) +def isolated_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: + monkeypatch.setenv("HOME", str(tmp_path)) + return tmp_path + + +def _step_down(context: _Context, stop: QuotaStop = NAMED_STOP) -> dict | None: + return step_down_for_quota(context, ExhaustedRunner(context.agent, context.model), stop, now=NOW) + + +def test_steps_from_opus_to_sonnet_and_records_the_model_cooldown(isolated_home: Path) -> None: + context = _Context("claude-agent", "claude-opus-5-5") + record = _step_down(context) + assert context.model == "claude-sonnet-4-6" + assert record == { + "exhausted_agent": "claude-agent", + "exhausted_model": "claude-opus-5-5", + "reset_at": "2026-12-01T05:58:00Z", + "resume_after": "2026-12-01T05:59:00Z", + "replacement_model": "claude-sonnet-4-6", + "recorded_at": "2026-12-01T04:13:00Z", + } + expected = isolated_home / ".holon" / "preflight-cooldown" / "claude--claude-opus-5-5.json" + assert model_marker_path("claude-agent", "claude-opus-5-5") == str(expected) + assert expected.exists() + marker = read_active_model_cooldown("claude-agent", "claude-opus-5-5", now=NOW.timestamp()) + assert marker is not None + assert marker.expires_at == pytest.approx(NOW.timestamp() + 3600.0) + + +def test_log_line_names_both_models_and_the_reset_hint() -> None: + context = _Context("claude-agent", "claude-opus-5-5") + _step_down(context) + assert len(context.lines) == 1 + line = context.lines[0] + assert all( + part in line for part in ("claude-agent", "claude-opus-5-5", "claude-sonnet-4-6", "2026-12-01T05:59:00Z") + ) + + +def test_bare_quota_records_null_times_and_says_no_reset_was_named() -> None: + context = _Context("claude-agent", "claude-opus-5-5") + record = _step_down(context, QuotaStop()) + assert record is not None + assert (record["reset_at"], record["resume_after"]) == (None, None) + assert "no reset time was named" in context.lines[0] + assert read_active_model_cooldown("claude-agent", "claude-opus-5-5", now=NOW.timestamp()) is not None + + +def test_skips_a_rung_in_active_model_cooldown() -> None: + record_model_cooldown("claude-agent", "claude-sonnet-4-6", "quota", now=NOW.timestamp(), ttl_seconds=600.0) + context = _Context("claude-agent", "claude-opus-5-5") + record = _step_down(context) + assert record is not None + assert context.model == "claude-haiku-4-5" + + +def test_last_rung_returns_none_and_keeps_the_model() -> None: + context = _Context("claude-agent", "claude-haiku-4-5") + assert _step_down(context) is None + assert context.model == "claude-haiku-4-5" + assert context.lines == [] + assert os.path.exists(model_marker_path("claude-agent", "claude-haiku-4-5")) + + +def test_antigravity_ladder_is_walked_rung_by_rung() -> None: + context = _Context("antigravity-agent", "gemini-4-neon") + walked = [context.model] + while _step_down(context) is not None: + walked.append(context.model) + assert walked == ["gemini-4-neon", "gemini-4-argon", "gemini-4-hydrogen", "gemini-3.8-flash"] + + +def test_another_runner_never_changes_the_context_model() -> None: + context = _Context("antigravity-agent", "gemini-4-neon") + runner = ExhaustedRunner("claude-agent", "claude-opus-5-5") + assert step_down_for_quota(context, runner, NAMED_STOP, now=NOW) is None + assert context.model == "gemini-4-neon" + + +def test_execution_step_down_reads_the_summary_row() -> None: + context = _Context("claude-agent", "claude-opus-5-5") + row = {"summary": "Plan execution failed with exit code 3 (quota (resets 2026-12-01T05:58Z))", "agent": ""} + record = execution_step_down(context, row) + assert record is not None + assert record["exhausted_model"] == "claude-opus-5-5" + assert context.model == "claude-sonnet-4-6" + + +@pytest.mark.parametrize("row", [None, {"summary": "Plan execution failed with exit code 1"}, {}]) +def test_execution_step_down_ignores_rows_without_a_quota_stop(row: dict | None) -> None: + context = _Context("claude-agent", "claude-opus-5-5") + assert execution_step_down(context, row) is None + assert context.model == "claude-opus-5-5" + + +def test_module_imports_only_the_standard_library_and_its_three_neighbours() -> None: + tree = ast.parse(Path(quota_step_down.__file__).read_text()) + imported = {node.module or "" for node in ast.walk(tree) if isinstance(node, ast.ImportFrom)} + imported |= {alias.name for node in ast.walk(tree) if isinstance(node, ast.Import) for alias in node.names} + allowed_internal = { + "sandbox_executor.model_tiers", + "sandbox_executor.preflight_cooldown", + "sandbox_executor.quota_park", + } + internal = {name for name in imported if name.startswith("sandbox_executor")} + assert internal == allowed_internal + assert imported - internal <= {"__future__", "collections.abc", "datetime", "typing"} diff --git a/apps/sandbox-executor/tests/test_runner_specs.py b/apps/sandbox-executor/tests/test_runner_specs.py index e962fa5c2..6fb8731ef 100644 --- a/apps/sandbox-executor/tests/test_runner_specs.py +++ b/apps/sandbox-executor/tests/test_runner_specs.py @@ -7,9 +7,11 @@ import pytest from sandbox_executor import claude_keychain +from sandbox_executor.agent_defaults import normalise_model_and_effort from sandbox_executor.launcher import antigravity_mounts as launcher_antigravity_mounts from sandbox_executor.launcher import pi_mounts as launcher_pi_mounts from sandbox_executor.launcher.mounts import get_agent_session_mounts +from sandbox_executor.model_tiers import fallback_ladder, next_fallback_model from sandbox_executor.runners import RUNNER_SPECS, ModelCapability, SessionMountSpec, runner_spec_for from sandbox_executor.runners import antigravity as antigravity_runner from sandbox_executor.runners import pi as pi_runner @@ -384,3 +386,52 @@ def test_launcher_mount_modules_reexport_the_runner_objects() -> None: assert launcher_pi_mounts.CONTAINER_HOME is pi_runner.CONTAINER_HOME assert launcher_pi_mounts.OWNED_TMPFS_OPTIONS is pi_runner.OWNED_TMPFS_OPTIONS assert launcher_pi_mounts.get_pi_mounts is pi_runner.get_pi_mounts + + +CLAUDE_LADDER = ("claude-fable-5-2", "claude-opus-5-5", "claude-sonnet-4-6", "claude-haiku-4-5") +ANTIGRAVITY_LADDER = ("gemini-4-neon", "gemini-4-argon", "gemini-4-hydrogen", "gemini-3.8-flash") + + +def test_quota_fallback_ladders_are_declared_on_the_claude_and_antigravity_specs() -> None: + assert RUNNER_SPECS["claude"].quota_fallback_ladder == CLAUDE_LADDER + assert RUNNER_SPECS["antigravity"].quota_fallback_ladder == ANTIGRAVITY_LADDER + assert fallback_ladder("claude-agent") == CLAUDE_LADDER + assert fallback_ladder("antigravity-agent") == ANTIGRAVITY_LADDER + assert fallback_ladder("unknown-agent") == () + + +@pytest.mark.parametrize("agent_id", ["pi", "codex", "opencode"]) +def test_other_runners_declare_no_quota_fallback_ladder(agent_id: str) -> None: + assert RUNNER_SPECS[agent_id].quota_fallback_ladder == () + + +@pytest.mark.parametrize( + ("runner", "rung"), + [("claude-agent", rung) for rung in CLAUDE_LADDER] + [("antigravity-agent", rung) for rung in ANTIGRAVITY_LADDER], +) +def test_every_ladder_rung_normalises_to_itself(runner: str, rung: str) -> None: + assert normalise_model_and_effort(runner, rung)[0] == rung + + +def test_every_claude_ladder_rung_is_a_canonical_capability() -> None: + canonical = {cap.canonical_model for cap in RUNNER_SPECS["claude"].model_capabilities} + assert set(CLAUDE_LADDER) <= canonical + + +def test_next_fallback_model_walks_the_ladder() -> None: + assert next_fallback_model("claude-agent", "claude-fable-5-2") == "claude-opus-5-5" + assert next_fallback_model("claude-agent", "opus") == "claude-sonnet-4-6" + assert next_fallback_model("antigravity-agent", "gemini-4-argon") == "gemini-4-hydrogen" + + +def test_next_fallback_model_skips_unavailable_rungs() -> None: + assert next_fallback_model("claude-agent", "claude-opus-5-5", is_available=lambda m: m != "claude-sonnet-4-6") == ( + "claude-haiku-4-5" + ) + assert next_fallback_model("claude-agent", "claude-opus-5-5", is_available=lambda m: False) is None + + +def test_next_fallback_model_stops_at_the_last_rung_and_off_ladder() -> None: + assert next_fallback_model("claude-agent", "claude-haiku-4-5") is None + assert next_fallback_model("antigravity-agent", "gemini-3.8-flash-medium") is None + assert next_fallback_model("pi-agent", "local-model") is None diff --git a/docs/budgets.md b/docs/budgets.md index c5487f39e..a85c645c1 100644 --- a/docs/budgets.md +++ b/docs/budgets.md @@ -187,8 +187,14 @@ credited to the review stage timer, so it never counts against the stage ceiling ## Quota stop record When an agent runner is out of quota and the stage fails, the engine records a machine-readable quota stop so an outside -driver can resume the flow at the reset time or pick another model without reading the log. The record is written when: - +driver can resume the flow at the reset time or pick another model without reading the log. A quota stop first steps +down the runner's fallback ladder (see "Quota step-down" below); the record is written only when no lower rung is +available, or when the quota-failed runner is not the flow's own. The record is written when: + +- Stage 2 fails because the planner agent exited non-zero on a quota or a monthly spend limit without writing a usable + plan. The planner's failure detail then reads `the planner agent exited with code (quota (resets