diff --git a/src/agent_env/cli/submitted_runs.py b/src/agent_env/cli/submitted_runs.py index 5ef2ef079..9f2ab7dec 100644 --- a/src/agent_env/cli/submitted_runs.py +++ b/src/agent_env/cli/submitted_runs.py @@ -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 @@ -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 + 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 be73021a5..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, 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" @@ -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. @@ -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``.""" @@ -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 --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 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 8bbdcff41..c937a5fd4 100644 --- a/tst/unit/runner/local_runner_test.py +++ b/tst/unit/runner/local_runner_test.py @@ -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() @@ -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"]