Download tasks/efflora__fossify-compose-screens/tests/verifier/evaluator.py from efflora/android-bench-sample: direct link, hf CLI and curl.
- Browser
- Download file 47.7 kB
-
https://huggingface.co/datasets/efflora/android-bench-sample/resolve/main/tasks/efflora__fossify-compose-screens/tests/verifier/evaluator.py
- Command line
-
hf download hf://datasets/efflora/android-bench-sample/tasks/efflora__fossify-compose-screens/tests/verifier/evaluator.py
-
curl -L -o evaluator.py https://huggingface.co/datasets/efflora/android-bench-sample/resolve/main/tasks/efflora__fossify-compose-screens/tests/verifier/evaluator.py
47.7 kB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import glob
import json
import logging
import os
import shutil
import subprocess
import sys
import re
import traceback
import tomli as tomllib
# Add the project root to the Python path to ensure we pick up the correct modules
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
sys.path.insert(0, project_root)
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import List
import helpers, shell
from benchmark import (
BenchmarkTask,
Status,
TokenDetails,
STATUS_DESCRIPTIONS,
)
from config import config
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
@dataclass
class BenchmarkResult:
score: float
diagnostics: List[str]
status: Status
used_tokens: TokenDetails | None = None
exported_passed_tests: List[str] = field(default_factory=list)
exported_failed_tests: List[str] = field(default_factory=list)
partial_score: float = 0.0
pass_rate: float = 0.0
validation_results: dict[str, bool] = field(default_factory=dict)
scoring_breakdown: dict = field(default_factory=dict)
custom_metrics: dict = field(default_factory=dict)
def to_dict(self):
data = asdict(self)
data["status"] = self.status.name
data["status_description"] = STATUS_DESCRIPTIONS.get(self.status, "")
custom = data.pop("custom_metrics", {})
if custom:
data.update(custom)
return data
def run_benchmark_task(
task: BenchmarkTask,
output_dir: Path | None = None,
export_tests: bool = False,
keep_tests: bool = False,
) -> BenchmarkResult:
emulator_process = None
repo_name = task.repo_url.split("/")[-1].replace(".git", "")
work_dir = (
Path(repo_name) / task.work_dir if task.work_dir else Path("/workspace/testbed")
)
if not work_dir.exists():
logger.error(f"Working directory not found: {work_dir}")
return BenchmarkResult(
score=0.0,
diagnostics=[f"Working directory not found: {work_dir}"],
status=Status.INFRA_FAILURE_SETUP_ISSUE,
)
# Log task execution summary
logger.info("=" * 70)
logger.info(f"STARTING BENCHMARK TASK: {task.instance_id}")
logger.info(f"Repository: {task.repo_url}")
logger.info(f"Work directory: {work_dir}")
logger.info(f"Patch file: {task.patch_file}")
logger.info(f"Test commands: {task.test_commands}")
if keep_tests:
logger.info("Keep tests: True")
os.environ["KEEP_TESTS"] = "true" if keep_tests else "false"
logger.info("=" * 70)
try:
log_file = os.path.join(work_dir, "log.txt")
emulator_process = None
# --- Set Java Version ---
java_home = f"/usr/lib/jvm/java-{task.env_config.jdk_version}-openjdk-amd64"
logger.info(f"Instance {task.instance_id}: Setting JAVA_HOME to: {java_home}")
helpers.update_local_properties(work_dir, java_home)
# --- Repository Setup ---
logger.info(f"Instance {task.instance_id}: Using working directory: {work_dir}")
result = shell.run_command("pwd && ls", cwd=str(work_dir))
logger.debug(f"Instance {task.instance_id}: pwd && ls = {result.stdout}")
if task.startup_script and task.startup_script.exists():
logger.info(
f"Instance {task.instance_id}: Running startup script: {task.startup_script}"
)
script_command = f"bash {task.startup_script.resolve().as_posix()}"
result = shell.run_command(script_command, cwd=str(work_dir))
logger.info(
f"Instance {task.instance_id}: Startup script output: {result.stdout}\n{result.stderr}"
)
if result.exit_code != 0:
return BenchmarkResult(
score=0.0,
diagnostics=[f"Startup script failed: {result.stderr}"],
status=Status.INFRA_FAILURE_SETUP_ISSUE,
)
# Save current git work to patch
try:
subprocess.run(
"git add -A && git diff --cached --binary > /logs/artifacts/_submission.patch && git reset",
shell=True,
cwd=str(work_dir),
check=False,
)
except Exception as e:
logger.warning(f"Failed to save submission patch: {e}")
# Revert patterns selection
if task.revert_patterns is not None:
revert_patterns = list(task.revert_patterns)
else:
# Revert changes to test files
revert_patterns = [
# Some tasks expect the agent to make changes to build files, so these should not be reverted.
# "**/build.gradle.kts",
# "**/build/**",
"**/androidTest/**",
"**/androidTests/**",
"**/src/*Test/**",
"**/testFixtures/**",
"**/[tT]est/**",
"**/[tT]esting/**",
"**/[tT]ests/**",
"**/*Test.*",
"**/*Tests.*",
"**/test.*",
"**/tests.*",
]
exclude_config = ":!*.gradle.kts"
diagnostics = []
if task.test_files:
revert_patterns.extend(task.test_files)
if not keep_tests:
# Revert changes to test files.
for pattern in revert_patterns:
logger.info(
f"Instance {task.instance_id}: Reverting pattern: {pattern}"
)
shell.run_command(
f"git checkout HEAD -- '{pattern}' '{exclude_config}'",
cwd=str(work_dir),
)
# Remove untracked test files
for pattern in revert_patterns:
logger.info(f"Instance {task.instance_id}: Cleaning pattern: {pattern}")
shell.run_command(
f"git clean -fd '{pattern}' -- '{exclude_config}'",
cwd=str(work_dir),
)
# Apply test patch
if task.test_patch_file and task.test_patch_file.exists():
logger.info(
f"Instance {task.instance_id}: Applying test patch: {task.test_patch_file.name}..."
)
result = shell.run_command(
f"git apply {task.test_patch_file.resolve().as_posix()}",
cwd=str(work_dir),
)
if result.stdout:
logger.info(f"git apply (test) patch stdout: {result.stdout}")
if result.stderr:
logger.info(f"git apply (test) patch stderr: {result.stderr}")
if result.exit_code != 0:
return BenchmarkResult(
score=0.0,
diagnostics=[f"git apply (test) patch failed: {result.stderr}"],
status=Status.INFRA_FAILURE_SETUP_ISSUE,
)
else:
logger.info(
f"Instance {task.instance_id}: Skipping reverting and cleaning of test files as keep_tests is enabled."
)
# Run after agent commands
if task.after_agent_commands:
logger.info(
f"Instance {task.instance_id}: Running after agent commands: {task.after_agent_commands}"
)
if not helpers.run_after_agent_commands(
task.after_agent_commands, str(work_dir)
):
diagnostics.append("Failed to run after agent commands.")
return BenchmarkResult(
score=0.0,
diagnostics=diagnostics,
status=Status.AGENT_FAILED_AFTER_CMD,
)
# Check project's build status
if not helpers.can_compile_successfully(task.build_commands, str(work_dir)):
diagnostics.append("Project failed to compile.")
return BenchmarkResult(
score=0.0,
diagnostics=diagnostics,
status=Status.AGENT_FAILED_BUILD,
)
# Normalize composable lambda hash names in test results.
pass_to_pass_tests_list = [
re.sub(
r"ComposableLambdaImpl@[a-zA-Z0-9]+(?=\))", "ComposableLambdaImpl", s
)
for s in task.pass_to_pass_tests or []
]
fail_to_pass_tests_list = [
re.sub(
r"ComposableLambdaImpl@[a-zA-Z0-9]+(?=\))", "ComposableLambdaImpl", s
)
for s in task.fail_to_pass_tests or []
]
must_pass_tests = set(pass_to_pass_tests_list + fail_to_pass_tests_list)
all_tests_must_pass = len(must_pass_tests) == 0
if all_tests_must_pass:
diagnostics.append(
"pass_to_pass and fail_to_pass tests are not specified in the yaml, verifying all tests."
)
else:
diagnostics.append(
f"Verifying {len(pass_to_pass_tests_list)} pass_to_pass tests and {len(fail_to_pass_tests_list)} fail_to_pass tests."
)
# Aggregate test results across all command invocations
all_passed_tests: set[str] = set()
all_failed_tests: set[str] = set()
validation_results: dict[str, bool] = {}
old_fashioned_test_naming = True
# Structured test names use {TaskName}#Test {testName}({testClass})
TEST_NAME_REGEX = r"^\w+#Test"
if (
fail_to_pass_tests_list
and re.match(TEST_NAME_REGEX, fail_to_pass_tests_list[0])
) or (
pass_to_pass_tests_list
and re.match(TEST_NAME_REGEX, pass_to_pass_tests_list[0])
):
old_fashioned_test_naming = False
test_attempts = 0
status = Status.AGENT_FAILED_TEST
# Run tests multiple times to prevent flakes marking a test as failed incorrectly
while (
test_attempts < config.emulator_config.test_retry_attempts
and status != Status.PASSED
):
# Start emulator
if any("AndroidTest" in t for t in task.test_commands):
try:
emulator_process = helpers.start_and_wait_for_emulator(
log_file,
task.env_config.emulator_name,
timeout_seconds=config.emulator_config.emulator_boot_timeout,
)
except helpers.EmulatorMissingError as e:
logger.error(f"Emulator missing: {e}")
return BenchmarkResult(
score=0.0,
diagnostics=[str(e)],
status=Status.INFRA_FAILURE_EMULATOR_STARTUP,
)
except Exception as e:
logger.error(f"Failed to start emulator: {e}")
return BenchmarkResult(
score=0.0,
diagnostics=[f"Failed to start emulator: {e}"],
status=Status.INFRA_FAILURE_EMULATOR_STARTUP,
)
test_attempts = test_attempts + 1
logger.info("=" * 70)
logging.info(f"Running test attempt: {test_attempts}")
diagnostics.append(f"Running test attempt: {test_attempts}")
logger.info("=" * 70)
status = _run_tests(
task,
work_dir,
all_tests_must_pass,
diagnostics,
all_passed_tests,
all_failed_tests,
old_fashioned_test_naming,
)
# Guard against flakes by assuming if a test passed on any run, it is a pass
all_failed_tests = all_failed_tests - all_passed_tests
# After all commands, check if any must_pass test failed (across all invocations)
if status == Status.PASSED and not all_tests_must_pass:
failed_must_pass = must_pass_tests & all_failed_tests
not_passed_must_pass = must_pass_tests - all_passed_tests
if failed_must_pass:
for failed_test in sorted(failed_must_pass):
diagnostics.append(f"Must Pass test failed: '{failed_test}'")
status = Status.AGENT_FAILED_TEST
elif not_passed_must_pass:
# It would reach here if:
# 1. Build is successful, so all_passed_tests and/or all_failed_tests are non empty.
# 2. not_passed_must_pass tests are not in either all_passed_tests or all_failed_tests.
# So we can say that gradle did not run those tests.
for not_passed_test in sorted(not_passed_must_pass):
diagnostics.append(
f"Must Pass test wasn't executed: '{not_passed_test}'"
)
status = Status.AGENT_MISSING_REQUIRED_TEST_RESULTS
diagnostics.append(f"Test attempt {test_attempts}: {status}")
logger.info("=" * 70)
# Get passing and failing tests to calculate f2p and p2p for enriched tasks
exported_passed_tests: set[str] = set()
exported_failed_tests: set[str] = set()
if export_tests:
# Run tests multiple times to filter out flaky tests
for test_attempts in range(
1, config.emulator_config.test_retry_attempts + 1
):
logger.info("=" * 70)
logging.info(f"Running test attempt: {test_attempts}")
diagnostics.append(f"Running test attempt: {test_attempts}")
logger.info("=" * 70)
_get_test_results(
task,
work_dir,
exported_passed_tests,
exported_failed_tests,
is_first_attempt=test_attempts == 1,
)
validation_results = {}
global_script_failed = False
global_script_result = None
task_script_failed = False
task_script_result = None
# Clear any previous validation results file to ensure a clean slate
check_results_file = Path("/logs/verifier/validate_results.txt")
if check_results_file.exists():
try:
check_results_file.unlink()
logger.info("Cleared previous validate_results.txt file.")
except Exception as e:
logger.error(f"Failed to clear previous check results file: {e}")
env = os.environ.copy()
task_scoring = getattr(task, "scoring", None) or {}
global_checks = task_scoring.get("global_checks") or {}
if isinstance(global_checks, dict):
skip_list = global_checks.get("skip", [])
if isinstance(skip_list, list):
for check_name in skip_list:
env_key = f"SKIP_{str(check_name).upper()}"
env[env_key] = "1"
# 1. Run global validation script (bash)
global_validation_file = Path(__file__).parent / "scoring" / "validate.sh"
if global_validation_file.exists():
logger.info(
f"Instance {task.instance_id}: Running global validation script: {global_validation_file}"
)
os.chmod(global_validation_file, 0o755)
script_command = f"bash {global_validation_file.resolve().as_posix()}"
result = shell.run_command(script_command, cwd=str(work_dir), env=env)
logger.info(
f"Instance {task.instance_id}: Global validation script output: {result.stdout}\n{result.stderr}"
)
global_script_result = result
if result.exit_code != 0:
global_script_failed = True
else:
logger.info("No global validation script present")
# 2. Run task-specific validation script (bash)
if task.validation_file and task.validation_file.exists():
logger.info(
f"Instance {task.instance_id}: Running validation script: {task.validation_file}"
)
script_command = f"bash {task.validation_file.resolve().as_posix()}"
result = shell.run_command(script_command, cwd=str(work_dir))
logger.info(
f"Instance {task.instance_id}: Validation script output: {result.stdout}\n{result.stderr}"
)
if result.exit_code != 0:
task_script_failed = True
task_script_result = result
else:
logger.info("No task-specific validation script present")
# 3. Read validation checks results (Flat Text)
check_results_file = Path("/logs/verifier/validate_results.txt")
validation_messages = {}
if check_results_file.exists():
try:
with open(check_results_file, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
k, v = line.split(":", 1)
val_str = v.strip()
message = ""
# If a pipe "|" is present, extract the rich reasoning message
if " | " in val_str:
val_str, message = val_str.split(" | ", 1)
try:
validation_results[k.strip()] = float(val_str)
except ValueError:
validation_results[k.strip()] = (
1.0 if val_str.lower() == "pass" else 0.0
)
if message:
validation_messages[k.strip()] = message
logger.info(f"Loaded check results (txt): {validation_results}")
except Exception as e:
logger.error(f"Failed to read check results: {e}")
code_quality_score = None
code_quality_violations = None
code_quality_file = Path("/logs/verifier/code_quality.json")
if code_quality_file.exists():
try:
with open(code_quality_file, "r") as f:
cq_data = json.load(f)
if "score" in cq_data and cq_data["score"] is not None:
code_quality_score = float(cq_data["score"])
if (
"violations_count" in cq_data
and cq_data["violations_count"] is not None
):
code_quality_violations = int(cq_data["violations_count"])
logger.info(
f"Loaded check results (code quality): score={code_quality_score}, violations={code_quality_violations}"
)
except Exception as e:
logger.error(f"Failed to read code quality results: {e}")
# 4. Determine final validation status
validation_failed = (
global_script_failed
or task_script_failed
or any(v < 1.0 for v in validation_results.values())
)
if validation_failed:
status = Status.AGENT_FAILED_VALIDATION
if (global_script_failed or task_script_failed) and not validation_results:
failed_script = (
global_script_result if global_script_failed else task_script_result
)
diagnostics.append(
f"Validation script failed: {failed_script.stdout}|{failed_script.stderr}"
)
else:
failed_checks = [k for k, v in validation_results.items() if v < 1.0]
for check in failed_checks:
diagnostics.append(f"validation failed: {check}")
else:
if validation_results:
logger.info("All validation checks passed.")
# Calculate partial score
(
partial_score,
scoring_breakdown,
pass_rate,
) = _evaluate_weighted_scoring(
task,
all_passed_tests,
all_failed_tests,
validation_results,
all_tests_must_pass,
must_pass_tests,
validation_messages=validation_messages,
code_quality_score=code_quality_score,
code_quality_violations=code_quality_violations,
)
custom_metrics = {}
if code_quality_score is not None:
custom_metrics["code_quality_score"] = round(code_quality_score, 4)
if code_quality_violations is not None:
custom_metrics["code_quality_violations"] = code_quality_violations
if status != Status.PASSED:
return BenchmarkResult(
score=0.0,
diagnostics=diagnostics,
status=status,
exported_passed_tests=sorted(list(exported_passed_tests)),
exported_failed_tests=sorted(list(exported_failed_tests)),
partial_score=partial_score,
pass_rate=pass_rate,
validation_results=validation_results,
scoring_breakdown=scoring_breakdown,
custom_metrics=custom_metrics,
)
if status == Status.PASSED and test_attempts > 1:
status = Status.PASSED_FLAKY
return BenchmarkResult(
score=1.0,
diagnostics=diagnostics,
status=status,
exported_passed_tests=sorted(list(exported_passed_tests)),
exported_failed_tests=sorted(list(exported_failed_tests)),
partial_score=partial_score,
pass_rate=pass_rate,
validation_results=validation_results,
scoring_breakdown=scoring_breakdown,
custom_metrics=custom_metrics,
)
except helpers.EmulatorStartupTimeoutError as e:
return BenchmarkResult(
score=0.0,
diagnostics=[
f"Emulator failed to start within {e.timeout_seconds} seconds"
],
status=Status.INFRA_FAILURE_EMULATOR_TIMEOUT,
)
except helpers.EmulatorFailedToStartError as e:
return BenchmarkResult(
score=0.0,
diagnostics=["Emulator failed to start"],
status=Status.INFRA_FAILURE_EMULATOR_STARTUP,
)
finally:
if output_dir:
try:
helpers.copy_build_outputs(work_dir, output_dir)
except Exception as e:
logger.error(f"Failed to copy build outputs: {e}")
if emulator_process:
logger.info(f"Instance {task.instance_id}: --- Stopping emulator ---")
emulator_process.terminate()
try:
emulator_process.wait(timeout=30)
except subprocess.TimeoutExpired:
emulator_process.kill()
# Cleanup to avoid hangs
logger.info(
f"Instance {task.instance_id}: Starting aggressive environment teardown..."
)
try:
gradlew_path = work_dir / "gradlew"
if gradlew_path.exists():
subprocess.run(
[str(gradlew_path), "--stop"], timeout=30, capture_output=True
)
subprocess.run(
["pkill", "-9", "-f", "gradle"], timeout=10, capture_output=True
)
except Exception:
pass
try:
subprocess.run(["adb", "kill-server"], timeout=10, capture_output=True)
except Exception:
pass
subprocess.run(["pkill", "-9", "-f", "java"], capture_output=True)
subprocess.run(["pkill", "-9", "-f", "android"], capture_output=True)
def _get_test_results(
task,
work_dir,
exported_passed_tests,
exported_failed_tests,
is_first_attempt: bool,
):
this_attempt_passed: set[str] = set()
this_attempt_failed: set[str] = set()
helpers.clean_test_outputs(str(work_dir))
for command in task.test_commands:
logger.info(f"Instance {task.instance_id}: Executing: {command}")
test_result = helpers.run_tests(
str(work_dir),
command,
timeout=config.emulator_config.test_execution_timeout,
workers=config.emulator_config.gradle_workers,
remove_task_names=False,
)
logger.info(f"--- Command: {command} ---")
logger.info(f"--- Passed Tests: {len(test_result.passed_tests)} ---")
for test in sorted(test_result.passed_tests):
logger.info(f" {test}")
logger.info(f"--- Failed Tests: {len(test_result.failed_tests)} ---")
for test in sorted(test_result.failed_tests):
logger.info(f" {test}")
this_attempt_passed.update(test_result.passed_tests)
this_attempt_failed.update(test_result.failed_tests)
if is_first_attempt:
exported_passed_tests.update(this_attempt_passed)
exported_failed_tests.update(this_attempt_failed)
else:
exported_passed_tests.intersection_update(this_attempt_passed)
exported_failed_tests.intersection_update(this_attempt_failed)
def _run_tests(
task,
work_dir,
all_tests_must_pass,
diagnostics,
all_passed_tests,
all_failed_tests,
old_fashioned_test_naming,
):
helpers.clean_test_outputs(str(work_dir))
has_build_failure = False
has_test_failure = False
for command in task.test_commands:
logger.info(f"Instance {task.instance_id}: Executing: {command}")
test_result = helpers.run_tests(
str(work_dir),
command,
timeout=config.emulator_config.test_execution_timeout,
workers=config.emulator_config.gradle_workers,
remove_task_names=old_fashioned_test_naming,
)
logger.info(f"--- Command: {command} ---")
logger.info(f"--- Passed Tests: {len(test_result.passed_tests)} ---")
for test in sorted(test_result.passed_tests):
logger.info(f" {test}")
logger.info(f"--- Failed Tests: {len(test_result.failed_tests)} ---")
for test in sorted(test_result.failed_tests):
logger.info(f" {test}")
# Aggregate results
all_passed_tests.update(test_result.passed_tests)
all_failed_tests.update(test_result.failed_tests)
# Context: legit/258310/1/common/eval_data_classes.py#67
# We check result of build command if pass_to_pass + fail_to_pass tests are empty.
# We also can't prevent flakes in this scenario.
if not test_result.build_successful:
diagnostics.append(f"Build failed for command: '{command}'")
has_build_failure = True
if len(test_result.failed_tests) > 0:
logger.warning(f"Test command failed: '{command}'.")
diagnostics.append(f"Test failed, command: '{command}'")
has_test_failure = True
# For all_tests_must_pass mode, fail if any test or build failed.
# Note: Cannot differentiate between BUILD_FAILED and TEST_FAILED in this case,
# so marking it as AGENT_FAILED_TEST.
if all_tests_must_pass and (has_build_failure or has_test_failure):
return Status.AGENT_FAILED_TEST
return Status.PASSED
def _evaluate_weighted_scoring(
task,
all_passed_tests: set[str],
all_failed_tests: set[str],
validation_results: dict[str, float],
all_tests_must_pass: bool,
must_pass_tests: set[str],
validation_messages: dict[str, str] = None,
code_quality_score: float | None = None,
code_quality_violations: int | None = None,
) -> tuple[float, dict, float]:
"""Calculates weighted partial score based on categories and multipliers."""
local_passed = set(all_passed_tests)
local_failed = set(all_failed_tests)
local_must_pass = set(must_pass_tests)
# Add validation results to sets
for check_name, passed in validation_results.items():
validation_test_name = f"validate#{check_name}"
local_must_pass.add(validation_test_name)
if passed == 1.0:
local_passed.add(validation_test_name)
else:
local_failed.add(validation_test_name)
# 1. Calculate pass rate and filter tests based on must-pass requirements
if all_tests_must_pass:
total_tests = len(local_passed) + len(local_failed)
pass_rate = len(local_passed) / total_tests if total_tests > 0 else 0.0
else:
# Filter out any executed tests that are not part of the task's required tests (e.g. unit tests)
local_passed = local_passed & local_must_pass
local_failed = local_failed & local_must_pass
# Any required test that did not pass (either failed or unexecuted) is a failure
unpassed_required = local_must_pass - local_passed
local_failed.update(unpassed_required)
pass_rate = len(local_passed) / len(local_must_pass) if local_must_pass else 0.0
pass_rate = round(pass_rate, 4)
# 2. Get merged scoring configuration
task_scoring = task.scoring or {}
scoring_config = _get_merged_scoring_config(task_scoring)
weights = scoring_config.get("base_weights", {})
has_custom_weights = bool(weights)
# 3. Construct all_tests for classification
all_tests = []
if all_tests_must_pass:
# Loop over all executed tests
executed_tests = local_passed | local_failed
for check_name in validation_results:
executed_tests.add(f"validate#{check_name}")
for t in executed_tests:
if t.startswith("validate#"):
check_name = t.split("#", 1)[1]
if check_name in validation_results:
score = validation_results[check_name]
else:
score = 1.0 if t in local_passed else 0.0
else:
score = 1.0 if t in local_passed else 0.0
all_tests.append((t, score))
else:
# Loop over all required must-pass tests
for t in local_must_pass:
if t.startswith("validate#"):
check_name = t.split("#", 1)[1]
if check_name in validation_results:
score = validation_results[check_name]
else:
score = 1.0 if t in local_passed else 0.0
else:
score = 1.0 if t in local_passed else 0.0
all_tests.append((t, score))
if not has_custom_weights:
# If no weights are defined, consider all possible categories from config plus 'functional'
possible_categories = (
set(scoring_config.get("matchers", {}).keys())
| set(scoring_config.get("exact_matches", {}).keys())
| {"functional"}
)
category_names = sorted(list(possible_categories))
else:
category_names = list(weights.keys())
# 3. Classify tests into categories and identify failed multipliers
category_stats, failed_multipliers, scoring_logs = _classify_tests_into_categories(
all_tests,
scoring_config,
task,
category_names,
validation_messages=validation_messages,
)
if not has_custom_weights:
active_categories = [
c for c, stats in category_stats.items() if stats["total"] > 0
]
if not active_categories:
return pass_rate, {}, pass_rate
equal_weight = round(1.0 / len(active_categories), 4)
weights = {c: equal_weight for c in active_categories}
remainder = 1.0 - sum(weights.values())
if remainder != 0:
weights[active_categories[-1]] = round(
weights[active_categories[-1]] + remainder, 4
)
# 4. Perform final mathematical aggregation
partial_score, scoring_breakdown = _calculate_final_weighted_score(
category_stats,
failed_multipliers,
weights,
scoring_logs,
pass_rate,
code_quality_score=code_quality_score,
code_quality_violations=code_quality_violations,
)
return partial_score, scoring_breakdown, pass_rate
def _get_merged_scoring_config(task_scoring: dict) -> dict:
"""Loads common config and merges with task-specific overrides."""
common_scoring = {}
# Use script-relative path for portability (works in Docker and Local)
common_scoring_path = Path(__file__).parent / "scoring/common_scoring.toml"
if common_scoring_path.exists():
try:
with open(common_scoring_path, "rb") as f:
common_scoring = tomllib.load(f)
except Exception as e:
logger.error(f"Error loading common_scoring.toml: {e}")
# Extraction of rules and matchers
task_rules = task_scoring.get("rules") or {}
task_matchers = task_rules.get("matchers") or {}
common_rules = common_scoring.get("rules") or {}
common_matchers = common_rules.get("matchers") or {}
# Start with all task-defined matchers (preserving spec.toml order)
merged_matchers = dict(task_matchers)
# Append remaining global default matchers that weren't overridden
for category, patterns in common_matchers.items():
if category not in merged_matchers:
merged_matchers[category] = patterns
# Merge multipliers
merged_multipliers = common_scoring.get("multipliers", {}).get("tests", {}).copy()
if "multipliers" in task_scoring and "tests" in task_scoring["multipliers"]:
merged_multipliers.update(task_scoring["multipliers"]["tests"])
# Merge exact matches
merged_exact = common_rules.get("exact_matches", {}).copy()
if "exact_matches" in task_rules:
merged_exact.update(task_rules["exact_matches"])
# Filter out categories that are not defined in base_weights (if base_weights is specified)
base_weights = task_scoring.get("base_weights", {})
if base_weights:
active_categories = set(base_weights.keys())
merged_matchers = {
k: v for k, v in merged_matchers.items() if k in active_categories
}
merged_exact = {k: v for k, v in merged_exact.items() if k in active_categories}
# Merge rules
merged = {
"multipliers": merged_multipliers,
"matchers": merged_matchers,
"exact_matches": merged_exact,
"base_weights": base_weights,
}
return merged
def _classify_tests_into_categories(
all_tests: list[tuple[str, float]],
config: dict,
task,
category_names: list[str],
validation_messages: dict[str, str] = None,
) -> tuple[dict, list[dict], list[str]]:
"""Sorts test results into category statistics and identifies failed multipliers."""
category_stats = {c: {"passed": 0.0, "total": 0} for c in category_names}
failed_multipliers = []
scoring_logs = []
multipliers = config["multipliers"]
rules_exact = config["exact_matches"]
rules_matchers = config["matchers"]
for test_name, score in all_tests:
# Check multipliers
is_multiplier = False
for mult_test_name, penalty in multipliers.items():
if mult_test_name in test_name:
is_multiplier = True
if score < 1.0:
# Extract reasoning message for diagnostics
reasoning = "Test failed during benchmark execution."
if validation_messages and mult_test_name.startswith("validate#"):
check_key = mult_test_name.replace("validate#", "", 1)
reasoning = validation_messages.get(check_key, reasoning)
failed_multipliers.append(
{
"name": mult_test_name,
"value": penalty,
"reasoning": reasoning,
}
)
break
if is_multiplier:
continue
matched_category = None
# Check Exact matches
matched_exact = [
cat
for cat, tests in rules_exact.items()
if test_name in tests or any(test_name == f"validate#{t}" for t in tests)
]
if matched_exact:
matched_category = matched_exact[0]
if len(matched_exact) > 1:
log_msg = (
f"Test '{test_name}' matched multiple EXACT categories: {matched_exact}. "
f"Defaulting to '{matched_category}' because it was defined first in the configuration."
)
logger.info(log_msg)
scoring_logs.append(log_msg)
# Check Regex/Magic matches
if not matched_category:
matched_regex = []
for category, patterns in rules_matchers.items():
for pattern in patterns:
is_match = False
if pattern == "^pass_to_pass$":
if (
task.pass_to_pass_tests
and test_name in task.pass_to_pass_tests
):
is_match = True
elif pattern == "^fail_to_pass$":
if (
task.fail_to_pass_tests
and test_name in task.fail_to_pass_tests
):
is_match = True
elif pattern in test_name or re.search(pattern, test_name):
is_match = True
if is_match:
matched_regex.append(category)
break
if matched_regex:
matched_category = matched_regex[0]
if len(matched_regex) > 1:
log_msg = (
f"Test '{test_name}' matched multiple REGEX categories: {matched_regex}. "
f"Defaulting to '{matched_category}' because it was defined first in the configuration."
)
logger.info(log_msg)
scoring_logs.append(log_msg)
if not matched_category:
log_msg = f"WARNING: Test '{test_name}' did not match any category rules. It will be IGNORED and not scored."
logger.warning(log_msg)
scoring_logs.append(log_msg)
if matched_category in category_stats:
category_stats[matched_category]["total"] += 1
category_stats[matched_category]["passed"] += score
return category_stats, failed_multipliers, scoring_logs
def _calculate_final_weighted_score(
category_stats: dict,
failed_multipliers: list[dict],
weights: dict,
scoring_logs: list[str],
pass_rate: float,
code_quality_score: float | None = None,
code_quality_violations: int | None = None,
) -> tuple[float, dict]:
"""Performs the weighted sum and applies multiplicative penalties."""
base_score = 0.0
breakdown_categories = {}
total_weight = sum(float(w) for w in weights.values())
if total_weight == 0.0:
total_weight = 1.0
for category, raw_weight in weights.items():
weight = float(raw_weight) / total_weight
stats = category_stats[category]
rate = stats["passed"] / stats["total"] if stats["total"] > 0 else 0.0
contribution = round(rate * weight, 4)
base_score += contribution
passed_val = stats["passed"]
if passed_val == int(passed_val):
passed_val = int(passed_val)
else:
passed_val = round(passed_val, 4)
breakdown_categories[category] = {
"passed": passed_val,
"total": stats["total"],
"weight": round(weight, 4),
"raw_weight": float(raw_weight),
"score": round(rate, 4),
"contribution": contribution,
}
if code_quality_score is not None:
breakdown_categories["code_quality"] = {
"passed": round(code_quality_score, 4),
"total": 1.0,
"weight": 0.0,
"raw_weight": 0.0,
"score": round(code_quality_score, 4),
"contribution": 0.0,
"violations_count": (
code_quality_violations if code_quality_violations is not None else 0
),
}
base_score = round(base_score, 4)
final_score = base_score
for item in failed_multipliers:
final_score *= float(item["value"])
final_score = round(final_score, 4)
breakdown = {
"base_score": base_score,
"categories": breakdown_categories,
"multipliers_applied": failed_multipliers,
"logs": scoring_logs,
}
return final_score, breakdown
def save_benchmark_result(
instance_id: str,
result_value: BenchmarkResult,
verifier_dir: Path,
artifacts_dir: Path,
):
verifier_dir.mkdir(parents=True, exist_ok=True)
artifacts_dir.mkdir(parents=True, exist_ok=True)
# Create scores and rewards file
rewards_file = verifier_dir / "reward.txt"
if result_value.score == 1.0:
logger.info("=" * 70)
logger.info(f"TASK COMPLETED: {instance_id} - PASSED (score: 1.0)")
logger.info("=" * 70)
else:
logger.info("=" * 70)
logger.info(f"TASK COMPLETED: {instance_id} - FAILED (score: 0.0)")
logger.info("=" * 70)
logger.info(f"Partial score: {result_value.partial_score}")
rewards_file.write_text(f"{result_value.partial_score}\n")
# Extract token counts from trajectory.json if available
trajectory_file = Path("/logs/agent/trajectory.json")
if trajectory_file.exists():
try:
trajectory_data = json.loads(trajectory_file.read_text())
final_metrics = trajectory_data.get("final_metrics", {})
if final_metrics:
prompt_tokens = final_metrics.get("total_prompt_tokens", 0)
completion_tokens = final_metrics.get("total_completion_tokens", 0)
cached_tokens = final_metrics.get("total_cached_tokens", 0)
result_value.used_tokens = TokenDetails(
completion_tokens=completion_tokens,
prompt_tokens=prompt_tokens,
total_tokens=prompt_tokens + completion_tokens,
)
logger.info(
f"Extracted tokens from trajectory: prompt={prompt_tokens}, completion={completion_tokens}"
)
except Exception as e:
logger.warning(f"Could not parse trajectory for token details: {e}")
result_data = {instance_id: result_value.to_dict()}
scores_file = verifier_dir / "detailed_scores.json"
scores_file.write_text(json.dumps(result_data, indent=4))
# Copy to artifacts
artifacts_scores = artifacts_dir / "_detailed_scores.json"
shutil.copy(scores_file, artifacts_scores)
logger.info(
f"Successfully wrote results to {scores_file} and copied to {artifacts_scores}"
)
def main(
spec_toml_file: str,
export_tests: bool = False,
keep_tests: bool = False,
disable_partial_scoring: bool = False,
):
verifier_dir = Path("/logs/verifier")
verifier_dir.mkdir(parents=True, exist_ok=True)
artifacts_dir = Path("/logs/artifacts")
artifacts_dir.mkdir(parents=True, exist_ok=True)
task_json_data = {}
# Read the TOML task specification
with open(spec_toml_file, "rb") as f:
task_json_data = tomllib.load(f)
# Use 'id' as 'instance_id' when the latter is absent.
if "instance_id" not in task_json_data and "id" in task_json_data:
task_json_data["instance_id"] = task_json_data["id"]
instance_id = task_json_data.get("instance_id", "unknown")
try:
task = BenchmarkTask.from_json(json_data=task_json_data)
if task is None:
logger.error(f"Could not create task '{instance_id}'.")
raise Exception(f"Task creation failed for {instance_id}")
instance_id = task.instance_id
logger.info(f"Successfully created BenchmarkTask object for: {instance_id}")
if keep_tests:
logger.info(f"Instance {instance_id}: Using keep_tests=True")
result_value = run_benchmark_task(
task=task,
output_dir=artifacts_dir,
export_tests=export_tests,
keep_tests=keep_tests,
)
if disable_partial_scoring:
logger.info(
"Disabling partial scoring: Overwriting partial_score with binary score."
)
result_value.partial_score = result_value.score
save_benchmark_result(instance_id, result_value, verifier_dir, artifacts_dir)
sys.exit(0)
except Exception as e:
logger.error(f"Error running BenchmarkTask {instance_id}: {e}")
logger.error(traceback.format_exc())
result_data = {instance_id: f"Error: {e}"}
try:
scores_file = verifier_dir / "detailed_scores.json"
scores_file.write_text(json.dumps(result_data, indent=4))
shutil.copy(scores_file, artifacts_dir / "_detailed_scores.json")
except Exception:
pass
sys.exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run a benchmark task locally.")
parser.add_argument(
"--spec-toml-file",
"--task-toml-file",
dest="spec_toml_file",
type=str,
default="/tests/spec.toml",
help="Path to the TOML file containing the task specification.",
)
parser.add_argument(
"--export-tests",
action="store_true",
help="Export the test files.",
)
parser.add_argument(
"--keep-tests",
action="store_true",
help="Keep test files instead of reverting them.",
)
parser.add_argument(
"--disable-partial-scoring",
action="store_true",
help="Disable partial scoring and return binary score.",
)
args = parser.parse_args()
keep_tests = args.keep_tests or os.path.exists("/tmp/open_test.patch")
if keep_tests:
logger.info(
f"keep_tests enabled (args.keep_tests={args.keep_tests}, open_test.patch exists={os.path.exists('/tmp/open_test.patch')})"
)
main(
spec_toml_file=args.spec_toml_file,
export_tests=args.export_tests,
keep_tests=keep_tests,
disable_partial_scoring=args.disable_partial_scoring,
)
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import glob
import json
import logging
import os
import shutil
import subprocess
import sys
import re
import traceback
import tomli as tomllib
# Add the project root to the Python path to ensure we pick up the correct modules
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
sys.path.insert(0, project_root)
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import List
import helpers, shell
from benchmark import (
BenchmarkTask,
Status,
TokenDetails,
STATUS_DESCRIPTIONS,
)
from config import config
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
class BenchmarkResult:
score: float
diagnostics: List[str]
status: Status
used_tokens: TokenDetails | None = None
exported_passed_tests: List[str] = field(default_factory=list)
exported_failed_tests: List[str] = field(default_factory=list)
partial_score: float = 0.0
pass_rate: float = 0.0
validation_results: dict[str, bool] = field(default_factory=dict)
scoring_breakdown: dict = field(default_factory=dict)
custom_metrics: dict = field(default_factory=dict)
def to_dict(self):
data = asdict(self)
data["status"] = self.status.name
data["status_description"] = STATUS_DESCRIPTIONS.get(self.status, "")
custom = data.pop("custom_metrics", {})
if custom:
data.update(custom)
return data
def run_benchmark_task(
task: BenchmarkTask,
output_dir: Path | None = None,
export_tests: bool = False,
keep_tests: bool = False,
) -> BenchmarkResult:
emulator_process = None
repo_name = task.repo_url.split("/")[-1].replace(".git", "")
work_dir = (
Path(repo_name) / task.work_dir if task.work_dir else Path("/workspace/testbed")
)
if not work_dir.exists():
logger.error(f"Working directory not found: {work_dir}")
return BenchmarkResult(
score=0.0,
diagnostics=[f"Working directory not found: {work_dir}"],
status=Status.INFRA_FAILURE_SETUP_ISSUE,
)
# Log task execution summary
logger.info("=" * 70)
logger.info(f"STARTING BENCHMARK TASK: {task.instance_id}")