Skip to content

Reward-mode container verifier scores a reward.txt the agent planted, even when test.sh exits non-zero #305

Closed

Description

@jimmy-holdout

What happened?

When reward_path is set, RunContainerUnitTestsVerifierTaskStep reads the reward file from the task container after the verifier command runs, and records that number as the score. It never clears the file first, and in reward mode it ignores the exit code. So if the agent writes 1 to the reward path during its turn (for example echo 1 > /logs/verifier/reward.txt), and the task's test.sh then fails without writing the file, the planted 1 is recorded as score=1.0, result=True. The verifier exited 1 and the step does not raise.

Details (at 35b6ae1, file src/agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py):

  • The verifier runs in the task container named by container_name; an agent working in that container can leave files there (docker exec ... bash -c <command>). Nothing removes reward_path or the other result_paths before this command.
  • After the command, every result path is docker cp'd out, whoever wrote it.
  • In reward mode the score is the parsed file content. passed_surrogate (exit code 0 and no timeout) is only used when reward_path is None.
  • The step raises on a non-zero exit only when reward_path is None. The comment there says "In reward mode a non-zero exit is a graded failure (already recorded as score 0)", but nothing sets the score to 0 when the exit code is non-zero. That only happens if the file is missing.

This needs a test.sh that can exit without writing the reward file. Two script shapes can do that: a fail-fast script (set -e, then the tests, then echo 1 > reward.txt), and a pass-only write (pytest && echo 1 > reward.txt, relying on "missing file = 0"). A test.sh that always writes 0 or 1 overwrites the planted file, so it is not affected. No task in this repo sets reward_path (only unit tests do), so this is about user-supplied Harbor-style tasks.

Reproduce: save the script below as repro.py next to the repo and run it with the repo's venv (repo/.venv/bin/python repro.py; uv run python repro.py from the repo root works too). It calls the real RunContainerUnitTestsVerifierTaskStep.execute() with reward_path="/logs/verifier/reward.txt". Only the sandbox is replaced: the task container's filesystem is a temp directory, and the exact command string the step builds for docker exec is run with real bash (container paths are prefixed with $ROOT). docker cp becomes a file copy. Docker, network and LLM calls are not used. grep -qx 42 answer.txt stands in for pytest. It grades three agent turns against three test.sh shapes: correct answer, wrong answer, and wrong answer plus a planted reward.txt.

repro.py
"""RunContainerUnitTestsVerifierTaskStep in reward mode scores a reward file that was
already in the container before the verifier ran, even when the verifier exits non-zero.

Drives the real RunContainerUnitTestsVerifierTaskStep.execute(). Only the sandbox is
replaced: the task container's filesystem is a temp directory, and the command string the
step builds is run with real bash (paths are prefixed with $ROOT). No Docker, no network,
no LLM. `grep -qx 42 answer.txt` stands in for pytest.

Usage (from the repo root):  uv run python repro.py
"""
from __future__ import annotations

import asyncio
import os
import shlex
import shutil
import subprocess
import tempfile
import types
from pathlib import Path

STATE = Path(tempfile.mkdtemp(prefix="repro-state-"))
os.chdir(STATE)
os.environ["AGENT_ENV_OBJECT_STORE"] = "local"
os.environ["AGENT_ENV_DOCUMENT_STORE"] = "local"
for k in ("LITELLM_API_KEY", "LITELLM_BASE_URL"):
    os.environ.pop(k, None)

from agent_env.config import configure  # noqa: E402
from agent_env.providers.sandbox_providers import sandbox_provider  # noqa: E402
from agent_env.task_step.context import DeployedSandbox, TaskStepContext  # noqa: E402
from agent_env.task_step.task_steps.verifiers.run_container_unit_tests_verifier import (  # noqa: E402
    RunContainerUnitTestsVerifierTaskStep as Step,
)

configure()

REWARD = "/logs/verifier/reward.txt"

TEST_SH = {
    # fail-fast script: writes the reward only after the tests pass
    "set -e": 'set -e\ngrep -qx 42 "$ROOT/app/answer.txt"\necho 1 > "$ROOT/logs/verifier/reward.txt"\n',
    # writes the reward only on success, relying on "missing reward file = 0"
    "pass-only write": 'grep -qx 42 "$ROOT/app/answer.txt" && echo 1 > "$ROOT/logs/verifier/reward.txt"\n',
    # always writes 0 or 1 (control: the planted file is overwritten)
    "if/else always writes": 'if grep -qx 42 "$ROOT/app/answer.txt"; then echo 1 > "$ROOT/logs/verifier/reward.txt"; '
                             'else echo 0 > "$ROOT/logs/verifier/reward.txt"; fi\n',
}


class FakeSandbox:
    """A VM with one task container, backed by two temp dirs."""

    type = "local"

    def __init__(self, root: Path, vm: Path):
        self.root, self.vm = root, vm

    def scoped_name(self, name):
        return name

    def _vm(self, p):
        return self.vm / p.lstrip("/")

    async def exec_script(self, script, *, max_retries=0):
        parts = shlex.split(script)
        if parts[:2] == ["rm", "-f"]:
            self._vm(parts[2]).unlink(missing_ok=True)
        return ""

    async def exec_with_output(self, *args):
        if args[:2] == ("sudo", "cat"):
            p = self._vm(args[2])
            return (0, p.read_text(), "") if p.exists() else (1, "", "No such file")
        # ("sudo", "bash", "-c", "docker exec ... timeout ... bash -c <command>")
        inner = shlex.split(args[3])[-1]  # the command string the step built
        p = subprocess.run(["bash", "-c", inner], env={**os.environ, "ROOT": str(self.root)},
                           capture_output=True, text=True)
        return p.returncode, p.stdout, p.stderr

    async def docker_cp(self, source, destination, *, remove_source=False):
        src = self.root / source.split(":", 1)[1].lstrip("/")
        if not src.exists():
            raise RuntimeError(f"docker cp: no such file {source}")
        dst = self._vm(destination)
        dst.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(src, dst)


def run_case(variant: str, answer: str, plant: bool) -> dict:
    base = Path(tempfile.mkdtemp(prefix="repro-"))
    root, vm = base / "container", base / "vm"
    for d in ("tests", "app", "logs/verifier"):
        (root / d).mkdir(parents=True)
    vm.mkdir()
    (root / "tests/test.sh").write_text(TEST_SH[variant])
    # The agent's turn: it writes its answer and, in the exploit case, a reward file.
    (root / "app/answer.txt").write_text(answer + "\n")
    if plant:
        (root / "logs/verifier/reward.txt").write_text("1\n")

    sandbox = FakeSandbox(root, vm)
    sandbox_provider.build_sandbox_provider = lambda _t: types.SimpleNamespace(
        get_sandbox=lambda _id: asyncio.sleep(0, result=sandbox))
    ctx = TaskStepContext(deployed_sandboxes=[DeployedSandbox(
        sandbox_name="h", sandbox_id="local-x", sandbox_mode="vm", sandbox_type="local", tunnel_urls={})])
    ctx.metadata["deployed_docker_containers"] = [{"container_name": "task", "sandbox_name": "h"}]
    step = Step(id="verify", version=None, sandbox_name="h", container_name="task",
                command='bash "$ROOT/tests/test.sh"', reward_path=REWARD)
    # Skip the stdout/stderr artifact upload; it does not affect scoring.
    Step._upload_text_artifact = staticmethod(lambda text, artifact_id, description, object_url:
                                              types.SimpleNamespace(id=artifact_id, version=1, object_url=object_url))
    raised = None
    try:
        asyncio.run(step.execute(ctx))
    except Exception as e:
        raised = f"{type(e).__name__}: {e}"
    v = ctx.metadata["verifications"]["verify"]
    return {"score": v["score"], "result": v["results"][0]["result"], "exit_code": v["exit_code"],
            "raised": raised}


def main():
    cases = [
        ("correct answer (42)", "42", False),
        ("wrong answer (41)", "41", False),
        ("wrong answer (41) + planted reward.txt=1", "41", True),
    ]
    for variant in TEST_SH:
        print(f"\n=== test.sh: {variant} ===")
        for label, answer, plant in cases:
            r = run_case(variant, answer, plant)
            print(f"  {label:42s} -> score={r['score']} result={r['result']} "
                  f"exit_code={r['exit_code']} raised={r['raised']}")


if __name__ == "__main__":
    main()

Expected: a wrong answer scores 0, whatever the agent left in /logs/verifier/. The comment at L387-L389 says a non-zero exit in reward mode is recorded as score 0.

Actual: with the set -e and pass-only test.sh, the wrong answer plus a planted reward.txt scores 1.0 / result=True with exit_code=1, the same as the correct answer. The honest wrong answer scores 0.0. The always-writes test.sh is not affected. The full output is below. The LITELLM_* warnings come from the step's logger and are expected, because no model endpoint is configured. The two "failed to extract" lines are the honest wrong-answer cases, where no reward file exists.

Impact: When a task sets reward_path, the agent can write that path, and test.sh can fail without overwriting it, a planted 1 is recorded as a passing score. This can inflate downstream reward or pass metrics that use this verification entry. No shipped task in this repo sets reward_path.

Possible fix:

  • Before running the verifier command, remove the prior reward_path file from the task container (rm -f -- <path>). This prevents a preexisting file from being scored.
  • In reward mode, record score 0 when exit_code != 0, as the comment at L387-L389 already says. If some verifiers intentionally exit non-zero with a valid reward, define that behavior separately.
  • More robust: have the verifier write the reward to a directory the agent can't write, e.g. one mounted only for the verifier run.

Happy to help test a fix. Found while auditing public RL environments.

Environment: commit 35b6ae1ac977ecedc33f6912d1deb34e80e4d484, Python 3.11.17 (from uv sync --frozen), Ubuntu 24.04 LTS (Linux 6.8), run with the network disabled (unshare -n).

Output and errors

LITELLM_API_KEY unavailable; verifier won't have LLM creds
LITELLM_BASE_URL unavailable; verifier won't have LLM base URL
LITELLM_API_KEY unavailable; verifier won't have LLM creds
LITELLM_BASE_URL unavailable; verifier won't have LLM base URL
[verify] failed to extract /logs/verifier/reward.txt: docker cp: no such file task:/logs/verifier/reward.txt
LITELLM_API_KEY unavailable; verifier won't have LLM creds
LITELLM_BASE_URL unavailable; verifier won't have LLM base URL
LITELLM_API_KEY unavailable; verifier won't have LLM creds
LITELLM_BASE_URL unavailable; verifier won't have LLM base URL
LITELLM_API_KEY unavailable; verifier won't have LLM creds
LITELLM_BASE_URL unavailable; verifier won't have LLM base URL
[verify] failed to extract /logs/verifier/reward.txt: docker cp: no such file task:/logs/verifier/reward.txt
LITELLM_API_KEY unavailable; verifier won't have LLM creds
LITELLM_BASE_URL unavailable; verifier won't have LLM base URL
LITELLM_API_KEY unavailable; verifier won't have LLM creds
LITELLM_BASE_URL unavailable; verifier won't have LLM base URL
LITELLM_API_KEY unavailable; verifier won't have LLM creds
LITELLM_BASE_URL unavailable; verifier won't have LLM base URL
LITELLM_API_KEY unavailable; verifier won't have LLM creds
LITELLM_BASE_URL unavailable; verifier won't have LLM base URL

=== test.sh: set -e ===
  correct answer (42)                        -> score=1.0 result=True exit_code=0 raised=None
  wrong answer (41)                          -> score=0.0 result=False exit_code=1 raised=None
  wrong answer (41) + planted reward.txt=1   -> score=1.0 result=True exit_code=1 raised=None

=== test.sh: pass-only write ===
  correct answer (42)                        -> score=1.0 result=True exit_code=0 raised=None
  wrong answer (41)                          -> score=0.0 result=False exit_code=1 raised=None
  wrong answer (41) + planted reward.txt=1   -> score=1.0 result=True exit_code=1 raised=None

=== test.sh: if/else always writes ===
  correct answer (42)                        -> score=1.0 result=True exit_code=0 raised=None
  wrong answer (41)                          -> score=0.0 result=False exit_code=0 raised=None
  wrong answer (41) + planted reward.txt=1   -> score=0.0 result=False exit_code=0 raised=None

Screenshots

No response

Output of agent-env plugin list

agent-env 0.9.1346 · uv project
config: (none)

PACKAGE             VERSION   PROVIDES                                      STATUS
agentenv-framework  0.9.1346  bundle agents, bundle echo-mcp, bundle hello  ok

Operating system

Linux (x86_64)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions