Skip to content

abc_runner.runner

WARNING

This documentation is almost entirely "vibe coded"; while a helpful resource for humans and agents to understand this codebase, it should not be considered a source of ground truth in the way documentation normally is, and the user is responsible for verifying that all instructions given here are safe.

abc_runner.runner

Benchmark orchestration for ABC Runner.

The heavy lifting of sandboxed execution lives in :mod:automaton. This module orchestrates a benchmark run on top of it:

  1. resolve the task, agent, harness, and runtime container,
  2. stage the workspace, prompt, and harness assets into a per-run directory,
  3. run the task's build_env.sh inside the container,
  4. run the agent via :meth:automaton.Sandbox.run_agent (deliverable is left in the workspace),
  5. run the task's hidden verification inside the container,
  6. compute PASS/FAIL, replace the full workspace with a delta against the task (the compressed result format, see :mod:abc_runner.result_format), and write result.json, metadata.json, and usage.json.

BenchmarkResult

BenchmarkResult(task_id: str, task_group: str, task_ref: str, agent_id: str, harness_id: str, model_names: list[str], status: str, result_dir: Path, verify_log: str | None = None, error: str | None = None, failure_phase: str | None = None, usage_summary: dict[str, Any] | None = None, model_apis: list[str | None] | None = None)

Result of a benchmark run.

Source code in abc_runner/runner.py
def __init__(
    self,
    task_id: str,
    task_group: str,
    task_ref: str,
    agent_id: str,
    harness_id: str,
    model_names: list[str],
    status: str,
    result_dir: Path,
    verify_log: str | None = None,
    error: str | None = None,
    failure_phase: str | None = None,
    usage_summary: dict[str, Any] | None = None,
    model_apis: list[str | None] | None = None,
):
    self.task_id = task_id
    self.task_group = task_group
    self.task_ref = task_ref
    self.agent_id = agent_id
    self.harness_id = harness_id
    self.model_names = model_names
    self.status = status
    self.result_dir = result_dir
    self.verify_log = verify_log
    self.error = error
    self.failure_phase = failure_phase
    self.usage_summary = usage_summary or {}
    self.model_apis = list(model_apis) if model_apis is not None else []
    #: Memory cap and OOM-kill counts, recorded in metadata.json.
    self.memory: dict[str, Any] = {}
    self.timestamp = datetime.now().isoformat()

BenchmarkRunner

BenchmarkRunner(config: Config, resolver: GroupResolver, dry_run: bool = False, stream_output: bool = True, clean_env: bool = True, harness_memory_limit_bytes: int | None = None, harness_memory_limit_fraction: float | None = 0.9, sandbox_network: bool | None = None, keep_workspace: bool = False)

Orchestrates benchmark execution on top of :class:automaton.Sandbox.

Parameters:

Name Type Description Default
config Config

Configuration object.

required
resolver GroupResolver

Task-group resolver (CLI --task-dir > TASK_PATH > installed).

required
dry_run bool

If True, print commands without executing.

False
stream_output bool

If True, mirror container output to terminal.

True
clean_env bool

If True, remove task environment after verification.

True
harness_memory_limit_bytes int

Fixed harness memory cap in bytes.

None
harness_memory_limit_fraction float

Fraction of available memory to cap harness at. Default 0.9.

0.9
sandbox_network bool

Override loopback-only sandbox networking; defaults to the config value.

None

Examples:

>>> config = Config()
>>> runner = BenchmarkRunner(config, config.group_resolver(), dry_run=True)
Source code in abc_runner/runner.py
def __init__(
    self,
    config: Config,
    resolver: GroupResolver,
    dry_run: bool = False,
    stream_output: bool = True,
    clean_env: bool = True,
    harness_memory_limit_bytes: int | None = None,
    harness_memory_limit_fraction: float | None = 0.9,
    sandbox_network: bool | None = None,
    keep_workspace: bool = False,
):
    self.config = config
    self.resolver = resolver
    self.package_root = config.package_root
    self.dry_run = dry_run
    self.stream_output = stream_output
    self.clean_env = clean_env
    self.harness_memory_limit_bytes = harness_memory_limit_bytes
    self.harness_memory_limit_fraction = harness_memory_limit_fraction
    self.sandbox_network = config.sandbox_network if sandbox_network is None else sandbox_network
    self.keep_workspace = keep_workspace

run

run(task_id: str, agent_id: str, task_group: str | None = None, timeout: int | None = None, results_dir: Path | None = None, output_dir: Path | None = None, attempt: int | None = None, attempts: int = 1) -> BenchmarkResult

Run a single benchmark and return its :class:BenchmarkResult.

When attempts > 1 the run is stored under a per-attempt subdirectory (.../<task>/attempt_NN/<timestamp>_<agent>_<task>/); attempt is the 1-based index of this attempt. A single attempt (the default) keeps the flat .../<task>/<timestamp>_<agent>_<task>/ layout unchanged. These only apply to the organized results_dir layout, not to a standalone output_dir.

Source code in abc_runner/runner.py
def run(
    self,
    task_id: str,
    agent_id: str,
    task_group: str | None = None,
    timeout: int | None = None,
    results_dir: Path | None = None,
    output_dir: Path | None = None,
    attempt: int | None = None,
    attempts: int = 1,
) -> BenchmarkResult:
    """Run a single benchmark and return its :class:`BenchmarkResult`.

    When ``attempts > 1`` the run is stored under a per-attempt subdirectory
    (``.../<task>/attempt_NN/<timestamp>_<agent>_<task>/``); ``attempt`` is
    the 1-based index of this attempt. A single attempt (the default) keeps
    the flat ``.../<task>/<timestamp>_<agent>_<task>/`` layout unchanged.
    These only apply to the organized ``results_dir`` layout, not to a
    standalone ``output_dir``.
    """
    task = Task(task_id, self.resolver, task_group=task_group)
    agent = Agent(agent_id, self.config)
    harness = Harness(agent.harness_id, self.package_root / "harnesses" / agent.harness_id)
    container_manager = ContainerManager(self.package_root, self.resolver)
    runtime_container_ref = container_manager.runtime_container_ref(agent.harness_id, task.group_id)
    runtime_container = container_manager.get_container_path(runtime_container_ref)
    agent_model_configs = [model.config for model in agent.models]
    agent_model_apis = [config.get("api") for config in agent_model_configs]

    task_errors = task.validate()
    if task_errors:
        raise ValueError("Task validation failed:\n" + "\n".join(task_errors))

    harness_errors = agent.validate()
    if harness_errors:
        raise ValueError("Agent validation failed:\n" + "\n".join(harness_errors))
    harness_errors = harness.validate()
    if harness_errors:
        raise ValueError("Harness validation failed:\n" + "\n".join(harness_errors))

    if not runtime_container.exists():
        raise FileNotFoundError(
            f"Harness runtime not found: {runtime_container}\n"
            f"Build it first with: abc-runner build-container {agent.harness_id}/{task.group_id}"
        )

    started_at = datetime.now(timezone.utc)
    result_dir, output_mode, agent_archive_dir = self._result_dir(
        task_group=task.group_id,
        task_id=task.task_id,
        agent_id=agent.agent_id,
        models=agent_model_configs,
        harness_id=agent.harness_id,
        started_at=started_at,
        results_dir=results_dir,
        output_dir=output_dir,
        attempt=attempt,
        attempts=attempts,
    )
    result_dir.mkdir(parents=True, exist_ok=False)

    print(f"Running benchmark: {task.task_ref} with {agent.agent_id}")
    print(f"Results directory: {result_dir}")
    container_paths = self._container_run_paths()
    bind_mounts = self._container_bind_mounts(result_dir)
    sandbox = self._sandbox(result_dir.parent)

    proxy_usage_summary: dict[str, Any] = {}
    memory: dict[str, Any] = {
        "cgroup": self.config.memory_cgroup,
        "limit_bytes": None,
        "build_env_oom_kills": 0,
        "harness_oom_kills": 0,
        "verification_oom_kills": 0,
    }

    try:
        workspace_dir = result_dir / "workspace"
        print(f"Copying workspace from {task.workspace_dir} to {workspace_dir}")
        shutil.copytree(
            task.workspace_dir,
            workspace_dir,
            ignore=shutil.ignore_patterns("__pycache__", "*.pyc"),
        )

        shutil.copy2(task.prompt_file, result_dir / "prompt.md")

        # Optional shared task-group prompt layer. When the group defines a
        # group_prompt.md, stage it so the harness can inject it between the
        # system prompt and the per-task prompt; otherwise drop the key so
        # the harness receives no --group-prompt and behaves as before.
        group_prompt_file = task.group_prompt_file
        if group_prompt_file is not None:
            shutil.copy2(group_prompt_file, result_dir / "group_prompt.md")
        else:
            container_paths.pop("group_prompt", None)

        staged_harness_dir = result_dir / "harness"
        shutil.copytree(
            harness.harness_dir,
            staged_harness_dir,
            ignore=shutil.ignore_patterns("__pycache__", "*.pyc"),
        )

        build_env_script = result_dir / "build_env.sh"
        shutil.copy2(task.build_env_script, build_env_script)
        build_env_script.chmod(0o755)

        sandbox_helper_script = result_dir / "sandbox_helper.py"
        sandbox_helper_script.write_text(sandbox.sandbox_helper_script())
        sandbox_helper_script.chmod(0o755)

        # 1. build_env.sh (non-isolated network, matching legacy behavior)
        print("Running build environment script...")
        try:
            sandbox.run_command(
                runtime_container,
                ["bash", str(container_paths["build_env"])],
                cwd=container_paths["workspace"],
                log_file=result_dir / "build_env.log",
                env_vars={
                    "ABC_RUNNER_WORKSPACE": str(container_paths["workspace"]),
                    "ABC_RUNNER_TASK_ENV": str(container_paths["task_env"]),
                },
                bind_mounts=bind_mounts,
                memory_limit_bytes=self._command_memory_limit(sandbox),
                network=True,
            )
            memory["build_env_oom_kills"] = sandbox.last_oom_kills
        except MemoryCgroupUnavailable:
            raise
        except Exception as e:
            result = BenchmarkResult(
                task_id=task.task_id,
                task_group=task.group_id,
                task_ref=task.task_ref,
                agent_id=agent.agent_id,
                harness_id=agent.harness_id,
                model_names=agent.model_names,
                status="HARNESS_ERROR",
                result_dir=result_dir,
                error=str(e),
                failure_phase="memory_limit" if sandbox.last_oom_kills else "build_env",
                model_apis=agent_model_apis,
            )
            memory["build_env_oom_kills"] = sandbox.last_oom_kills
            result.memory = memory
            ended_at = datetime.now(timezone.utc)
            self._finalize(result, task, agent, agent_model_configs, result_dir,
                           output_mode, agent_archive_dir, timeout, started_at, ended_at)
            return result

        # 2. Run the agent (deliverable left in workspace)
        print("Running harness...")
        harness_output_dir = result_dir / "harness_output"
        harness_output_dir.mkdir(exist_ok=True)
        models_config_file = result_dir / "models_config.yaml"
        harness_config_file = result_dir / "harness_config.yaml"
        proxy_log = harness_output_dir / "model_proxy.log"
        usage_records_file = harness_output_dir / "usage.jsonl"

        execution = sandbox.run_agent(
            runtime_container,
            harness,
            agent,
            workspace=container_paths["workspace"],
            run_dir=result_dir,
            container_paths=container_paths,
            bind_mounts=bind_mounts,
            proxy_log=proxy_log,
            usage_records_file=usage_records_file,
            harness_output_dir=harness_output_dir,
            models_config_file=models_config_file,
            harness_config_file=harness_config_file,
            extra_env={
                "ABC_RUNNER_WORKSPACE": str(container_paths["workspace"]),
                "ABC_RUNNER_TASK_ENV": str(container_paths["task_env"]),
            },
            timeout=timeout,
            sandboxed=self.sandbox_network,
        )
        proxy_usage_summary = execution.usage_summary
        memory["limit_bytes"] = getattr(execution, "memory_limit_bytes", None)
        memory["harness_oom_kills"] = getattr(execution, "oom_kills", 0)

        if execution.dry_run:
            result = BenchmarkResult(
                task_id=task.task_id, task_group=task.group_id, task_ref=task.task_ref,
                agent_id=agent.agent_id, harness_id=agent.harness_id,
                model_names=agent.model_names, status="DRY-RUN",
                result_dir=result_dir, model_apis=agent_model_apis,
            )
            ended_at = datetime.now(timezone.utc)
            self._finalize(result, task, agent, agent_model_configs, result_dir,
                           output_mode, agent_archive_dir, timeout, started_at, ended_at,
                           usage_summary=proxy_usage_summary)
            return result

        if not execution.success:
            status, failure_phase = self._classify_harness_failure(execution)
            print(f"Harness failed; recording benchmark result as {status}: {execution.failure_detail}")
            result = BenchmarkResult(
                task_id=task.task_id, task_group=task.group_id, task_ref=task.task_ref,
                agent_id=agent.agent_id, harness_id=agent.harness_id,
                model_names=agent.model_names, status=status,
                result_dir=result_dir, error=execution.failure_detail,
                failure_phase=failure_phase, model_apis=agent_model_apis,
            )
        elif getattr(execution, "blocked_provider_executed_tools", None):
            # The harness exited cleanly, but the proxy refused a
            # provider-executed tool along the way (an agent can retry
            # without the tool and still exit 0). Do not grade this: a
            # containment failure must not be able to produce a PASS.
            blocked = ", ".join(execution.blocked_provider_executed_tools)
            detail = (
                f"Model proxy blocked provider-executed tool(s): {blocked}. "
                "Refusing to grade this run; fix the harness configuration or "
                "allow the tool explicitly."
            )
            print(f"Harness succeeded but {detail}")
            result = BenchmarkResult(
                task_id=task.task_id, task_group=task.group_id, task_ref=task.task_ref,
                agent_id=agent.agent_id, harness_id=agent.harness_id,
                model_names=agent.model_names, status="HARNESS_ERROR",
                result_dir=result_dir, error=detail,
                failure_phase="provider_executed_tool_blocked",
                model_apis=agent_model_apis,
            )
        else:
            # 3. Stage + run verification against the deliverable
            print("Injecting verification...")
            verification_dir = result_dir / "verification"
            if verification_dir.exists():
                shutil.rmtree(verification_dir)
            shutil.copytree(
                task.verification_dir,
                verification_dir,
                ignore=shutil.ignore_patterns("__pycache__", "*.pyc"),
            )

            print("Running verification...")
            verify_log = result_dir / "verify.log"
            verify_result = self._run_verification(
                sandbox=sandbox,
                container_path=runtime_container,
                workspace=container_paths["workspace"],
                verification_dir=container_paths["verification"],
                log_file=verify_log,
                bind_mounts=bind_mounts,
            )
            verify_oom_kills = sandbox.last_oom_kills
            memory["verification_oom_kills"] = verify_oom_kills

            if self.clean_env:
                self._clean_task_env(workspace_dir)

            if verify_result == "FAIL" and verify_oom_kills:
                # The verifier ran out of memory, so its FAIL says nothing
                # about the deliverable. Inconclusive, not a task failure.
                result = BenchmarkResult(
                    task_id=task.task_id, task_group=task.group_id, task_ref=task.task_ref,
                    agent_id=agent.agent_id, harness_id=agent.harness_id,
                    model_names=agent.model_names, status="HARNESS_ERROR",
                    result_dir=result_dir, verify_log="verify.log",
                    error=(
                        f"Verification exceeded the memory cap: the kernel OOM-killed "
                        f"{verify_oom_kills} process(es). See verify.log."
                    ),
                    failure_phase="memory_limit",
                    model_apis=agent_model_apis,
                )
            else:
                result = BenchmarkResult(
                    task_id=task.task_id, task_group=task.group_id, task_ref=task.task_ref,
                    agent_id=agent.agent_id, harness_id=agent.harness_id,
                    model_names=agent.model_names, status=verify_result,
                    result_dir=result_dir, verify_log="verify.log",
                    failure_phase=None if verify_result == "PASS" else "verification",
                    model_apis=agent_model_apis,
                )

    except (result_format.WorkspaceDeltaError, MemoryCgroupUnavailable):
        raise
    except Exception as e:
        print(f"Error during benchmark run: {e}")
        result = BenchmarkResult(
            task_id=task.task_id, task_group=task.group_id, task_ref=task.task_ref,
            agent_id=agent.agent_id, harness_id=agent.harness_id,
            model_names=agent.model_names, status="ERROR",
            result_dir=result_dir, error=str(e), model_apis=agent_model_apis,
        )

    result.memory = memory
    ended_at = datetime.now(timezone.utc)
    self._finalize(result, task, agent, agent_model_configs, result_dir,
                   output_mode, agent_archive_dir, timeout, started_at, ended_at,
                   usage_summary=proxy_usage_summary)
    return result

attempt_is_complete

attempt_is_complete(attempt_dir: Path) -> bool

Return True iff attempt_dir holds a conclusive, finished benchmark.

A complete attempt has a readable metadata.json whose complete flag is true (equivalently, a conclusive status). Missing, unreadable, or inconclusive results are treated as incomplete so a resume re-runs them.

Source code in abc_runner/runner.py
def attempt_is_complete(attempt_dir: Path) -> bool:
    """Return True iff ``attempt_dir`` holds a conclusive, finished benchmark.

    A complete attempt has a readable ``metadata.json`` whose ``complete`` flag
    is true (equivalently, a conclusive ``status``). Missing, unreadable, or
    inconclusive results are treated as incomplete so a resume re-runs them.
    """
    metadata_path = attempt_dir / "metadata.json"
    try:
        with open(metadata_path) as handle:
            metadata = json.load(handle)
    except (OSError, ValueError):
        return False
    if not isinstance(metadata, dict):
        return False
    if "complete" in metadata:
        return bool(metadata["complete"])
    # Backward compatibility with results written before the ``complete`` flag.
    return str(metadata.get("status", "")) in CONCLUSIVE_STATUSES