Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <intent_branch> <agent_name> <model_name>")
Expand Down Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)
Expand Down
30 changes: 29 additions & 1 deletion apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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()
Expand Down Expand Up @@ -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)
Expand All @@ -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)


Expand Down
46 changes: 43 additions & 3 deletions apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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)
25 changes: 24 additions & 1 deletion apps/sandbox-executor/src/sandbox_executor/model_tiers.py
Original file line number Diff line number Diff line change
@@ -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")
Expand Down Expand Up @@ -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)
60 changes: 50 additions & 10 deletions apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand Down Expand Up @@ -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}")
Expand All @@ -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)
Loading
Loading