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): reject missing, nonfinite and nonnumeric evaluator rewards (#5163)
injaneity341d1e172378
diff --git a/libs/cua-bench/cua_bench/runners.py b/libs/cua-bench/cua_bench/runners.pyindex 9e888b0e65..bc9d5dc2f7 100644--- a/libs/cua-bench/cua_bench/runners.py+++ b/libs/cua-bench/cua_bench/runners.py@@ -6,6 +6,7 @@ interactive environments, using the core gym interface (make, reset, step, evaluimport asyncioimport fnmatch+import mathimport timeimport uuidfrom dataclasses import dataclass@@ -82,7 +83,7 @@ async def run_single_task(task_index: Task variant index (default: 0)split: Dataset split (default: "train")agent_fn: Optional agent function that takes (screenshot, task_config)- and returns an Action. If None and oracle=False, returns after setup.+ and returns an Action. Required when oracle=False; otherwise the run fails closed after setup.max_steps: Maximum steps per task (default: 100)oracle: Run oracle/solver mode (default: False)@@ -99,7 +100,13 @@ async def run_single_task(result = await run_single_task(Path("./task"), agent_fn=my_agent)"""+ if type(max_steps) is not int or max_steps < 1:+ raise ValueError("max_steps must be a positive integer")+env = None+ step_count = 0+ outcome = None+try:# Create environment using gym interfaceenv = make(str(env_path), split=split)@@ -108,16 +115,13 @@ async def run_single_task(# Reset environmentscreenshot, task_cfg = await env.reset(task_id=task_index)- step_count = 0- reward = 0.0-if oracle:# Run oracle solverif env.solve_task_fn is not None:await env.solve()step_count = env.step_countelse:- return TaskResult(+ outcome = TaskResult(task_path=str(env_path),variant_id=task_index,success=False,@@ -125,6 +129,7 @@ async def run_single_task(steps=0,error="No solve_task_fn defined for oracle mode",)+ return outcomeelif agent_fn is not None:# Run agentdone = False@@ -134,39 +139,55 @@ async def run_single_task(step_count += 1done = isinstance(action, DoneAction)+ if not oracle and agent_fn is None:+ raise ValueError("No agent_fn supplied; task was not executed")+# Evaluate- if env.evaluate_task_fn is not None:- result = await env.evaluate()- if isinstance(result, (int, float)):- reward = float(result)- elif isinstance(result, list) and len(result) > 0:- reward = float(result[0])- elif isinstance(result, dict) and "reward" in result:- reward = float(result["reward"])-- return TaskResult(+ if env.evaluate_task_fn is None:+ raise ValueError("Task has no evaluator")+ result = await env.evaluate()+ if isinstance(result, dict) and "reward" in result:+ values = [result["reward"]]+ elif isinstance(result, list) and result:+ values = result+ else:+ values = [result]+ for value in values:+ if not isinstance(value, (int, float)):+ raise ValueError("Evaluator reward must be numeric")+ if not math.isfinite(value) or not 0.0 <= value <= 1.0:+ raise ValueError("Evaluator reward must be finite and within [0, 1]")+ reward = float(values[0])++ outcome = TaskResult(task_path=str(env_path),variant_id=task_index,success=reward >= 0.5, # Common thresholdreward=reward,steps=step_count,)+ return outcomeexcept Exception as e:- return TaskResult(+ outcome = TaskResult(task_path=str(env_path),variant_id=task_index,success=False,reward=0.0,- steps=0,+ steps=step_count,error=str(e),)+ return outcomefinally:if env is not None:try:await env.close()- except Exception:- pass+ except Exception as close_error:+ if outcome is not None:+ outcome.success = False+ outcome.reward = 0.0+ detail = f"Environment cleanup failed: {close_error}"+ outcome.error = f"{outcome.error}; {detail}" if outcome.error else detailasync def run_benchmark(@@ -222,6 +243,13 @@ async def run_benchmark(max_parallel=4,)"""+ if type(max_parallel) is not int or max_parallel < 1:+ raise ValueError("max_parallel must be a positive integer")+ if max_variants is not None and (type(max_variants) is not int or max_variants < 1):+ raise ValueError("max_variants must be a positive integer or None")+ if type(max_steps) is not int or max_steps < 1:+ raise ValueError("max_steps must be a positive integer")+start_time = time.time()# Validate dataset path@@ -249,16 +277,26 @@ async def run_benchmark(# Expand tasks to (task_path, variant_id) tuplestask_variants: List[Tuple[Path, int]] = []for task_path in tasks:+ env = Nonetry:env = make(str(task_path), split=split)if env.tasks_config_fn:variant_count = len(env.tasks_config_fn())else:variant_count = 1- except Exception:- variant_count = 1-- if max_variants:+ except Exception as exc:+ raise RuntimeError(f"Unable to discover variants for {task_path}") from exc+ finally:+ if env is not None:+ try:+ await env.close()+ except Exception as exc:+ raise RuntimeError(+ f"Unable to close discovery environment for {task_path}"+ ) from exc+ if variant_count < 1:+ raise ValueError(f"Invalid variant count for {task_path}: {variant_count!r}")+ if max_variants is not None:variant_count = min(variant_count, max_variants)for variant_id in range(variant_count):diff --git a/libs/cua-bench/cua_bench/tests/test_run_benchmark.py b/libs/cua-bench/cua_bench/tests/test_run_benchmark.pyindex ec1ac0b116..5180bc537e 100644--- a/libs/cua-bench/cua_bench/tests/test_run_benchmark.py+++ b/libs/cua-bench/cua_bench/tests/test_run_benchmark.py@@ -410,3 +410,357 @@ async def setup(task, session):assert task_cfg.description == "Interactive task"finally:await env.close()+++class TestEvaluatorRewardFailClosed:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("value", [[1.0, float("nan")], [1.0, "bad"], [1.0, 1.5]])+ async def test_invalid_secondary_reward_cannot_claim_success(+ self, tmp_path, monkeypatch, value+ ):+ from types import SimpleNamespace+ import cua_bench.runners as runners++ class FakeEnvironment:+ evaluate_task_fn = object()+ solve_task_fn = None++ async def reset(self, task_id=0):+ return b"screen", SimpleNamespace()++ async def step(self, action):+ return b"screen"++ async def evaluate(self):+ return value++ async def close(self):+ pass++ monkeypatch.setattr(runners, "make", lambda *args, **kwargs: FakeEnvironment())+ result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())+ assert result.success is False+ assert result.reward == 0.0+ assert result.error is not None++ @pytest.mark.asyncio+ @pytest.mark.parametrize("value", ["1.0", None, float("nan"), float("inf"), -0.1, 1.1])+ async def test_invalid_reward_cannot_claim_success(self, tmp_path, monkeypatch, value):+ from types import SimpleNamespace+ import cua_bench.runners as runners++ class FakeEnvironment:+ evaluate_task_fn = object()+ solve_task_fn = None++ async def reset(self, task_id=0):+ return b"screen", SimpleNamespace()++ async def step(self, action):+ return b"screen"++ async def evaluate(self):+ return value++ async def close(self):+ pass++ monkeypatch.setattr(runners, "make", lambda *args, **kwargs: FakeEnvironment())+ result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())+ assert result.success is False+ assert result.reward == 0.0+ assert result.error is not None++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "value, reward",+ [+ (True, 1.0),+ (False, 0.0),+ ([1.0, True], 1.0),+ ({"reward": True}, 1.0),+ (0.75, 0.75),+ ({"reward": 1.0}, 1.0),+ ],+ )+ async def test_valid_reward(self, tmp_path, monkeypatch, value, reward):+ from types import SimpleNamespace+ import cua_bench.runners as runners++ class FakeEnvironment:+ evaluate_task_fn = object()++ async def reset(self, task_id=0):+ return b"screen", SimpleNamespace()++ async def step(self, action):+ return b"screen"++ async def evaluate(self):+ return value++ async def close(self):+ pass++ monkeypatch.setattr(runners, "make", lambda *args, **kwargs: FakeEnvironment())+ result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())+ assert result.success is (reward >= 0.5)+ assert result.reward == reward+ assert result.error is None++ @pytest.mark.asyncio+ async def test_missing_evaluator_cannot_claim_success(self, tmp_path, monkeypatch):+ from types import SimpleNamespace+ import cua_bench.runners as runners++ class FakeEnvironment:+ evaluate_task_fn = None+ solve_task_fn = None++ async def reset(self, task_id=0):+ return b"screen", SimpleNamespace()++ async def step(self, action):+ return b"screen"++ async def close(self):+ pass++ monkeypatch.setattr(runners, "make", lambda *args, **kwargs: FakeEnvironment())+ result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())+ assert result.success is False+ assert result.error is not None++ @pytest.mark.asyncio+ async def test_setup_only_cannot_claim_success_even_if_evaluator_would_pass(+ self, tmp_path, monkeypatch+ ):+ from types import SimpleNamespace+ import cua_bench.runners as runners++ calls = {"evaluated": False, "closed": False}++ class AlreadySatisfied:+ evaluate_task_fn = object()+ solve_task_fn = None++ async def reset(self, task_id=0):+ return b"screen", SimpleNamespace()++ async def evaluate(self):+ calls["evaluated"] = True+ return 1.0++ async def close(self):+ calls["closed"] = True++ monkeypatch.setattr(runners, "make", lambda *args, **kwargs: AlreadySatisfied())+ result = await runners.run_single_task(tmp_path)+ assert result.success is False+ assert result.reward == 0.0+ assert "No agent_fn" in result.error+ assert calls["evaluated"] is False+ assert calls["closed"] is True++ @pytest.mark.asyncio+ async def test_cleanup_failure_revokes_success_and_keeps_steps(self, tmp_path, monkeypatch):+ from types import SimpleNamespace+ import cua_bench.runners as runners++ class FailedCleanup:+ evaluate_task_fn = object()+ solve_task_fn = None++ async def reset(self, task_id=0):+ return b"screen", SimpleNamespace()++ async def step(self, action):+ return b"screen"++ async def evaluate(self):+ return 1.0++ async def close(self):+ raise RuntimeError("injected close failure")++ monkeypatch.setattr(runners, "make", lambda *a, **k: FailedCleanup())+ result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())+ assert result.success is False+ assert result.reward == 0.0+ assert result.steps == 1+ assert "Environment cleanup failed" in result.error++ @pytest.mark.asyncio+ async def test_mid_execution_failure_retains_completed_step_count(self, tmp_path, monkeypatch):+ from types import SimpleNamespace+ import cua_bench.runners as runners++ class FailedStep:+ solve_task_fn = None++ def __init__(self):+ self.calls = 0+ self.closed = False++ async def reset(self, task_id=0):+ return b"screen", SimpleNamespace()++ async def step(self, action):+ self.calls += 1+ if self.calls == 3:+ raise RuntimeError("injected third step failure")+ return b"screen"++ async def close(self):+ self.closed = True++ env = FailedStep()+ monkeypatch.setattr(runners, "make", lambda *a, **k: env)+ result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: object(), max_steps=4)+ assert result.success is False+ assert result.steps == 2+ assert "third step failure" in result.error+ assert env.closed is True++ @pytest.mark.asyncio+ @pytest.mark.parametrize("budget", [0, -1, False, True, 1.5, "2"])+ async def test_invalid_step_budget_cannot_score_initial_state(+ self, tmp_path, monkeypatch, budget+ ):+ import cua_bench.runners as runners++ def forbidden_make(*args, **kwargs):+ raise AssertionError("must reject before creating a task environment")++ monkeypatch.setattr(runners, "make", forbidden_make)+ with pytest.raises(ValueError, match="max_steps must be a positive integer"):+ await runners.run_single_task(+ tmp_path, agent_fn=lambda *_: DoneAction(), max_steps=budget+ )++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "value",+ [+ {"reward": None},+ {"reward": "1.0"},+ {"reward": float("nan")},+ {"reward": float("inf")},+ {"reward": -0.1},+ {"reward": 1.1},+ {"score": 1.0},+ ],+ )+ async def test_invalid_mapping_reward_cannot_claim_success(self, tmp_path, monkeypatch, value):+ from types import SimpleNamespace+ import cua_bench.runners as runners++ class FakeEnvironment:+ evaluate_task_fn = object()+ solve_task_fn = None++ async def reset(self, task_id=0):+ return b"screen", SimpleNamespace()++ async def step(self, action):+ return b"screen"++ async def evaluate(self):+ return value++ async def close(self):+ pass++ monkeypatch.setattr(runners, "make", lambda *a, **k: FakeEnvironment())+ result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())+ assert result.success is False+ assert result.reward == 0.0+ assert result.error is not None+++class TestBenchmarkDiscoveryFailClosed:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("parallel", [0, -1, True, 1.5, "2"])+ async def test_invalid_parallelism_rejected_before_task_discovery(self, tmp_path, parallel):+ import cua_bench.runners as runners++ with pytest.raises(ValueError, match="max_parallel must be a positive integer"):+ await runners.run_benchmark(tmp_path, max_parallel=parallel)++ @pytest.mark.asyncio+ @pytest.mark.parametrize("limit", [0, -1, True, 1.5, "2"])+ async def test_invalid_variant_limit_rejected(self, tmp_path, limit):+ import cua_bench.runners as runners++ with pytest.raises(ValueError, match="max_variants must be a positive integer"):+ await runners.run_benchmark(tmp_path, max_variants=limit)++ @pytest.mark.asyncio+ async def test_variant_discovery_failure_is_not_silently_scored(self, tmp_path, monkeypatch):+ import cua_bench.runners as runners++ task_dir = tmp_path / "task"+ task_dir.mkdir()+ (task_dir / "main.py").write_text("# fixture\n")++ def broken_make(*args, **kwargs):+ raise RuntimeError("invalid task fixture")++ monkeypatch.setattr(runners, "make", broken_make)+ with pytest.raises(RuntimeError, match="Unable to discover variants"):+ await runners.run_benchmark(tmp_path, oracle=True)++ @pytest.mark.asyncio+ async def test_discovery_environment_is_closed_before_execution(self, tmp_path, monkeypatch):+ import cua_bench.runners as runners++ task_dir = tmp_path / "task"+ task_dir.mkdir()+ (task_dir / "main.py").write_text("# fixture\n")++ calls = {"closed": 0}++ class DiscoveryEnvironment:+ def tasks_config_fn(self):+ return [object()]++ async def close(self):+ calls["closed"] += 1++ def make_for_discovery(*args, **kwargs):+ return DiscoveryEnvironment()++ async def fake_run(*args, **kwargs):+ assert calls["closed"] == 1+ return runners.TaskResult(+ task_path=str(task_dir),+ variant_id=0,+ success=False,+ reward=0.0,+ steps=0,+ error="not executed",+ )++ monkeypatch.setattr(runners, "make", make_for_discovery)+ monkeypatch.setattr(runners, "run_single_task", fake_run)+ await runners.run_benchmark(tmp_path)+ assert calls["closed"] == 1++ @pytest.mark.asyncio+ async def test_discovery_cleanup_failure_blocks_benchmark(self, tmp_path, monkeypatch):+ import cua_bench.runners as runners++ task_dir = tmp_path / "task"+ task_dir.mkdir()+ (task_dir / "main.py").write_text("# fixture\n")++ class DiscoveryEnvironment:+ def tasks_config_fn(self):+ return [object()]++ async def close(self):+ raise RuntimeError("cleanup failure")++ monkeypatch.setattr(runners, "make", lambda *a, **k: DiscoveryEnvironment())+ with pytest.raises(RuntimeError, match="Unable to close discovery environment"):+ await runners.run_benchmark(tmp_path)