diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 34c04ced..1441ac13 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -222,6 +222,7 @@ jobs: uv run --all-extras --frozen pytest -q tests/test_separate_verifier_container.py tests/test_separate_verifier_harbor.py + tests/test_validate_fresh_stages_container.py egress-controls: name: Go/Rust solve-time egress controls runs-on: ubuntu-latest diff --git a/docs/pipelines/pr_runtime.md b/docs/pipelines/pr_runtime.md index 22881bb0..68fdcf6e 100644 --- a/docs/pipelines/pr_runtime.md +++ b/docs/pipelines/pr_runtime.md @@ -124,6 +124,21 @@ replace the validation container. This does **not** provide a new dependency ima or container for every PR. Revision-aware dependencies and stronger per-candidate isolation remain tracked in [#253](https://github.com/huggingface/Repo2RLEnv/issues/253). +### Fresh validation stages + +Use `--pipeline-opt fresh_validation_stages=true` to snapshot the prepared +validation container once per candidate and run pre-fix, post-fix, stability +reruns and mutant checks in separate containers. Stage-written files and running +processes do not carry into the next stage. Containers and the temporary snapshot +are removed when validation finishes, including on early rejection or failure; +cleanup failures are logged without hiding the original error. + +The default remains `false`. This adds snapshot/startup overhead and inherits the +prepared container's installed dependencies. It does not reinstall them at the +historical base revision, change validation networking, or isolate an existing +mounted volume (Docker snapshots exclude volume contents). Use images whose source +and dependencies live in the container filesystem. Published tasks are unchanged. + ## Options Pass each option with `--pipeline-opt key=value`. @@ -136,6 +151,7 @@ Pass each option with `--pipeline-opt key=value`. | `require_fail_to_pass` | `true` | Skip PRs with fewer than `min_fail_to_pass` F2P tests after validation | | `min_fail_to_pass` | `1` | Minimum number of F2P tests | | `validation_timeout_sec` | `600` | Whole-stage deadline; the test launcher reserves part of it for setup and cleanup | +| `fresh_validation_stages` | `false` | Run each validation stage in a new container from one prepared snapshot per candidate | | `skip_validation` | `false` | Emit candidates without running tests. Tasks then have no F2P/P2P lists, a pass/fail exit-code reward and, with nothing measured, a 300 s per-run limit. For debugging | | `require_new_test_funcs` | `true` | Require the test patch to add at least one test function or class | | `skip_ci_only` | `true` | Skip PRs whose source changes are all under `.github/` | diff --git a/src/repo2rlenv/bootstrap/docker.py b/src/repo2rlenv/bootstrap/docker.py index 397df659..9efbf3b0 100644 --- a/src/repo2rlenv/bootstrap/docker.py +++ b/src/repo2rlenv/bootstrap/docker.py @@ -358,11 +358,16 @@ def push(self, tag: str, *, timeout: int = 900) -> bool: return False return True - def cleanup(self) -> None: + def cleanup(self, *, strict: bool = False) -> None: + """Remove the container; strict callers require confirmed removal.""" if not self._alive: return # `rm -f` stops + removes in one go - _run(["docker", "rm", "-f", self.container_id], timeout=30) + result = _run(["docker", "rm", "-f", self.container_id], timeout=30) + if strict and not result.ok: + raise DockerError( + f"could not remove {self.container_id}: {result.stderr.strip()[:400]}" + ) self._alive = False def __enter__(self) -> DockerSandbox: diff --git a/src/repo2rlenv/pipelines/pr_runtime.py b/src/repo2rlenv/pipelines/pr_runtime.py index 12762bbd..a6f43053 100644 --- a/src/repo2rlenv/pipelines/pr_runtime.py +++ b/src/repo2rlenv/pipelines/pr_runtime.py @@ -1426,6 +1426,7 @@ def run(self, out_dir: Path) -> PipelineResult: test_cmds=targeted_cmds, language=self.bootstrap.language.value, timeout=self.options.validation_timeout_sec, + fresh_stages=self.options.fresh_validation_stages, ) fail_to_pass = outcome.fail_to_pass pass_to_pass = outcome.pass_to_pass diff --git a/src/repo2rlenv/pipelines/pr_runtime_validate.py b/src/repo2rlenv/pipelines/pr_runtime_validate.py index 4b321fef..6136e827 100644 --- a/src/repo2rlenv/pipelines/pr_runtime_validate.py +++ b/src/repo2rlenv/pipelines/pr_runtime_validate.py @@ -34,11 +34,14 @@ import logging import re import shlex +import subprocess +import tempfile import time +import uuid from dataclasses import dataclass, field from pathlib import Path -from repo2rlenv.bootstrap.docker import DockerSandbox +from repo2rlenv.bootstrap.docker import DockerError, DockerSandbox from repo2rlenv.log_parsers import parse_logs from repo2rlenv.pipelines._eval_script import upload from repo2rlenv.pipelines._grading_time import GradingTime, fit_runs, measure @@ -143,6 +146,68 @@ def run(self, sandbox: DockerSandbox, script: str, timeout: int): return result +class _StageHost: + """Where validation stages run. + + Shared mode runs every stage in the candidate's sandbox, as before. Fresh mode + snapshots the sandbox once it is prepared (git, Python, base commit fetched) + and runs each stage in a new container from that snapshot, so nothing a stage + leaves behind (processes, files, caches) reaches the next one. + """ + + def __init__(self, sandbox: DockerSandbox, *, fresh: bool) -> None: + self.sandbox = sandbox + self.fresh = fresh + self.image: str | None = None + self.current: DockerSandbox | None = None + + def stage(self) -> DockerSandbox: + """The sandbox the next stage runs in.""" + if not self.fresh: + return self.sandbox + if self.image is None: + self.image = f"r2e-validate/{uuid.uuid4().hex[:12]}:stage" + self.sandbox.commit(self.image, message="repo2rlenv validation snapshot") + self._release() + with tempfile.TemporaryDirectory(prefix="r2e-stage-") as directory: + marker = Path(directory) + (marker / ".keep").write_text("") + self.current = DockerSandbox.start(self.image, marker, platform=self.sandbox.platform) + return self.current + + def reader(self) -> DockerSandbox: + """The latest stage's sandbox, whose /workspace holds that stage's tree.""" + return self.current or self.sandbox + + def _release(self) -> None: + if self.current is not None: + # cleanup uses `docker rm -f`, which already sends SIGKILL. + self.current.cleanup(strict=True) + self.current = None + + def close(self) -> None: + # Do not hide a candidate error or skip image removal if the daemon fails. + try: + self._release() + except (OSError, subprocess.SubprocessError, DockerError) as exc: + logger.warning("Could not remove validation stage container: %s", exc) + if self.image is not None: + try: + result = subprocess.run( + ["docker", "image", "rm", "-f", self.image], + capture_output=True, + timeout=60, + check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + logger.warning("Could not remove validation snapshot %s: %s", self.image, exc) + else: + if result.returncode: + logger.warning("Could not remove validation snapshot %s", self.image) + else: + self.image = None + + def _status(found: re.Match | None) -> str: return (found.group(1) or "grader error") if found else "not run" @@ -445,11 +510,13 @@ def validate_pr( test_cmds: list[str], language: str | None = None, timeout: int = 600, + fresh_stages: bool = False, ) -> ValidationOutcome: """Run the two-stage validation and return the resulting outcome. Re-uses a shared sandbox across PRs; the `git reset --hard` at the top of - each stage script guarantees a clean working tree. + each stage script guarantees a clean working tree. With `fresh_stages`, each + stage instead runs in a new container from a snapshot of the prepared sandbox. `language` is the LanguageHint value (e.g. "python", "go") used as a fallback when test_cmds doesn't name a known runner. Almost always the @@ -474,207 +541,219 @@ def validate_pr( status="failed", reason="no system python3 for the grader launcher in the bootstrap image", ) - clock = _Stopwatch() - - def read_base(path: str) -> str | None: - shown = sandbox.exec( - f"git -C /workspace show {base_commit}:{shlex.quote(path)} 2>/dev/null", timeout=30 - ) - return shown.stdout if shown.ok else None - - # npm/yarn scripts and jest/mocha/vitest settings resolved against base, once. - test_cmds = freeze_node_commands(test_cmds, read_base) - - # Stage 1: pre-fix (apply test_patch only) — captures the "buggy" baseline. - pre_script = _build_stage_script( - base_commit, - apply_patch=None, - apply_test_patch=test_patch, - test_cmds=test_cmds, - language=language, - staged=_stage(sandbox, test_patch=test_patch), - keep_collecting=True, - test_timeout=_test_timeout(timeout), - ) - logger.info("validate_pr: running pre-fix stage at %s", base_commit[:12]) - pre = clock.run(sandbox, pre_script, timeout) - # Parse the FULL output — a real suite emits 100k+ chars of per-test lines; - # truncating to 20k elided the test section and zeroed F2P detection. - pre_log = pre.truncated(max_chars=5_000_000) - pre_status = parse_logs(test_cmds, _slice_test_output(pre_log), language=language) - - if _UNSAFE_IMAGE in pre_log: - return ValidationOutcome( - test_cmds=test_cmds, - status="failed", - reason="unsafe image: a path root runs code from is writable by the test user", - pre_log=pre_log, - ) - rebuilt = _REBUILD_RE.search(pre_log) - if not rebuilt or rebuilt.group(1) != "ok": - return ValidationOutcome( - test_cmds=test_cmds, - status="failed", - reason=f"base tree does not survive the submission rebuild ({_status(rebuilt)})", - pre_log=pre_log, - ) - - # If the test_patch itself failed to apply, no point continuing. - if "error: patch failed" in pre_log.lower() or "patch does not apply" in pre_log.lower(): - return ValidationOutcome( - test_cmds=test_cmds, - status="failed", - reason="test_patch failed to apply at base_commit", - pre_log=pre_log, - ) - - # Stage 2: post-fix (apply both patch and test_patch). - post_script = _build_stage_script( - base_commit, - apply_patch=patch, - apply_test_patch=test_patch, - test_cmds=test_cmds, - language=language, - staged=_stage(sandbox, patch=patch, test_patch=test_patch), - test_timeout=_test_timeout(timeout), - ) - logger.info("validate_pr: running post-fix stage") - post = clock.run(sandbox, post_script, timeout) - post_log = post.truncated(max_chars=5_000_000) - post_status = parse_logs(test_cmds, _slice_test_output(post_log), language=language) - - rebuilt = _REBUILD_RE.search(post_log) - if rebuilt and rebuilt.group(1) != "ok": - # The grader would drop part of the fix, or refuse it: the oracle - # could never score 1 (e.g. it edits a path the grader treats as a test). - return ValidationOutcome( + host = _StageHost(sandbox, fresh=fresh_stages) + try: + clock = _Stopwatch() + + def read_base(path: str) -> str | None: + shown = sandbox.exec( + f"git -C /workspace show {base_commit}:{shlex.quote(path)} 2>/dev/null", timeout=30 + ) + return shown.stdout if shown.ok else None + + # npm/yarn scripts and jest/mocha/vitest settings resolved against base, once. + test_cmds = freeze_node_commands(test_cmds, read_base) + + # Stage 1: pre-fix (apply test_patch only) — captures the "buggy" baseline. + stage = host.stage() + pre_script = _build_stage_script( + base_commit, + apply_patch=None, + apply_test_patch=test_patch, test_cmds=test_cmds, - status="failed", - reason=f"gold patch does not survive the submission rebuild ({_status(rebuilt)})", - pre_log=pre_log, - post_log=post_log, + language=language, + staged=_stage(stage, test_patch=test_patch), + keep_collecting=True, + test_timeout=_test_timeout(timeout), ) - if "error: patch failed" in post_log.lower() or "patch does not apply" in post_log.lower(): - return ValidationOutcome( + logger.info("validate_pr: running pre-fix stage at %s", base_commit[:12]) + pre = clock.run(stage, pre_script, timeout) + # Parse the FULL output — a real suite emits 100k+ chars of per-test lines; + # truncating to 20k elided the test section and zeroed F2P detection. + pre_log = pre.truncated(max_chars=5_000_000) + pre_status = parse_logs(test_cmds, _slice_test_output(pre_log), language=language) + + if _UNSAFE_IMAGE in pre_log: + return ValidationOutcome( + test_cmds=test_cmds, + status="failed", + reason="unsafe image: a path root runs code from is writable by the test user", + pre_log=pre_log, + ) + rebuilt = _REBUILD_RE.search(pre_log) + if not rebuilt or rebuilt.group(1) != "ok": + return ValidationOutcome( + test_cmds=test_cmds, + status="failed", + reason=f"base tree does not survive the submission rebuild ({_status(rebuilt)})", + pre_log=pre_log, + ) + + # If the test_patch itself failed to apply, no point continuing. + if "error: patch failed" in pre_log.lower() or "patch does not apply" in pre_log.lower(): + return ValidationOutcome( + test_cmds=test_cmds, + status="failed", + reason="test_patch failed to apply at base_commit", + pre_log=pre_log, + ) + + # Stage 2: post-fix (apply both patch and test_patch). + stage = host.stage() + post_script = _build_stage_script( + base_commit, + apply_patch=patch, + apply_test_patch=test_patch, test_cmds=test_cmds, - status="failed", - reason="gold patch failed to apply at base_commit", - pre_log=pre_log, - post_log=post_log, + language=language, + staged=_stage(stage, patch=patch, test_patch=test_patch), + test_timeout=_test_timeout(timeout), ) - - # Repeat the post-fix stage; a test is tracked only if every run agrees. - reruns = [] - for attempt in range(2, POST_FIX_RUNS + 1): - logger.info("validate_pr: post-fix rerun %d/%d", attempt, POST_FIX_RUNS) - rerun = clock.run(sandbox, post_script, timeout).truncated(max_chars=5_000_000) - reruns.append(parse_logs(test_cmds, _slice_test_output(rerun), language=language)) - flaky = flaky_tests([post_status, *reruns]) - if flaky: - logger.info("validate_pr: dropping %d flaky test(s)", len(flaky)) - - # Compute F2P / P2P. Both sets are over the union of test names seen. - # - # F2P counts ERROR->PASSED as well as FAILED->PASSED: a new test that - # references a symbol the fix introduces *errors* (import/collection - # failure) at base_commit rather than asserting-failing. Restricting F2P - # to FAILED-only silently drops these, killing otherwise-valid candidates - # on `no_fail_to_pass`. Both transitions mean "broken at base, fixed by - # the gold patch" — the FAIL_TO_PASS contract. - fail_to_pass: list[str] = [] - pass_to_pass: list[str] = [] - for tname, pre_st in pre_status.items(): - if tname in flaky: - continue - post_st = post_status.get(tname) - if pre_st in ("FAILED", "ERROR") and post_st == "PASSED": - fail_to_pass.append(tname) - elif pre_st == "PASSED" and post_st == "PASSED": - pass_to_pass.append(tname) - # A test module that can't be imported at base, typically because it - # imports what the fix adds, has no test IDs there: pytest reports one - # file-level ERROR. Go JSON likewise reports a package-level ERROR only - # with explicit build-failure evidence; its tests use package::test IDs. - # In either case, only tests from that exact unit can be inferred. - uncollected = {name for name, st in pre_status.items() if st == "ERROR" and "::" not in name} - promoted: dict[str, int] = {} - for tname, post_st in post_status.items(): - if tname in pre_status or tname in flaky or post_st != "PASSED": - continue - module = tname.split("::", 1)[0] - if module in uncollected: - fail_to_pass.append(tname) - promoted[module] = promoted.get(module, 0) + 1 - if promoted: + logger.info("validate_pr: running post-fix stage") + post = clock.run(stage, post_script, timeout) + post_log = post.truncated(max_chars=5_000_000) + post_status = parse_logs(test_cmds, _slice_test_output(post_log), language=language) + + rebuilt = _REBUILD_RE.search(post_log) + if rebuilt and rebuilt.group(1) != "ok": + # The grader would drop part of the fix, or refuse it: the oracle + # could never score 1 (e.g. it edits a path the grader treats as a test). + return ValidationOutcome( + test_cmds=test_cmds, + status="failed", + reason=f"gold patch does not survive the submission rebuild ({_status(rebuilt)})", + pre_log=pre_log, + post_log=post_log, + ) + if "error: patch failed" in post_log.lower() or "patch does not apply" in post_log.lower(): + return ValidationOutcome( + test_cmds=test_cmds, + status="failed", + reason="gold patch failed to apply at base_commit", + pre_log=pre_log, + post_log=post_log, + ) + + # Repeat the post-fix stage; a test is tracked only if every run agrees. + reruns = [] + for attempt in range(2, POST_FIX_RUNS + 1): + logger.info("validate_pr: post-fix rerun %d/%d", attempt, POST_FIX_RUNS) + stage = host.stage() + if host.fresh: + _stage(stage, patch=patch, test_patch=test_patch) + rerun = clock.run(stage, post_script, timeout).truncated(max_chars=5_000_000) + reruns.append(parse_logs(test_cmds, _slice_test_output(rerun), language=language)) + flaky = flaky_tests([post_status, *reruns]) + if flaky: + logger.info("validate_pr: dropping %d flaky test(s)", len(flaky)) + + # Compute F2P / P2P. Both sets are over the union of test names seen. + # + # F2P counts ERROR->PASSED as well as FAILED->PASSED: a new test that + # references a symbol the fix introduces *errors* (import/collection + # failure) at base_commit rather than asserting-failing. Restricting F2P + # to FAILED-only silently drops these, killing otherwise-valid candidates + # on `no_fail_to_pass`. Both transitions mean "broken at base, fixed by + # the gold patch" — the FAIL_TO_PASS contract. + fail_to_pass: list[str] = [] + pass_to_pass: list[str] = [] + for tname, pre_st in pre_status.items(): + if tname in flaky: + continue + post_st = post_status.get(tname) + if pre_st in ("FAILED", "ERROR") and post_st == "PASSED": + fail_to_pass.append(tname) + elif pre_st == "PASSED" and post_st == "PASSED": + pass_to_pass.append(tname) + # A test module that can't be imported at base, typically because it + # imports what the fix adds, has no test IDs there: pytest reports one + # file-level ERROR. Go JSON likewise reports a package-level ERROR only + # with explicit build-failure evidence; its tests use package::test IDs. + # In either case, only tests from that exact unit can be inferred. + uncollected = { + name for name, st in pre_status.items() if st == "ERROR" and "::" not in name + } + promoted: dict[str, int] = {} + for tname, post_st in post_status.items(): + if tname in pre_status or tname in flaky or post_st != "PASSED": + continue + module = tname.split("::", 1)[0] + if module in uncollected: + fail_to_pass.append(tname) + promoted[module] = promoted.get(module, 0) + 1 + if promoted: + logger.info( + "validate_pr: fail-to-pass tests inferred from base collection/build errors: %s", + promoted, + ) + + # Diagnostics: when yield is poor, this tells us whether the suite even + # ran (test counts) and where transitions went — distinguishing "genuine + # non-bugfix PR" from "validation didn't detect the failing test". logger.info( - "validate_pr: fail-to-pass tests inferred from base collection/build errors: %s", - promoted, + "validate_pr: parsed pre=%d post=%d tests; f2p=%d p2p=%d (pre statuses: %s)", + len(pre_status), + len(post_status), + len(fail_to_pass), + len(pass_to_pass), + {s: sum(1 for v in pre_status.values() if v == s) for s in set(pre_status.values())}, ) - # Diagnostics: when yield is poor, this tells us whether the suite even - # ran (test counts) and where transitions went — distinguishing "genuine - # non-bugfix PR" from "validation didn't detect the failing test". - logger.info( - "validate_pr: parsed pre=%d post=%d tests; f2p=%d p2p=%d (pre statuses: %s)", - len(pre_status), - len(post_status), - len(fail_to_pass), - len(pass_to_pass), - {s: sum(1 for v in pre_status.values() if v == s) for s in set(pre_status.values())}, - ) - - if not fail_to_pass: - return ValidationOutcome( + if not fail_to_pass: + return ValidationOutcome( + test_cmds=test_cmds, + status="failed", + reason="no fail-to-pass tests after validation", + fail_to_pass=fail_to_pass, + pass_to_pass=pass_to_pass, + pre_log=pre_log, + post_log=post_log, + flaky=sorted(flaky), + ) + + mutants = _validate_mutants( + sandbox=sandbox, + host=host, + base_commit=base_commit, + patch=patch, + test_patch=test_patch, test_cmds=test_cmds, - status="failed", - reason="no fail-to-pass tests after validation", - fail_to_pass=fail_to_pass, - pass_to_pass=pass_to_pass, - pre_log=pre_log, - post_log=post_log, - flaky=sorted(flaky), + language=language, + timeout=timeout, + targets=sorted(fail_to_pass), + tracked=sorted(fail_to_pass) + sorted(pass_to_pass), + post_status=post_status, + clock=clock, ) - - mutants = _validate_mutants( - sandbox=sandbox, - base_commit=base_commit, - patch=patch, - test_patch=test_patch, - test_cmds=test_cmds, - language=language, - timeout=timeout, - targets=sorted(fail_to_pass), - tracked=sorted(fail_to_pass) + sorted(pass_to_pass), - post_status=post_status, - clock=clock, - ) - timing = measure(clock.samples, clock.copies) - timing, checked = fit_runs(timing, mutants is not None) - mutants = mutants if checked else None - if timing is not None and timing.over_cap: + timing = measure(clock.samples, clock.copies) + timing, checked = fit_runs(timing, mutants is not None) + mutants = mutants if checked else None + if timing is not None and timing.over_cap: + return ValidationOutcome( + test_cmds=test_cmds, + status="failed", + reason=( + f"grading would need a {timing.needed_verifier_timeout} s verifier timeout, " + "over the cap" + ), + pre_log=pre_log, + post_log=post_log, + flaky=sorted(flaky), + timing=timing, + ) return ValidationOutcome( test_cmds=test_cmds, - status="failed", - reason=( - f"grading would need a {timing.needed_verifier_timeout} s verifier timeout, " - "over the cap" - ), + status="verified", + fail_to_pass=sorted(fail_to_pass), + pass_to_pass=sorted(pass_to_pass), pre_log=pre_log, post_log=post_log, flaky=sorted(flaky), timing=timing, + mutants=mutants, ) - return ValidationOutcome( - test_cmds=test_cmds, - status="verified", - fail_to_pass=sorted(fail_to_pass), - pass_to_pass=sorted(pass_to_pass), - pre_log=pre_log, - post_log=post_log, - flaky=sorted(flaky), - timing=timing, - mutants=mutants, - ) + finally: + host.close() def flaky_tests(runs: list[dict[str, str]]) -> set[str]: @@ -696,6 +775,7 @@ def _read_workspace_file(sandbox: DockerSandbox, path: str) -> str | None: def _validate_mutants( *, sandbox: DockerSandbox, + host: _StageHost | None = None, base_commit: str, patch: str, test_patch: str, @@ -720,7 +800,7 @@ def _validate_mutants( seed = hashlib.sha256(f"{base_commit}\0{test_patch}".encode()).hexdigest() def read(path: str) -> str | None: - return _read_workspace_file(sandbox, path) + return _read_workspace_file(host.reader() if host else sandbox, path) # Python through its own AST; Go, Rust and JS/TS through tree-sitter. mutants = make_mutants( @@ -738,17 +818,18 @@ def read(path: str) -> str | None: ) if mutants is None: return None + stage = host.stage() if host else sandbox script = _build_stage_script( base_commit, apply_patch=patch, apply_test_patch=test_patch, test_cmds=test_cmds, language=language, - staged=_stage(sandbox, patch=patch, test_patch=test_patch, mutants=mutants), + staged=_stage(stage, patch=patch, test_patch=test_patch, mutants=mutants), test_timeout=_test_timeout(timeout), ) logger.info("validate_pr: running the mutant stage (%d tests)", len(mutants.ids)) - output = clock.run(sandbox, script, timeout).truncated(max_chars=5_000_000) + output = clock.run(stage, script, timeout).truncated(max_chars=5_000_000) exit_code = _EXIT_RE.search(output) fixed = parse_logs(test_cmds, _slice_test_output(output), language=language) kept = validated(mutants, fixed=post_status, fixed_with_mutants=fixed, tracked=tracked) diff --git a/src/repo2rlenv/spec/options.py b/src/repo2rlenv/spec/options.py index ba76f27b..7fb92efa 100644 --- a/src/repo2rlenv/spec/options.py +++ b/src/repo2rlenv/spec/options.py @@ -55,6 +55,9 @@ class PRRuntimeOptions(_BaseOptions): min_fail_to_pass: int = 1 validation_timeout_sec: int = 600 # per-PR cap on the two test runs skip_validation: bool = False # emit candidates without F2P/P2P (debug / fast iteration) + # Run each validation stage in a new container from a snapshot of the prepared + # sandbox, so nothing one stage leaves behind reaches the next. + fresh_validation_stages: bool = False # --- Quality (SWE-bench Lite-style sampling) --- lite_filter: bool = False diff --git a/tests/test_validate_fresh_stages.py b/tests/test_validate_fresh_stages.py new file mode 100644 index 00000000..8c7ce246 --- /dev/null +++ b/tests/test_validate_fresh_stages.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import subprocess + +import pytest + +from repo2rlenv.pipelines import pr_runtime_validate as validate + +_STARTED = [] + + +class _Sandbox: + def __init__(self, name, platform="linux/amd64"): + self.name, self.platform = name, platform + self.container_id = name + self.committed, self.cleaned = [], False + + def commit(self, tag, *, message=""): + self.committed.append(tag) + return tag + + def cleanup(self, *, strict=False): + self.cleaned = True + + +def _fake_start(image, repo_dir, *, platform): + sandbox = _Sandbox(f"stage{len(_STARTED)}", platform) + sandbox.image = image + _STARTED.append(sandbox) + return sandbox + + +def test_shared_mode_runs_every_stage_in_the_sandbox(): + anchor = _Sandbox("anchor") + host = validate._StageHost(anchor, fresh=False) + assert host.stage() is anchor and host.stage() is anchor + assert host.reader() is anchor + host.close() + assert anchor.committed == [] and not anchor.cleaned + + +def test_fresh_mode_snapshots_once_and_gives_each_stage_its_own_container(monkeypatch): + _STARTED.clear() + monkeypatch.setattr(validate.DockerSandbox, "start", staticmethod(_fake_start)) + docker = [] + monkeypatch.setattr( + validate.subprocess, + "run", + lambda args, **kwargs: docker.append(args[1:]) or subprocess.CompletedProcess(args, 0), + ) + anchor = _Sandbox("anchor", platform="linux/arm64") + host = validate._StageHost(anchor, fresh=True) + first, second = host.stage(), host.stage() + assert first is not second and first is not anchor + assert len(anchor.committed) == 1 # one snapshot per candidate + assert {s.image for s in (first, second)} == set(anchor.committed) + assert first.platform == "linux/arm64" + assert first.cleaned and not second.cleaned # the previous stage is discarded + assert host.reader() is second # mutants read the latest stage's tree + host.close() + assert second.cleaned and not anchor.cleaned + # Container cleanup force-removes each stage; the snapshot image is removed. + assert docker == [ + ["image", "rm", "-f", anchor.committed[0]], + ] + + +def test_cleanup_attempts_image_removal_even_if_container_cleanup_fails(monkeypatch, caplog): + anchor = _Sandbox("anchor") + host = validate._StageHost(anchor, fresh=True) + image = host.image = "r2e-validate/test:stage" + host.current = _Sandbox("stage") + calls = [] + + def broken_cleanup(*, strict): + assert strict + raise OSError("daemon unavailable") + + monkeypatch.setattr(host.current, "cleanup", broken_cleanup) + monkeypatch.setattr( + validate.subprocess, + "run", + lambda args, **kwargs: calls.append(args) or validate.subprocess.CompletedProcess(args, 0), + ) + # The original validation error must survive cleanup; image removal is still attempted. + with pytest.raises(ValueError, match="invalid candidate"): + try: + raise ValueError("invalid candidate") + finally: + host.close() + assert ["docker", "image", "rm", "-f", image] in calls + assert "daemon unavailable" in caplog.text + + +@pytest.mark.parametrize( + "failure", [OSError("missing docker"), subprocess.TimeoutExpired("docker", 60)] +) +def test_image_cleanup_failure_does_not_hide_validation_result(monkeypatch, caplog, failure): + host = validate._StageHost(_Sandbox("anchor"), fresh=True) + host.image = "r2e-validate/test:stage" + + def fail(*args, **kwargs): + raise failure + + monkeypatch.setattr(validate.subprocess, "run", fail) + host.close() + assert host.image is not None # failed cleanup remains available for retry + assert "Could not remove validation snapshot" in caplog.text + + +def test_start_failure_removes_temporary_directory_and_snapshot(monkeypatch): + host = validate._StageHost(_Sandbox("anchor"), fresh=True) + directories = [] + removals = [] + + def fail(image, directory, **kwargs): + directories.append(directory) + raise validate.DockerError("start failed") + + monkeypatch.setattr(validate.DockerSandbox, "start", fail) + monkeypatch.setattr( + validate.subprocess, + "run", + lambda args, **kwargs: removals.append(args) or subprocess.CompletedProcess(args, 0), + ) + with pytest.raises(validate.DockerError, match="start failed"): + try: + host.stage() + finally: + host.close() + assert directories and not directories[0].exists() + assert len(removals) == 1 and removals[0][:4] == ["docker", "image", "rm", "-f"] + host.close() + assert len(removals) == 1 + + +@pytest.mark.parametrize("exit_code", [1, 124]) +def test_failed_container_removal_blocks_next_stage_and_can_be_retried( + monkeypatch, caplog, exit_code +): + from repo2rlenv.bootstrap import docker + + current = docker.DockerSandbox("stage", "/workspace", "linux/amd64") + host = validate._StageHost(_Sandbox("anchor"), fresh=True) + host.current = current + host.image = "r2e-validate/test:stage" + monkeypatch.setattr( + docker, + "_run", + lambda *a, **k: docker.ExecResult(exit_code, "", "removal failed", 0), + ) + monkeypatch.setattr( + validate.subprocess, + "run", + lambda args, **kwargs: subprocess.CompletedProcess(args, 0), + ) + with pytest.raises(docker.DockerError, match="removal failed"): + host.stage() + assert host.current is current and current._alive + host.close() + assert "Could not remove validation stage container" in caplog.text + assert host.current is current + monkeypatch.setattr(docker, "_run", lambda *a, **k: docker.ExecResult(0, "", "", 0)) + host.close() + assert host.current is None and not current._alive diff --git a/tests/test_validate_fresh_stages_container.py b/tests/test_validate_fresh_stages_container.py new file mode 100644 index 00000000..22d33fcd --- /dev/null +++ b/tests/test_validate_fresh_stages_container.py @@ -0,0 +1,179 @@ +"""Fresh-stage lifecycle controls, run in the Linux Docker CI job.""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import uuid +from pathlib import Path + +import pytest + +from repo2rlenv.bootstrap.docker import DockerSandbox +from repo2rlenv.pipelines import pr_runtime_validate as validate + +pytestmark = pytest.mark.skipif( + os.environ.get("R2E_DOCKER_TESTS") != "1" or shutil.which("docker") is None, + reason="set R2E_DOCKER_TESTS=1 to run fresh-stage container controls", +) + + +def _run(*args: str, cwd: Path | None = None, check: bool = True): + return subprocess.run(args, cwd=cwd, capture_output=True, text=True, timeout=180, check=check) + + +@pytest.fixture(scope="module") +def image(tmp_path_factory): + context = tmp_path_factory.mktemp("fresh-stage-image") + (context / "Dockerfile").write_text( + "FROM python:3.12-slim\n" + "RUN apt-get update && apt-get install -y --no-install-recommends git " + "&& rm -rf /var/lib/apt/lists/*\n" + "RUN pip install --no-cache-dir pytest==8.3.5\n" + "WORKDIR /workspace\n" + ) + tag = f"r2e-fresh-stage-test:{uuid.uuid4().hex[:12]}" + try: + _run("docker", "build", "-t", tag, str(context)) + yield tag + finally: + _run("docker", "image", "rm", "-f", tag, check=False) + + +@pytest.fixture +def candidate(tmp_path): + _run("git", "init", str(tmp_path)) + _run("git", "config", "user.email", "test@example.com", cwd=tmp_path) + _run("git", "config", "user.name", "Test", cwd=tmp_path) + (tmp_path / "value.py").write_text("def value():\n return 1\n") + (tmp_path / "test_value.py").write_text( + "from value import value\n\ndef test_integer():\n assert isinstance(value(), int)\n" + ) + _run("git", "add", ".", cwd=tmp_path) + _run("git", "commit", "-m", "base", cwd=tmp_path) + base = _run("git", "rev-parse", "HEAD", cwd=tmp_path).stdout.strip() + (tmp_path / "value.py").write_text("def value():\n return 2\n") + patch = _run("git", "diff", "--", "value.py", cwd=tmp_path).stdout + with (tmp_path / "test_value.py").open("a") as f: + f.write("\ndef test_fixed():\n assert value() == 2\n") + test_patch = _run("git", "diff", "--", "test_value.py", cwd=tmp_path).stdout + _run("git", "reset", "--hard", base, cwd=tmp_path) + return tmp_path, base, patch, test_patch + + +def _assert_removed(containers, snapshots): + assert all(_run("docker", "inspect", cid, check=False).returncode for cid in containers) + assert all(_run("docker", "image", "inspect", tag, check=False).returncode for tag in snapshots) + + +def test_fresh_stages_isolate_files_and_processes(image, candidate): + directory, *_ = candidate + with DockerSandbox.start(image, directory) as anchor: + assert anchor.exec("echo prepared > /var/tmp/r2e-prepared").ok + host = validate._StageHost(anchor, fresh=True) + containers, snapshots = [], [] + try: + first = host.stage() + containers.append(first.container_id) + snapshots.append(host.image) + assert first.exec( + "echo dirty > /var/tmp/r2e-dirty; nohup sleep 9876 >/dev/null 2>&1 &" + ).ok + process_check = ( + 'python -c "from pathlib import Path; ' + "print(any(p.read_bytes() == b'sleep\\x009876\\x00' " + "for p in Path('/proc').glob('[0-9]*/cmdline') if p.exists()))\"" + ) + process = first.exec(process_check) + assert process.ok and process.stdout.strip() == "True" + second = host.stage() + containers.append(second.container_id) + assert second.exec("test -f /var/tmp/r2e-prepared && test ! -e /var/tmp/r2e-dirty").ok + process = second.exec(process_check) + assert process.ok and process.stdout.strip() == "False" + assert anchor.exec("test ! -e /var/tmp/r2e-dirty").ok + finally: + host.close() + _assert_removed(containers, snapshots) + + +def test_fresh_and_shared_validation_have_the_same_evidence(image, candidate, monkeypatch): + directory, base, patch, test_patch = candidate + containers, snapshots = [], [] + start, commit = DockerSandbox.start, DockerSandbox.commit + + def track_start(*args, **kwargs): + sandbox = start(*args, **kwargs) + containers.append(sandbox.container_id) + return sandbox + + def track_commit(self, tag, **kwargs): + snapshots.append(tag) + return commit(self, tag, **kwargs) + + monkeypatch.setattr(DockerSandbox, "start", track_start) + monkeypatch.setattr(DockerSandbox, "commit", track_commit) + outcomes = [] + for fresh in (False, True): + with DockerSandbox.start(image, directory) as anchor: + outcomes.append( + validate.validate_pr( + sandbox=anchor, + base_commit=base, + patch=patch, + test_patch=test_patch, + test_cmds=["python -m pytest -v test_value.py"], + language="python", + timeout=60, + fresh_stages=fresh, + ) + ) + for outcome in outcomes: + assert outcome.status == "verified", outcome + assert outcome.fail_to_pass == ["test_value.py::test_fixed"] + assert outcome.pass_to_pass == ["test_value.py::test_integer"] + assert outcome.flaky == [] + assert outcome.mutants is not None + assert len(snapshots) == 1 + assert len(containers) == 2 + 1 + validate.POST_FIX_RUNS + 1 + _assert_removed(containers, snapshots) + + +@pytest.mark.parametrize("fail", [False, True]) +def test_rejection_and_exception_remove_snapshot_and_stages(image, candidate, monkeypatch, fail): + directory, base, patch, test_patch = candidate + hosts = [] + stage = validate._StageHost.stage + + def record(self): + sandbox = stage(self) + hosts.append((sandbox.container_id, self.image)) + return sandbox + + monkeypatch.setattr(validate._StageHost, "stage", record) + if fail: + + def broken_upload(*args, **kwargs): + raise ValueError("upload failed") + + monkeypatch.setattr(validate, "_stage", broken_upload) + with DockerSandbox.start(image, directory) as anchor: + kwargs = dict( + sandbox=anchor, + base_commit=base, + patch=patch, + test_patch=test_patch, + test_cmds=["false"], + language="python", + timeout=60, + fresh_stages=True, + ) + if fail: + with pytest.raises(ValueError, match="upload failed"): + validate.validate_pr(**kwargs) + else: + assert validate.validate_pr(**kwargs).status == "failed" + assert anchor.exec("true").ok + assert hosts + _assert_removed([cid for cid, _ in hosts], {tag for _, tag in hosts})