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): stop workers hanging once their output pipe fills (#5360)
injaneity85d001220940
diff --git a/libs/cua-bench-rl/cua_bench_rl/workers/worker_manager.py b/libs/cua-bench-rl/cua_bench_rl/workers/worker_manager.pyindex 00109566f7..1a7dab25a4 100644--- a/libs/cua-bench-rl/cua_bench_rl/workers/worker_manager.py+++ b/libs/cua-bench-rl/cua_bench_rl/workers/worker_manager.py@@ -16,10 +16,12 @@ Example:"""import asyncio+import contextlibimport osimport socketimport subprocessimport sys+import threadingfrom dataclasses import dataclassfrom typing import List, Optional@@ -52,6 +54,13 @@ def _find_free_ports(n: int) -> List[int]:return ports+def _forward_output(worker_id: str, output: socket.socket) -> None:+ with output.makefile("r", errors="replace") as stream:+ for line in stream:+ with contextlib.suppress(Exception):+ sys.stderr.write(f"[{worker_id}] {line}")++@dataclassclass WorkerHandle:"""Handle for a running worker server.@@ -61,12 +70,16 @@ class WorkerHandle:port: Port the worker is listening onprocess: Subprocess running the workerapi_url: Full URL for API requests+ output: Our end of the socket carrying the worker's stdout and stderr+ output_reader: Thread forwarding the worker's stdout and stderr to ours"""worker_id: strport: intprocess: subprocess.Popenapi_url: str+ output: Optional[socket.socket] = None+ output_reader: Optional[threading.Thread] = Noneasync def health_check(self, timeout: float = 5.0) -> bool:"""Check if the worker is healthy.@@ -103,6 +116,13 @@ class WorkerHandle:self.process.wait(timeout=5)except Exception:pass+ if self.output_reader and self.output_reader.is_alive():+ self.output_reader.join(timeout=5)+ if self.output_reader.is_alive():+ self.output.shutdown(socket.SHUT_RDWR)+ self.output_reader.join(timeout=5)+ if self.output:+ self.output.close()@propertydef is_running(self) -> bool:@@ -161,29 +181,39 @@ async def create_workers(str(port),]+ output = worker_output = Nonetry:+ output, worker_output = socket.socketpair()process = subprocess.Popen(cmd,env=env,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,+ stdout=worker_output,+ stderr=subprocess.STDOUT,start_new_session=True, # Detach from parent)+ worker_output.close()+ api_url = f"http://127.0.0.1:{port}"+ handle = WorkerHandle(+ worker_id=worker_id,+ port=port,+ process=process,+ api_url=api_url,+ output=output,+ )+ handles.append(handle)+ handle.output_reader = threading.Thread(+ target=_forward_output, args=(worker_id, output), daemon=True+ )+ handle.output_reader.start()except Exception as e:+ for end in (output, worker_output):+ if end:+ end.close()# Clean up already started workersfor handle in handles:handle.stop()raise RuntimeError(f"Failed to start worker {worker_id}: {e}")- api_url = f"http://127.0.0.1:{port}"- handle = WorkerHandle(- worker_id=worker_id,- port=port,- process=process,- api_url=api_url,- )- handles.append(handle)-# Wait for all workers to become healthyasync def wait_for_health(handle: WorkerHandle) -> bool:"""Wait for a worker to become healthy."""diff --git a/libs/cua-bench-rl/tests/test_worker_output.py b/libs/cua-bench-rl/tests/test_worker_output.pynew file mode 100644index 0000000000..2402a84452--- /dev/null+++ b/libs/cua-bench-rl/tests/test_worker_output.py@@ -0,0 +1,92 @@+"""A worker started by create_workers keeps answering however much it logs.++uvicorn writes a line to the access log for every request. If nothing drains the+worker's output, the worker blocks once the OS pipe buffer (64 KiB, roughly 1,100+access-log lines) is full. This starts one real worker and sends well past that.+"""++import asyncio+import os+import signal+import sys++import aiohttp+import pytest+from cua_bench_rl.workers.worker_manager import cleanup_workers, create_workers++N_REQUESTS = 4000+REQUEST_TIMEOUT_S = 5.0+++async def test_worker_keeps_answering_past_pipe_buffer():+ workers = await create_workers(n_workers=1, allowed_ips=["127.0.0.1"], host="127.0.0.1")+ try:+ url = f"{workers[0].api_url}/health"+ timeout = aiohttp.ClientTimeout(total=REQUEST_TIMEOUT_S)+ async with aiohttp.ClientSession(timeout=timeout) as session:+ for i in range(N_REQUESTS):+ try:+ async with session.get(url) as response:+ assert response.status == 200+ except asyncio.TimeoutError:+ pytest.fail(f"worker stopped answering after {i} requests")+ finally:+ await cleanup_workers(workers)+++async def test_worker_output_reaches_parent_until_stopped(capfd):+ workers = await create_workers(n_workers=1, allowed_ips=["127.0.0.1"], host="127.0.0.1")+ try:+ async with aiohttp.ClientSession() as session:+ async with session.get(f"{workers[0].api_url}/health") as response:+ assert response.status == 200+ finally:+ await cleanup_workers(workers)++ assert not workers[0].output_reader.is_alive()+ err = capfd.readouterr().err+ assert "[w0] INFO: Uvicorn running on" in err+ assert any(+ line.startswith("[w0] ") and '"GET /health HTTP/1.1" 200' in line+ for line in err.splitlines()+ )+++class StderrFailingFirstWrite:+ def __init__(self):+ self.failed = False+ self.lines = []++ def write(self, line):+ if not self.failed:+ self.failed = True+ raise OSError("stderr unavailable")+ self.lines.append(line)+++async def test_worker_keeps_draining_when_forwarding_fails(monkeypatch):+ stderr = StderrFailingFirstWrite()+ monkeypatch.setattr(sys, "stderr", stderr)+ await test_worker_keeps_answering_past_pipe_buffer()+ assert stderr.failed+ assert any(line.startswith("[w0] INFO: Uvicorn running on") for line in stderr.lines)+ health_lines = [line for line in stderr.lines if '"GET /health HTTP/1.1" 200' in line]+ assert len(health_lines) >= N_REQUESTS+++async def test_reader_stops_when_grandchild_holds_output_open(monkeypatch, tmp_path, capfd):+ grandchild_pid = tmp_path / "grandchild.pid"+ launcher = tmp_path / "python"+ launcher.write_text(+ f'#!/bin/sh\nsleep 60 &\necho $! > {grandchild_pid}\nexec {sys.executable} "$@"\n'+ )+ launcher.chmod(0o755)+ monkeypatch.setattr(sys, "executable", str(launcher))+ workers = await create_workers(n_workers=1, allowed_ips=["127.0.0.1"], host="127.0.0.1")+ monkeypatch.undo()+ try:+ await cleanup_workers(workers)+ assert not workers[0].output_reader.is_alive()+ assert "[w0] INFO: Uvicorn running on" in capfd.readouterr().err+ finally:+ os.kill(int(grandchild_pid.read_text()), signal.SIGKILL)