Skip to content
Open
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
29 changes: 28 additions & 1 deletion src/agent_env/cli/submitted_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@
from agent_env.task_step.context import TaskStepContext

POLL_SECONDS = 2.0
#: How long a network outage may last before following the runs gives up.
OUTAGE_SECONDS = 600.0


def _network_error(e: BaseException) -> bool:
if isinstance(e, (ConnectionError, TimeoutError)):
return True
names = {f"{c.__module__.split('.')[0]}.{c.__name__}" for c in type(e).__mro__}
return bool(names & {"httpx.TransportError", "pymongo.AutoReconnect", "pymongo.ServerSelectionTimeoutError",
"pymongo.NetworkTimeout"})


@dataclass
Expand Down Expand Up @@ -75,8 +85,25 @@ async def _submit_and_follow(submissions, runs, step_lines, *, limit=None, **sub


async def _follow(runner, submit, pending, runs: list[SubmittedRun], limit, step_lines) -> None:
failing_since = None
while True:
await _poll(runner, runs, step_lines)
try:
await _poll(runner, runs, step_lines)
except Exception as e:
if not _network_error(e):
raise
now = asyncio.get_running_loop().time()
if failing_since is None:
failing_since = now
click.echo(click.style(f"Couldn't read the runs ({type(e).__name__}: {e}); retrying for up to "
f"{OUTAGE_SECONDS:g}s", fg="yellow"), err=True)
if now - failing_since >= OUTAGE_SECONDS:
raise
await asyncio.sleep(POLL_SECONDS)
continue
Comment on lines +102 to +103

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Step details disappear after recovery

If the network drops while _step_context reads a completed step's journal, this retry resumes polling but never prints that step's details. _poll_run adds the step to run.steps before _echo_step finishes, so later polls skip it. The command can report success without showing a deployed endpoint or verifier result.

Add the step to run.steps only after its output succeeds.

Knowledge Base Used: Command-line workflows

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/cli/submitted_runs.py
Line: 102-103

Comment:
**Step details disappear after recovery**

If the network drops while `_step_context` reads a completed step's journal, this retry resumes polling but never prints that step's details. `_poll_run` adds the step to `run.steps` before `_echo_step` finishes, so later polls skip it. The command can report success without showing a deployed endpoint or verifier result.

Add the step to `run.steps` only after its output succeeds.

**Knowledge Base Used:** [Command-line workflows](https://app.greptile.com/-/switch-tenant?tenant=scale-ai&next=%2Fcustom-context%2Fknowledge-base%2Fscaleapi%2Fagentenv-framework%2F-%2Fdocs%2Fcommand-line-workflows.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

if failing_since is not None:
failing_since = None
click.echo(click.style("Reading the runs again", fg="yellow"), err=True)
while pending and (limit is None or sum(not run.done for run in runs) < limit):
tag, task, metadata, instance_id = pending.pop(0)
handle = await submit(task.id, task.version, metadata=metadata, instance_id=instance_id)
Expand Down
54 changes: 45 additions & 9 deletions src/agent_env/runner/local_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from agent_env.runner import store as run_store
from agent_env.runner.runner import KEEP_KEY, RunHandle, RunRecord, Runner, RunStatus, run_outcome
from agent_env.task.store import get_task_instance_store, new_instance_id
from agent_env.task.teardown import TERMINATE_TIMEOUT_SECONDS, teardown_run
from agent_env.task.teardown import TERMINATE_TIMEOUT_SECONDS, TORN_DOWN_KEY, _remove_folder, teardown_run, terminate

logger = logging.getLogger(__name__)
ORPHANED_ERROR = "the process running it is gone, as after a restart"
Expand All @@ -36,9 +36,13 @@ class LocalRunner(Runner):
type = "local"
runs_outlive_submitter = False
retries_infra = False
# Backoff for re-terminating sandboxes a network drop kept up.
RETRY_WAITS_SECONDS = (5, 10, 20, 40)
RETRY_TERMINATE_SECONDS = 30
# How long a run's teardown may take, from when it starts: each sandbox gets TERMINATE_TIMEOUT_SECONDS,
# and the folder of a local one is removed after that, outside it.
TEARDOWN_WAIT_SECONDS = 2 * TERMINATE_TIMEOUT_SECONDS
# and the folder of a local one is removed after that, outside it; then the retries.
TEARDOWN_WAIT_SECONDS = (2 * TERMINATE_TIMEOUT_SECONDS + sum(RETRY_WAITS_SECONDS)
+ len(RETRY_WAITS_SECONDS) * RETRY_TERMINATE_SECONDS)
# How long stop() gives a cancelled run to unwind its steps and reach its teardown.
STOP_WAIT_SECONDS = 60
# After those waits, how long stop() gives a run it cancels again before shutting down without it.
Expand Down Expand Up @@ -268,21 +272,46 @@ async def _run(self, record: RunRecord) -> None:
await self._tear_down(record.run_id, context)
except TimeoutError:
logger.warning("Run %s: stopped waiting for its teardown after %ss; what it hadn't "
"removed is still up", record.run_id, self.TEARDOWN_WAIT_SECONDS)
"removed is still up. %s", record.run_id, self.TEARDOWN_WAIT_SECONDS,
_teardown_hint(context))
finally:
self._tearing_down.discard(record.run_id)
self._abandoned.discard(record.run_id)
self._contexts.pop(record.run_id, None)
self._inflight.pop(record.run_id, None)

@staticmethod
async def _tear_down(run_id: str, context) -> None:
"""Remove what the run deployed, however it ended: nothing resumes from a local run's sandboxes."""
@classmethod
async def _tear_down(cls, run_id: str, context) -> None:
"""Remove what the run deployed, however it ended: nothing resumes from a local run's sandboxes. Sandboxes
left up are retried, then named."""
report = await teardown_run(context)
for sandbox, why in report.failed:
logger.warning("Run %s: couldn't tear down %s: %s", run_id, sandbox.sandbox_id, why)
for sandbox in report.left:
logger.warning("Run %s: %s is still up", run_id, sandbox.sandbox_id)
torn = set(context.metadata.get(TORN_DOWN_KEY) or [])
retry = [sandbox for sandbox, _ in report.failed if sandbox.sandbox_id not in torn]
async def retry_one(sandbox) -> bool:
try:
async with asyncio.timeout(cls.RETRY_TERMINATE_SECONDS):
on_this_machine = await terminate(sandbox)
except Exception as e: # noqa: BLE001 - try it again after the next wait
logger.debug("Run %s: %s still not terminated: %s", run_id, sandbox.sandbox_id, e)
return False
if on_this_machine and (why := await _remove_folder(sandbox)):
logger.warning("Run %s: couldn't remove %s's folder: %s", run_id, sandbox.sandbox_id, why)
context.metadata[TORN_DOWN_KEY] = [*context.metadata.get(TORN_DOWN_KEY, []), sandbox.sandbox_id]
logger.info("Run %s: terminated %s on a retry", run_id, sandbox.sandbox_id)
return True

for wait in cls.RETRY_WAITS_SECONDS:
if not retry:
break
await asyncio.sleep(wait)
done = await asyncio.gather(*(retry_one(sandbox) for sandbox in retry))
retry = [sandbox for sandbox, ok in zip(retry, done) if not ok]
up = [sandbox.sandbox_id for sandbox in (*retry, *report.left)]
if up:
logger.warning("Run %s: %d sandbox(es) may still be up: %s. %s", run_id, len(up), ", ".join(up),
_teardown_hint(context))

def _finish(self, run_id: str, context, *, exc: Optional[BaseException] = None) -> None:
"""Persist the terminal state of a finished Task.run(), by ``run_outcome``."""
Expand Down Expand Up @@ -310,6 +339,13 @@ def _seed_context(self, record: RunRecord, stored):
return context


def _teardown_hint(context) -> str:
"""The command that removes what a run left up, once the stores and the sandbox backend can be reached again."""
instance_id = context.metadata.get("instance_id")
return (f"Stop them with: agent-env task teardown --instance {instance_id} --force" if instance_id
else "Stop them with: agent-env task teardown --instance <the run's instance> --force")


def _may_still_run(record: RunRecord, owned: tuple[str, ...]) -> bool:
"""Whether, by a fresh read of the run index, ``record``'s instance may still be played: ``record`` has ended or its
owner is alive after all, or another run in flight on the instance may still be running. The reconciler listed
Expand Down
27 changes: 27 additions & 0 deletions tst/unit/cli/submit_runs_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,13 +190,40 @@ async def stop(self):
def test_an_error_following_the_runs_still_stops_the_runner(monkeypatch, local_stores):
runner = _Runner(status_error=RuntimeError("run index unreachable"))
local_stores.set_runner(runner)
monkeypatch.setattr(submitted_runs, "OUTAGE_SECONDS", 0)

result = _invoke(monkeypatch, _Task(), "task", "run", "--id", "t")

assert isinstance(result.exception, RuntimeError)
assert runner.stopped


class _Blips(_Runner):
"""Its run index can't be read for the first ``blips`` polls, as when the network drops for a moment."""

def __init__(self, blips, **kwargs):
super().__init__(**kwargs)
self.blips, self.polls = blips, 0

async def status(self, run_id):
self.polls += 1
if self.polls <= self.blips:
raise ConnectionError("nodename nor servname provided, or not known")
return self.records[run_id]


def test_a_network_blip_reading_the_runs_doesnt_end_them(monkeypatch, local_stores):
runner = _Blips(blips=3)
local_stores.set_runner(runner)
monkeypatch.setattr(submitted_runs, "POLL_SECONDS", 0.01)

result = _invoke(monkeypatch, _Task(), "task", "run", "--id", "t")

assert result.exit_code == 0, result.output
assert "retrying for up to" in result.output and "Reading the runs again" in result.output
assert runner.polls > 3 and runner.stopped


def test_a_first_ctrl_c_lets_the_runner_finish_stopping(monkeypatch, local_stores):
runner = _Runner(stop_seconds=2.0)
local_stores.set_runner(runner)
Expand Down
91 changes: 91 additions & 0 deletions tst/unit/runner/local_runner_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,63 @@ async def test_conformance(case, local_stores, monkeypatch):
await runner.stop()


@pytest.mark.asyncio
async def test_a_sandbox_the_network_kept_up_is_terminated_on_a_retry(monkeypatch, caplog):
"""A sandbox a network drop kept up is terminated on a retry."""
from agent_env.runner import local_runner
from agent_env.task.teardown import TORN_DOWN_KEY, RecordedSandbox, TeardownReport
from agent_env.task_step.context import TaskStepContext

vm = RecordedSandbox("sb-vm", "modal_vm", "env")
tries = []

async def teardown_run(context):
return TeardownReport(failed=((vm, "ConnectError: nodename nor servname provided"),))

async def terminate(sandbox):
tries.append(sandbox.sandbox_id)
if len(tries) < 2:
raise ConnectionError("nodename nor servname provided")
return False

monkeypatch.setattr(local_runner, "teardown_run", teardown_run)
monkeypatch.setattr(local_runner, "terminate", terminate)
monkeypatch.setattr(LocalRunner, "RETRY_WAITS_SECONDS", (0, 0, 0))
context = TaskStepContext(metadata={"instance_id": "inst-1"})

with caplog.at_level("WARNING"):
await LocalRunner._tear_down("run-1", context)

assert tries == ["sb-vm", "sb-vm"]
assert context.metadata[TORN_DOWN_KEY] == ["sb-vm"]
assert "may still be up" not in caplog.text


@pytest.mark.asyncio
async def test_what_a_teardown_couldnt_close_is_named_with_the_command_that_does(monkeypatch, caplog):
from agent_env.runner import local_runner
from agent_env.task.teardown import RecordedSandbox, TeardownReport
from agent_env.task_step.context import TaskStepContext

vm, judge = RecordedSandbox("sb-vm", "modal_vm", "env"), RecordedSandbox("sb-judge", "modal", "agent")

async def teardown_run(context):
return TeardownReport(failed=((vm, "ConnectError"),), left=(judge,))

async def terminate(sandbox):
raise ConnectionError("still offline")

monkeypatch.setattr(local_runner, "teardown_run", teardown_run)
monkeypatch.setattr(local_runner, "terminate", terminate)
monkeypatch.setattr(LocalRunner, "RETRY_WAITS_SECONDS", (0, 0))

with caplog.at_level("WARNING"):
await LocalRunner._tear_down("run-1", TaskStepContext(metadata={"instance_id": "inst-1"}))

assert "2 sandbox(es) may still be up: sb-vm, sb-judge" in caplog.text
assert "agent-env task teardown --instance inst-1 --force" in caplog.text


async def _reconcile_once():
runner = LocalRunner(workers=1)
await runner.start()
Expand Down Expand Up @@ -842,3 +899,37 @@ async def test_an_instance_an_episode_from_a_version_that_never_renews_is_in_fli

assert run_store.get_run("dead").status is RunStatus.RUNNING
assert find_task_instance("t-shared").status == "running"


@pytest.mark.asyncio
async def test_a_retry_round_tries_every_sandbox_at_once_and_removes_a_local_ones_folder(monkeypatch):
from agent_env.runner import local_runner
from agent_env.task.teardown import TORN_DOWN_KEY, RecordedSandbox, TeardownReport
from agent_env.task_step.context import TaskStepContext

local, remote = RecordedSandbox("sb-local", "local", "agent"), RecordedSandbox("sb-remote", "modal", "agent")
started, removed = [], []

async def teardown_run(context):
return TeardownReport(failed=((local, "ConnectError"), (remote, "ConnectError")))

async def terminate(sandbox):
started.append(sandbox.sandbox_id)
await asyncio.sleep(0.05)
return sandbox is local

async def remove_folder(sandbox):
removed.append(sandbox.sandbox_id)

monkeypatch.setattr(local_runner, "teardown_run", teardown_run)
monkeypatch.setattr(local_runner, "terminate", terminate)
monkeypatch.setattr(local_runner, "_remove_folder", remove_folder)
monkeypatch.setattr(LocalRunner, "RETRY_WAITS_SECONDS", (0,))
context = TaskStepContext(metadata={"instance_id": "inst-1"})

t0 = asyncio.get_running_loop().time()
await LocalRunner._tear_down("run-1", context)

assert asyncio.get_running_loop().time() - t0 < 0.09
assert sorted(started) == ["sb-local", "sb-remote"] and removed == ["sb-local"]
assert sorted(context.metadata[TORN_DOWN_KEY]) == ["sb-local", "sb-remote"]
Loading