From 50009b3e5f9528edcfaa07b74e6c760d54ba3d30 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 11:27:40 -0800 Subject: [PATCH 1/3] local task run: keep following runs through a network blip; retry teardown and name what's left up A single failed read of the run index (a laptop losing DNS for a moment) made the CLI stop following, which stopped the LocalRunner and cancelled runs that were still working; their teardown then failed on the same outage and left every sandbox up until its TTL. - submitted_runs: a failed poll is retried for up to OUTAGE_SECONDS (10 min) before giving up. - LocalRunner: a sandbox the teardown couldn't terminate is tried again with backoff, and what is still up is logged with the agent-env task teardown command that removes it. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/cli/submitted_runs.py | 20 +++++++++- src/agent_env/runner/local_runner.py | 53 +++++++++++++++++++++----- tst/unit/cli/submit_runs_test.py | 27 +++++++++++++ tst/unit/runner/local_runner_test.py | 57 ++++++++++++++++++++++++++++ 4 files changed, 147 insertions(+), 10 deletions(-) diff --git a/src/agent_env/cli/submitted_runs.py b/src/agent_env/cli/submitted_runs.py index 5ef2ef079..040f5fef7 100644 --- a/src/agent_env/cli/submitted_runs.py +++ b/src/agent_env/cli/submitted_runs.py @@ -19,6 +19,9 @@ from agent_env.task_step.context import TaskStepContext POLL_SECONDS = 2.0 +#: How long reading the runs may keep failing before following them gives up (and, for a ``LocalRunner``, stops and +#: tears them down). A network blip mid-run must not end runs that are still working. +OUTAGE_SECONDS = 600.0 @dataclass @@ -75,8 +78,23 @@ 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: + 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 + 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) diff --git a/src/agent_env/runner/local_runner.py b/src/agent_env/runner/local_runner.py index 400dd1ef7..576036b1c 100644 --- a/src/agent_env/runner/local_runner.py +++ b/src/agent_env/runner/local_runner.py @@ -22,7 +22,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 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, teardown_run, terminate logger = logging.getLogger(__name__) @@ -33,9 +33,14 @@ class LocalRunner(Runner): type = "local" runs_outlive_submitter = False retries_infra = False + # A sandbox that wasn't terminated (the network dropped, say) is tried again after each of these waits, each try + # within RETRY_TERMINATE_SECONDS. + 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. @@ -257,21 +262,44 @@ 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. A sandbox + that wasn't terminated is tried again, backing off, since a network drop that ended the run often fails its + teardown too; what is still up at the end is named with the command that removes it.""" 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] + for wait in cls.RETRY_WAITS_SECONDS: + if not retry: + break + await asyncio.sleep(wait) + still = [] + for sandbox in retry: + try: + async with asyncio.timeout(cls.RETRY_TERMINATE_SECONDS): + 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) + still.append(sandbox) + continue + 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) + retry = still + 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``.""" @@ -299,6 +327,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 --force") + + def _owner_alive(owner: Optional[dict]) -> bool: """Whether the process that submitted a run may still be running it: on this host, whether its pid is alive; on another, whether it marked the run seen within ``OWNER_LEASE_SECONDS``. A run naming no owner predates owners.""" diff --git a/tst/unit/cli/submit_runs_test.py b/tst/unit/cli/submit_runs_test.py index 981e3ce9d..6baaec07d 100644 --- a/tst/unit/cli/submit_runs_test.py +++ b/tst/unit/cli/submit_runs_test.py @@ -190,6 +190,7 @@ 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") @@ -197,6 +198,32 @@ def test_an_error_following_the_runs_still_stops_the_runner(monkeypatch, local_s 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) diff --git a/tst/unit/runner/local_runner_test.py b/tst/unit/runner/local_runner_test.py index 1b94fafe7..1d3d81a40 100644 --- a/tst/unit/runner/local_runner_test.py +++ b/tst/unit/runner/local_runner_test.py @@ -694,3 +694,60 @@ async def test_conformance(case, local_stores, monkeypatch): await case(runner) finally: await runner.stop() + + +@pytest.mark.asyncio +async def test_a_sandbox_the_network_kept_up_is_terminated_on_a_retry(monkeypatch, caplog): + """A network drop that ended the run often fails its teardown too: the sandbox is tried again until it goes.""" + 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 From 1fd7f70138d393be4e73e587b0c9d68e8f0170ea Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 23:08:27 -0800 Subject: [PATCH 2/3] local run: retry only network errors while following runs; shorter comments Co-Authored-By: Claude Opus 5.5 --- src/agent_env/runner/local_runner.py | 8 +++----- tst/unit/runner/local_runner_test.py | 2 +- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/agent_env/runner/local_runner.py b/src/agent_env/runner/local_runner.py index 51aafdd7e..cb6cd8172 100644 --- a/src/agent_env/runner/local_runner.py +++ b/src/agent_env/runner/local_runner.py @@ -36,8 +36,7 @@ class LocalRunner(Runner): type = "local" runs_outlive_submitter = False retries_infra = False - # A sandbox that wasn't terminated (the network dropped, say) is tried again after each of these waits, each try - # within RETRY_TERMINATE_SECONDS. + # 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, @@ -283,9 +282,8 @@ async def _run(self, record: RunRecord) -> None: @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. A sandbox - that wasn't terminated is tried again, backing off, since a network drop that ended the run often fails its - teardown too; what is still up at the end is named with the command that removes it.""" + """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) diff --git a/tst/unit/runner/local_runner_test.py b/tst/unit/runner/local_runner_test.py index c2142667c..9847226f5 100644 --- a/tst/unit/runner/local_runner_test.py +++ b/tst/unit/runner/local_runner_test.py @@ -710,7 +710,7 @@ async def test_conformance(case, local_stores, monkeypatch): @pytest.mark.asyncio async def test_a_sandbox_the_network_kept_up_is_terminated_on_a_retry(monkeypatch, caplog): - """A network drop that ended the run often fails its teardown too: the sandbox is tried again until it goes.""" + """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 From 3a441b1db048e43fce18546f6a2c48228e58eb45 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 23:09:43 -0800 Subject: [PATCH 3/3] local run: retry sandboxes concurrently and remove a local one's folder Co-Authored-By: Claude Opus 5.5 --- src/agent_env/runner/local_runner.py | 29 +++++++++++++----------- tst/unit/runner/local_runner_test.py | 34 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/src/agent_env/runner/local_runner.py b/src/agent_env/runner/local_runner.py index cb6cd8172..a605866e4 100644 --- a/src/agent_env/runner/local_runner.py +++ b/src/agent_env/runner/local_runner.py @@ -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, TORN_DOWN_KEY, teardown_run, terminate +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" @@ -289,22 +289,25 @@ async def _tear_down(cls, run_id: str, context) -> None: logger.warning("Run %s: couldn't tear down %s: %s", run_id, sandbox.sandbox_id, why) 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) - still = [] - for sandbox in retry: - try: - async with asyncio.timeout(cls.RETRY_TERMINATE_SECONDS): - 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) - still.append(sandbox) - continue - 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) - retry = still + 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), diff --git a/tst/unit/runner/local_runner_test.py b/tst/unit/runner/local_runner_test.py index 9847226f5..c937a5fd4 100644 --- a/tst/unit/runner/local_runner_test.py +++ b/tst/unit/runner/local_runner_test.py @@ -899,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"]