diff --git a/tests/test_agentic_compaction_switch.py b/tests/test_agentic_compaction_switch.py index 651c86d71..cb4b8005d 100644 --- a/tests/test_agentic_compaction_switch.py +++ b/tests/test_agentic_compaction_switch.py @@ -28,8 +28,11 @@ import asyncio import copy import dataclasses +import gc +import logging import threading import time +import warnings from pathlib import Path from typing import Any @@ -41,7 +44,7 @@ from yeto.rl.agentic import TrialVerdict from yeto.rl.compaction import CompactionConfig from yeto.rl.engine.agentic_round import (DRAIN_EVENT, GROUP_EVENT, LOST_DRAIN, LOST_VERSION, RETRY_EVENT, - AgenticRound, infra_failure) + AgenticRound, LoopThread, infra_failure) from yeto.rl.engine.buffer_payload import GroupWriter, decode_group from yeto.rl.engine.engine_sampler import PromptItem from yeto.rl.engine.resume import CheckpointStore @@ -467,9 +470,12 @@ def test_finished_compacted_trials_leave_nothing_in_the_recorder(tmp_path, glm, assert len(_samples(tmp_path)) == 8 # two groups of two trials, two segments each -def test_closing_the_island_during_a_summary_turn_forgets_the_trial(tmp_path, glm, budget): +def test_closing_the_island_during_a_summary_turn_forgets_the_trial(tmp_path, glm, budget, caplog): """No suspension on this path: a sampler that stops (or restarts) with a trial in its - summary turn loses it with every segment; nothing of it is left in the recorder.""" + summary turn loses it with every segment; nothing of it is left in the recorder. Nor on + the round's loop: the recorder request still in the engine is cancelled, the recorder's + server stopped and the loop closed, so the garbage collector, in whatever test runs + next, finds no pending task ("Task was destroyed but it is pending!").""" model = Model(glm) model.release.clear() world = _world(glm, budget, model) @@ -482,6 +488,145 @@ def test_closing_the_island_during_a_summary_turn_forgets_the_trial(tmp_path, gl model.release.set() assert world.held() == EMPTY and _samples(tmp_path) == [] assert not _events(events, GROUP_EVENT) # never settled: its round is not in the buffer + assert rnd.loop.loop.is_closed() and world.recorder._runner is None + caplog.set_level(logging.DEBUG, logger="asyncio") + del rnd, world + gc.collect() + assert [r.getMessage() for r in caplog.records if r.name == "asyncio"] == [] + + +class CleanupAgent(Agent): + """An agent whose cancelled trial still awaits its own cleanup (a sandbox teardown) + on the round's loop before it ends.""" + + def __init__(self) -> None: + super().__init__() + self.cleaned = threading.Event() + + async def run(self, task, endpoint): + try: + return await super().run(task, endpoint) + except asyncio.CancelledError: + await asyncio.sleep(0.2) # on the loop the close is about to close + self.cleaned.set() + raise + + +def _listening(url: str) -> bool: + import socket + from urllib.parse import urlsplit + + parts = urlsplit(url) + with socket.socket() as sock: + sock.settimeout(2) + return sock.connect_ex((parts.hostname, parts.port)) == 0 + + +def test_close_after_finished_rounds_stops_the_recorder_server_and_closes_the_loop(tmp_path, glm, budget, caplog): + model = Model(glm) + world = _world(glm, budget, model) + rnd, events = _round(tmp_path, world, Agent()) + try: + rnd(0) + rnd.flush() + url = world.recorder._base_url + assert url and _listening(url) and not rnd.loop.loop.is_closed() # running: nothing closed early + finally: + deleted = rnd.close() + assert deleted == 0 and len(_samples(tmp_path)) == 2 # the finished trial's two segments were written + assert rnd.loop.loop.is_closed() and world.recorder._runner is None and not _listening(url) + assert [f["trials_total"] for f in _events(events, "rl_agentic_close")] == [1] + caplog.set_level(logging.DEBUG, logger="asyncio") + del rnd, world + gc.collect() + assert [r.getMessage() for r in caplog.records if r.name == "asyncio"] == [] + + +def test_close_waits_for_a_cancelled_trials_cleanup_before_it_closes_the_loop(tmp_path, glm, budget): + model = Model(glm) + model.release.clear() + world = _world(glm, budget, model) + agent = CleanupAgent() + rnd, _ = _round(tmp_path, world, agent) + try: + rnd(0) + _wait(model.summary_started.is_set) + finally: + rnd.close() + model.release.set() + assert agent.cleaned.is_set() # its cleanup ran to the end on the loop before the loop closed + assert rnd.loop.loop.is_closed() and world.held() == EMPTY + + +def test_close_closes_the_loop_when_stopping_the_recorder_or_deleting_the_pools_fails(tmp_path, glm, budget, + monkeypatch): + from yeto.rl.harness.harbor import boat_pool + + world = _world(glm, budget, Model(glm)) + rnd, events = _round(tmp_path, world, Agent()) + rnd(0) + rnd.flush() + + async def broken_aclose(): + raise OSError("the server did not stop") + + monkeypatch.setattr(world.recorder, "aclose", broken_aclose) + assert rnd.close() == 0 # the recorder's failure does not fail the close + assert rnd.loop.loop.is_closed() + + world = _world(glm, budget, Model(glm)) + rnd, events = _round(tmp_path / "b", world, Agent()) + rnd(0) + rnd.flush() + + def broken_pools(): + raise RuntimeError("boat API down") + + monkeypatch.setattr(boat_pool, "close_pools_now", broken_pools) + with pytest.raises(RuntimeError, match="boat API down"): # as before: the pool error is the caller's + rnd.close() + assert rnd.loop.loop.is_closed() and world.recorder._runner is None + + +def test_a_second_close_is_safe_and_changes_nothing(tmp_path, glm, budget, monkeypatch): + from yeto.rl.harness.harbor import boat_pool + + deletes = [] + monkeypatch.setattr(boat_pool, "close_pools_now", lambda: deletes.append("pools") or 3) + world = _world(glm, budget, Model(glm)) + rnd, events = _round(tmp_path, world, Agent()) + rnd(0) + rnd.flush() + assert rnd.close() == 3 + gc.collect() # what earlier tests left for the collector is not this close's + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + assert rnd.close() == 0 # the loop is closed already: nothing to cancel, stop or close + gc.collect() + assert [str(w.message) for w in caught] == [] # no coroutine handed to the closed loop + assert deletes == ["pools"] # the pooled sandboxes are deleted once + assert [f["trials_total"] for f in _events(events, "rl_agentic_close")] == [1] + assert rnd.loop.loop.is_closed() and world.recorder._runner is None + assert len(_samples(tmp_path)) == 2 + + +def test_closing_the_loop_thread_cancels_its_tasks_and_closes_the_loop(caplog): + loop = LoopThread(workers=1) + started = threading.Event() + + async def pending(): + started.set() + await asyncio.sleep(3600) + + task = asyncio.run_coroutine_threadsafe(pending(), loop.loop) + assert started.wait(10) + loop.close() + assert loop.loop.is_closed() and task.cancelled() + loop.close() # a second close does nothing + caplog.set_level(logging.DEBUG, logger="asyncio") + del loop + gc.collect() + assert [r.getMessage() for r in caplog.records if r.name == "asyncio"] == [] def test_a_request_for_a_forgotten_trajectory_recreates_no_state(glm, budget): diff --git a/tests/test_node_lease.py b/tests/test_node_lease.py index b9e55aa57..4ad27ea27 100644 --- a/tests/test_node_lease.py +++ b/tests/test_node_lease.py @@ -775,12 +775,23 @@ def test_ssh_probe_reads_the_script_output(out, rc, want): """ +FAKE_PS = """#!/bin/sh +# The node's process table (ps -eo pid=,args=): the rows of $FAKE_STATE_DIR/ps.txt and the +# probe itself (the shell that runs this ps), never the processes of the test host. +[ -f "$FAKE_STATE_DIR/ps.txt" ] && cat "$FAKE_STATE_DIR/ps.txt" +exec {ps} -o pid=,args= -p "$PPID" +""" + + def _node_bin(tmp_path, *, sudo=True): """A node's PATH: a fake podman that records what the real start command runs (its ``--name`` and ``--label`` flags) and answers ``ps --filter label=... --format``; a fake ``sudo -n`` whose containers are a separate (rootful) set (no ``sudo``: one - that always refuses). A fake ``docker`` with no containers shadows a real one.""" + that always refuses). A fake ``docker`` with no containers shadows a real one. A fake + ``ps`` lists the processes a test writes to ``ps.txt`` (none by default): the + sampler scan must not see the processes of other tests on the host.""" import os + import shutil import sys bin_dir = tmp_path / "bin" @@ -790,6 +801,8 @@ def _node_bin(tmp_path, *, sudo=True): (bin_dir / engine).chmod(0o755) (bin_dir / "sudo").write_text(FAKE_SUDO if sudo else "#!/bin/sh\nexit 1\n") (bin_dir / "sudo").chmod(0o755) + (bin_dir / "ps").write_text(FAKE_PS.format(ps=shutil.which("ps"))) + (bin_dir / "ps").chmod(0o755) return {**os.environ, "PATH": f"{bin_dir}:{os.environ['PATH']}", "HOME": str(tmp_path / "home"), "FAKE_STATE_DIR": str(tmp_path)} @@ -902,7 +915,6 @@ def test_an_unlabelled_sampler_container_is_possibly_the_runs(tmp_path, monkeypa def test_the_probe_finds_trainer_process_groups_and_venv_samplers(tmp_path): import os import subprocess - import time from yeto.launch.ssh_trainer_island import STATE_DIR @@ -913,7 +925,9 @@ def test_the_probe_finds_trainer_process_groups_and_venv_samplers(tmp_path): gone = subprocess.Popen(["true"], start_new_session=True) gone.wait() # a process group that ended group = subprocess.Popen(["sleep", "30"], start_new_session=True) - sampler = subprocess.Popen(["bash", "-c", "exec -a yeto-ssh-sampler:run-a:s3:t3 sleep 30"]) + # the node's venv samplers: one of run-a, one of a run whose name run-a prefixes + (tmp_path / "ps.txt").write_text("4242 yeto-ssh-sampler:run-a:s3:t3 python -m yeto.node.sampler\n" + "4343 yeto-ssh-sampler:run-ab:s0:t0 python -m yeto.node.sampler\n") try: for island, pgid, rc in (("isl-i0", group.pid, False), ("isl-i1", group.pid, True), ("isl-i2", gone.pid, False), ("isl-i3", 1, False)): @@ -922,19 +936,12 @@ def test_the_probe_finds_trainer_process_groups_and_venv_samplers(tmp_path): (d / "pgid").write_text(str(pgid)) if rc: (d / "rc").write_text("0") - for _ in range(50): # the exec -a has happened - if "yeto-ssh-sampler:run-a:s3" in subprocess.run(["ps", "-o", "args=", "-p", str(sampler.pid)], - capture_output=True, text=True).stdout: - break - time.sleep(0.05) found = _probe("run-a", env) other = _probe("run-z", env) finally: group.kill() - sampler.kill() group.wait() - sampler.wait() - assert found == (True, sorted(["container:yeto-run-a-isl-i0-n0", "process:isl-i0", f"sampler:{sampler.pid}"])) + assert found == (True, sorted(["container:yeto-run-a-isl-i0-n0", "process:isl-i0", "sampler:4242"])) assert other == (True, []) # nothing of another run; the probe does not find itself assert os.environ.get("FAKE_STATE_DIR") is None diff --git a/yeto/rl/engine/agentic_round.py b/yeto/rl/engine/agentic_round.py index 261f56d49..f5206aa69 100644 --- a/yeto/rl/engine/agentic_round.py +++ b/yeto/rl/engine/agentic_round.py @@ -153,6 +153,7 @@ def resolve_weight_switch(switch: str, engine: Any) -> str: WAIT_EVENT = "rl_agentic_waiting" WAIT_BEAT_S = 60.0 CLOSE_WAIT_S = 2.0 # close(): the longest wait for the cancelled trials to end +LOOP_CLOSE_WAIT_S = 2.0 # LoopThread.close(): the longest wait for the loop's other tasks to end RETRY_EVENT = "rl_agentic_trial_retry" LOST_EVENT = "rl_agentic_trial_lost" # one token_alignment loss: error, call, token window, trial_dir DEFAULT_INFRA_RETRIES = 2 # per trial slot (spec agentic.infra_retries) @@ -182,9 +183,38 @@ def __init__(self, *, workers: int) -> None: def run(self, coro: Any) -> Any: return asyncio.run_coroutine_threadsafe(coro, self.loop).result() + def cancel_pending(self, timeout_s: float) -> None: + """Cancel every task still pending on the loop (a recorder request still in the + engine: aiohttp does not cancel a handler whose client left) and give them up to + ``timeout_s`` to end.""" + + async def cancel() -> None: + tasks = [task for task in asyncio.all_tasks() if task is not asyncio.current_task()] + for task in tasks: + task.cancel() + if tasks: + await asyncio.wait(tasks, timeout=timeout_s) + + if self._thread.is_alive() and not self.loop.is_closed(): + asyncio.run_coroutine_threadsafe(cancel(), self.loop).result(timeout=timeout_s + 5) + def close(self) -> None: + """Cancel what still runs on the loop, stop it and close it. A loop that is only + stopped keeps its tasks and its selector until the garbage collector finds them, + in whatever runs then ("Task was destroyed but it is pending!", unclosed loop).""" + if self.loop.is_closed(): + return + try: + self.cancel_pending(LOOP_CLOSE_WAIT_S) + if self._thread.is_alive(): + asyncio.run_coroutine_threadsafe(self.loop.shutdown_asyncgens(), self.loop).result( + timeout=LOOP_CLOSE_WAIT_S) + except Exception: # noqa: BLE001 - still stop the loop + pass self.loop.call_soon_threadsafe(self.loop.stop) self._thread.join(timeout=10) + if not self._thread.is_alive(): + self.loop.close() def session_id(*parts: Any) -> str: @@ -627,7 +657,10 @@ def holds_weights(self) -> bool: def close(self) -> int: """End of the island: cancel the trials still running, delete the pooled boat sandboxes (the account returns to the sandboxes other runs hold) and - stop the loop; returns the VMs deleted.""" + stop the loop; returns the VMs deleted. A second close finds the loop closed and + does nothing.""" + if self.loop.loop.is_closed(): + return 0 deleted = 0 try: try: @@ -635,6 +668,7 @@ def close(self) -> int: self.loop.run(self._wait_cancelled(CLOSE_WAIT_S)) except Exception: # noqa: BLE001 - the loop may be gone already pass + self._stop_recorder_server() from yeto.rl.harness.harbor.boat_pool import close_pools_now deleted = int(close_pools_now() or 0) @@ -644,6 +678,19 @@ def close(self) -> int: trials_total=self.trials) return deleted + def _stop_recorder_server(self) -> None: + """Stop the recorder's HTTP server, which runs on this round's loop (its listening + socket and connections close with it). The requests still in it are cancelled + first: the server's shutdown would wait for them.""" + aclose = getattr(self.recorder, "aclose", None) + if aclose is None: + return + try: + self.loop.cancel_pending(CLOSE_WAIT_S) + self.loop.run(asyncio.wait_for(aclose(), CLOSE_WAIT_S)) + except Exception: # noqa: BLE001 - the loop closes anyway + pass + # ------------------------------------------------------------------ trials def _task(self, item: PromptItem, session: str) -> Any: from yeto.rl.agentic import AgentTask, HarnessConfigError