Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-bench-rl): reap idle worker envs without deadlocking and restart their clients' episodes (#5359)
injaneity5b1b3e44f524
diff --git a/libs/cua-bench-rl/cua_bench_rl/workers/worker_client.py b/libs/cua-bench-rl/cua_bench_rl/workers/worker_client.pyindex 4789a21e2d..5bfd298346 100644--- a/libs/cua-bench-rl/cua_bench_rl/workers/worker_client.py+++ b/libs/cua-bench-rl/cua_bench_rl/workers/worker_client.py@@ -160,6 +160,8 @@ class CBEnvWorkerClient:self.step_count = 0self.done = Falseself.prompt = None+ # Set when /step answers 404: the server no longer has env_id.+ self.env_gone = Falsedef reset(self):ret, meta_info = self.reset_attempt()@@ -216,6 +218,7 @@ class CBEnvWorkerClient:self.uid = str(uuid.uuid4())self.step_count = 0self.done = False+ self.env_gone = Falseobs = self.prompt_to_input_obs(self.prompt)ret = {"obs": obs, "done": False, "is_init": True}@@ -329,8 +332,21 @@ class CBEnvWorkerClient:return jpg_string_rsdef step(self, action):+ """Run one step; if the server no longer has the env, start a new episode.++ /step answers 404 when the server no longer has env_id, for example after+ the env's timeout passed or the worker restarted. No retry of the step can+ succeed then, so this returns the new episode's first observation+ (``is_init`` is True) instead.+ """ret, meta_info = self.step_attempt(action)while ret is None:+ if self.env_gone:+ print_debug(+ f"[CBEnvWorkerClient ID: {self.env_id}] Env released by the server, "+ "starting a new episode"+ )+ return self.reset()print_debug(f"[CBEnvWorkerClient ID: {self.env_id}] Step failed, retrying...")ret, meta_info = self.step_attempt(action)return ret, meta_info@@ -398,6 +414,8 @@ class CBEnvWorkerClient:self.done = doneexcept Exception as e:print_debug(f"[CBEnvWorkerClient ID: {self.env_id}] ERROR in step execution: {e}")+ if isinstance(e, requests.HTTPError) and e.response is not None:+ self.env_gone = e.response.status_code == 404return None, Noneaction_clean = (diff --git a/libs/cua-bench-rl/cua_bench_rl/workers/worker_server.py b/libs/cua-bench-rl/cua_bench_rl/workers/worker_server.pyindex a10676fea7..524413d0cc 100644--- a/libs/cua-bench-rl/cua_bench_rl/workers/worker_server.py+++ b/libs/cua-bench-rl/cua_bench_rl/workers/worker_server.py@@ -66,6 +66,12 @@ available_envs: List[int] = list(range(MAX_ENVS - 1, -1, -1)) # [1, 0] for MAX_active_envs: List[int] = []env_map: Dict[int, EnvState] = {}+# Event loop the envs were created on, recorded by /reset. The timeout checker thread+# has no running loop, so it schedules env.close() here.+_server_loop: Optional[asyncio.AbstractEventLoop] = None+# Pending close() calls, kept referenced until they finish.+_pending_closes: set = set()+# FastAPI appapp = FastAPI(title="CUA-Bench Worker Server", version="0.1.0")@@ -171,35 +177,57 @@ def _get_available_env(timeout: int) -> int:return env_id-def _release_env(env_id_or_all: int | str) -> None:- """Release an environment back to the pool."""+def _release_env(env_id_or_all: int | str, expired_at: Optional[float] = None) -> None:+ """Release an environment back to the pool.++ With ``expired_at``, a single env is released only if it is still past its timeout+ at that time, so an env used again after the timeout checker's sweep is kept.+ """with env_lock:if env_id_or_all == "all":# Release all active envsfor eid in list(active_envs):if eid in env_map:state = env_map.pop(eid)- # Close the environment- try:- asyncio.create_task(_close_env_async(state.env))- except Exception:- pass+ _close_env_soon(state.env)active_envs.remove(eid)available_envs.append(eid)else:env_id = int(env_id_or_all)if env_id in active_envs:+ if expired_at is not None:+ state = env_map.get(env_id)+ if state is None or expired_at - state.last_accessed <= state.timeout:+ returnif env_id in env_map:state = env_map.pop(env_id)- # Close the environment- try:- asyncio.create_task(_close_env_async(state.env))- except Exception:- pass+ _close_env_soon(state.env)active_envs.remove(env_id)available_envs.append(env_id)+def _close_env_soon(env: Any) -> None:+ """Schedule env.close() on the event loop, from the loop or from another thread."""+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ # Called from the timeout checker thread: hand the close to the server loop.+ loop = _server_loop+ if loop is None or loop.is_closed():+ return+ coro = _close_env_async(env)+ try:+ future = asyncio.run_coroutine_threadsafe(coro, loop)+ except RuntimeError:+ # The loop closed after the check above: the server is shutting down.+ coro.close()+ return+ else:+ future = asyncio.create_task(_close_env_async(env))+ _pending_closes.add(future)+ future.add_done_callback(_pending_closes.discard)++async def _close_env_async(env: Any) -> None:"""Close an environment asynchronously."""try:@@ -288,13 +316,17 @@ def _timeout_checker():time.sleep(30) # Check every 30 secondscurrent_time = time.time()+ # Collect timed-out envs under the lock and release them after dropping it:+ # _release_env takes env_lock itself, and env_lock is not reentrant.with env_lock:- for env_id in list(active_envs):- if env_id in env_map:- state = env_map[env_id]- if current_time - state.last_accessed > state.timeout:- # Release timed out environment- _release_env(env_id)+ expired = [+ env_id+ for env_id in active_envs+ if env_id in env_map+ and current_time - env_map[env_id].last_accessed > env_map[env_id].timeout+ ]+ for env_id in expired:+ _release_env(env_id, expired_at=current_time)# Start timeout checker thread@@ -313,6 +345,9 @@ async def reset(request: ResetRequest):3. Creates/resets the environment to the specified task4. Returns the initial screenshot and task instruction"""+ global _server_loop+ _server_loop = asyncio.get_running_loop()+# Release all active envs first (as per incus pattern)_release_env("all")diff --git a/libs/cua-bench-rl/tests/test_worker_client.py b/libs/cua-bench-rl/tests/test_worker_client.pyindex 1afa81cd43..e6460ce53e 100644--- a/libs/cua-bench-rl/tests/test_worker_client.py+++ b/libs/cua-bench-rl/tests/test_worker_client.py@@ -8,6 +8,8 @@ import base64import iofrom unittest.mock import MagicMock, patch+import pytest+import requestsfrom cua_bench_rl.workers.worker_client import CBEnvWorkerClientfrom PIL import Image@@ -362,6 +364,67 @@ class TestCBEnvWorkerClientStep:assert env_ret["done"] is Trueassert env_ret["reward"] == 1.0+ @patch("requests.post")+ def test_step_starts_a_new_episode_when_the_env_was_released(self, mock_post):+ """A 404 from /step means the server released the env (its timeout passed).++ Re-sending the step can never succeed then; step() starts a new episode.+ """+ img_b64 = create_test_image(1024, 768)+ resets = []+ steps = []++ class GaveUp(BaseException):+ """Ends the old retry-forever loop (step_attempt catches Exception only)."""++ def mock_post_side_effect(url, **kwargs):+ mock_resp = MagicMock()+ if "/reset" in url:+ resets.append(kwargs["json"])+ mock_resp.json.return_value = {+ "screenshot": img_b64,+ "instruction": "Test",+ "env_id": len(resets) - 1,+ }+ return mock_resp+ steps.append(kwargs["json"])+ if len(steps) > 20:+ raise GaveUp+ mock_resp.status_code = 404+ mock_resp.raise_for_status.side_effect = requests.HTTPError(+ "404 Client Error: Not Found for url: http://localhost:8001/step",+ response=mock_resp,+ )+ return mock_resp++ mock_post.side_effect = mock_post_side_effect++ task_configs = [{"env_path": "./task", "task_index": 0, "split": "train"}]+ env_config = {+ "server_url": "http://localhost:8001",+ "task_configs": task_configs,+ "max_step": 50,+ "max_hist": 10,+ "timeout": 300,+ }+ client = CBEnvWorkerClient(env_config)+ _, first = client.reset()++ try:+ env_ret, meta_info = client.step("<|action_start|>click(500,500)<|action_end|>")+ except GaveUp:+ pytest.fail(+ f"step() re-sent the step {len(steps) - 1} times for an env the server released"+ )++ assert len(steps) == 1+ assert len(resets) == 2+ assert env_ret["is_init"] is True+ assert env_ret["done"] is False+ assert meta_info["uid"] != first["uid"]+ assert client.env_id == 1+ assert client.step_count == 0+class TestCBEnvWorkerClientActions:"""Tests for action processing in CBEnvWorkerClient."""diff --git a/libs/cua-bench-rl/tests/test_worker_server.py b/libs/cua-bench-rl/tests/test_worker_server.pyindex eff79a4b50..50ed6b02d2 100644--- a/libs/cua-bench-rl/tests/test_worker_server.py+++ b/libs/cua-bench-rl/tests/test_worker_server.py@@ -3,8 +3,12 @@This module tests:- Action serialization/deserialization (unit tests)- FastAPI server endpoints using TestClient with real simulated environments (e2e)+- The background timeout checker that reaps inactive environments"""+import threading+import time+import pytestfrom cua_bench.types import (ClickAction,@@ -20,6 +24,7 @@ from cua_bench.types import (TypeAction,WaitAction,)+from cua_bench_rl.workers import worker_serverfrom cua_bench_rl.workers.worker_server import (ResetRequest,ShutdownRequest,@@ -361,3 +366,111 @@ class TestServerEndpoints:client = TestClient(app)response = client.get("/screenshot", params={"env_id": 999})assert response.status_code == 404+++class _SweepDone(Exception):+ """Raised by the fake clock to end the timeout checker's loop after one sweep."""+++class _OneSweepClock:+ """Fake ``time`` module for a single pass of ``_timeout_checker``.++ Only the checker thread under test sees it: its first ``sleep`` returns at once,+ ``time()`` reports ``now``, and its second ``sleep`` ends the loop. Every other+ thread (request handlers, the module's own checker thread) gets the real clock.+ """++ def __init__(self, now: float):+ self.now = now+ self.thread: threading.Thread | None = None+ self.sleeps = 0++ def _is_checker(self) -> bool:+ return threading.current_thread() is self.thread++ def time(self) -> float:+ return self.now if self._is_checker() else time.time()++ def sleep(self, seconds: float) -> None:+ if not self._is_checker():+ time.sleep(seconds)+ return+ self.sleeps += 1+ if self.sleeps > 1:+ raise _SweepDone+++def _run_one_sweep(monkeypatch, now: float) -> tuple[bool, list[BaseException]]:+ """Run one pass of the timeout checker at ``now``; return (finished, errors)."""+ clock = _OneSweepClock(now)+ errors: list[BaseException] = []++ def checker():+ try:+ worker_server._timeout_checker()+ except _SweepDone:+ pass+ except BaseException as e:+ errors.append(e)++ clock.thread = threading.Thread(target=checker, daemon=True)+ monkeypatch.setattr(worker_server, "time", clock)+ clock.thread.start()+ clock.thread.join(timeout=2.0)+ finished = not clock.thread.is_alive()+ if not finished:+ # Stuck on env_lock: release it from here so the checker and the rest of the+ # suite can carry on (a plain Lock can be released by any thread).+ worker_server.env_lock.release()+ clock.thread.join(timeout=2.0)+ return finished, errors+++class _FakeEnv:+ """Stands in for a cua_bench Environment and records when close() is awaited."""++ def __init__(self):+ self.closed = threading.Event()++ async def reset(self, task_id: int = 0):+ return b"\x89PNG", {"description": "fake task"}++ async def close(self):+ self.closed.set()+++class TestTimeoutChecker:+ """The timeout checker reaps environments idle for longer than their timeout."""++ @pytest.fixture+ def idle_env(self, monkeypatch):+ """Reset one fake env through the API, with the server's event loop running."""+ saved_available = list(worker_server.available_envs)+ saved_active = list(worker_server.active_envs)+ saved_map = dict(worker_server.env_map)+ env = _FakeEnv()+ monkeypatch.setattr(worker_server, "make", lambda env_path, split: env)+ with TestClient(app) as client:+ response = client.post("/reset", json={"env_path": "fake", "timeout": 60})+ assert response.status_code == 200+ yield client, env+ worker_server.available_envs[:] = saved_available+ worker_server.active_envs[:] = saved_active+ worker_server.env_map.clear()+ worker_server.env_map.update(saved_map)++ def test_sweep_releases_idle_env(self, idle_env, monkeypatch):+ """A sweep that finds an expired env finishes and returns its slot to the pool."""+ client, _ = idle_env+ finished, errors = _run_one_sweep(monkeypatch, now=time.time() + 3600)+ assert finished, "timeout checker deadlocked on env_lock"+ assert errors == []+ health = client.get("/health").json()+ assert health["active_envs"] == 0+ assert health["available_envs"] == health["max_envs"]++ def test_sweep_closes_released_env(self, idle_env, monkeypatch):+ """The checker thread has no event loop; the env it releases is still closed."""+ _, env = idle_env+ _run_one_sweep(monkeypatch, now=time.time() + 3600)+ assert env.closed.wait(timeout=2.0), "released env was never closed"