Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix(agentic): repair baseline collection verification (#6313)

nate nowack9e553dd970a3
diff --git a/.github/agentic/README.md b/.github/agentic/README.md
index 3c0ee4844..a6fc21456 100644
--- a/.github/agentic/README.md
+++ b/.github/agentic/README.md
@@ -40,6 +40,29 @@ uv run pytest -q
`agentic-checks.yml` runs the same checks in CI.
+## Contribution verification
+
+Changed author tests run on baseline and head. A module that only collects on
+head is retained as `baseline_collection_incompatible`, with its collection
+errors and output in the review summary. Without a standalone behavior probe,
+verification returns `evidence_needed`; do not retry unchanged tests as an
+environment outage or count an import error as a reproduced bug.
+
+Supply a baseline-compatible test through the item's `verification_probes` to
+repair the evidence. If author-module collection blocks the combined baseline
+run, the verifier runs those probes separately on both revisions, reusing their
+completed setup and limiting each probe run to 60 seconds. Author head results
+remain separate; only completed failure-to-pass test transitions establish
+`fixed_tests`. Source/probe/configuration files, Git metadata and installed dependency
+files are fingerprinted before execution and checked before/after each run and
+again before returning comparisons. Added, removed or modified inputs invalidate
+all transitions and produce `evidence_needed`, with bounded changed-path diagnostics.
+Both environments are prepared before author tests run; each test invocation gets
+a fresh HOME, temporary directory and pytest cache. Bytecode writes and user-site
+packages are disabled. These checks reject persistent contamination; they do not
+turn execution of contribution code into a security proof or replace contract review.
+Identical verification specs reuse the retained execution.
+
## Public review delivery
Every selected contribution still needs fresh head/baseline verification and independent
diff --git a/.github/agentic/flows/agentic_existing_review.py b/.github/agentic/flows/agentic_existing_review.py
index a6d22ee14..f4456b47f 100644
--- a/.github/agentic/flows/agentic_existing_review.py
+++ b/.github/agentic/flows/agentic_existing_review.py
@@ -53,11 +53,20 @@ def verification_result(run_id: UUID, runtime: Runtime, spec: VerificationSpec)
def summary(result: dict) -> dict:
stages = {}
- for name in ("base", "head", "adjacent"):
+ for name in ("base", "head", "adjacent", "probe_base", "probe_head"):
stage = result.get(name, {})
stages[name] = {
"status": stage.get("status", "not_run"),
"reason": stage.get("reason"),
+ "input_sha256": stage.get("input_sha256"),
+ "input_changes": stage.get("input_changes", []),
+ "input_changes_truncated": stage.get("input_changes_truncated", False),
+ "test_status": stage.get("test_status"),
+ "command": stage.get("command"),
+ "returncode": stage.get("returncode"),
+ "output_tail": stage.get("output_tail", "")[-6000:],
+ "output_truncated": stage.get("output_truncated", False)
+ or len(stage.get("output_tail", "")) > 6000,
"counts": dict(Counter(case["state"] for case in stage.get("cases", []))),
"failures": [
case
@@ -71,6 +80,7 @@ def summary(result: dict) -> dict:
"head_sha": result["spec"]["head_sha"],
"baseline_sha": result.get("baseline_sha"),
"status": result["status"],
+ "reason": result.get("reason"),
"tests": stages,
"comparison": result.get("comparison", {}),
"independent_probes": sorted(result["spec"]["probes"]),
@@ -220,6 +230,15 @@ def verify_existing(
if results
else "Review the assessment of merged contributions and subsequent history; no unmerged contribution was sent to verification"
)
+ if any(result["status"] == "evidence_needed" for result in results):
+ status = "evidence_needed"
+ next_step = (
+ "Repair the retained verification inputs. For baseline collection failures, "
+ "supply a standalone baseline-compatible behavior probe in verification_probes. "
+ "For input_mutation, fix the tests that modified the listed inputs. "
+ "Keep author tests on head; collection errors never establish a fix. "
+ "Do not retry unchanged inputs as an environment failure."
+ )
if not results and any(not pr["merged"] for pr in evidence["prs"]):
status = "verification_selection_required"
next_step = "Review why assessment selected no contribution for execution; no tests were run"
diff --git a/.github/agentic/flows/agentic_pr_verification.py b/.github/agentic/flows/agentic_pr_verification.py
index fa90e0e74..8b6bc3866 100644
--- a/.github/agentic/flows/agentic_pr_verification.py
+++ b/.github/agentic/flows/agentic_pr_verification.py
@@ -19,6 +19,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator
from flows.agentic_stack import digest
from flows.agentic_validate_patch import install_tools
+from flows.agentic_verification_inputs import VerificationInputs, reject_mutations
from flows.agentic_verification_process import isolated_verification
@@ -66,6 +67,8 @@ def environment(home: Path) -> dict[str, str]:
"GIT_COMMITTER_NAME": "Verification",
"GIT_COMMITTER_EMAIL": "[email protected]",
"PYTEST_XDIST_AUTO_NUM_WORKERS": "4",
+ "PYTHONDONTWRITEBYTECODE": "1",
+ "PYTHONNOUSERSITE": "1",
}
@@ -128,8 +131,17 @@ def merge_base(directory: Path, env: dict[str, str], head: str, trunk: str) -> s
def pytest_result(command: dict, report: Path) -> dict:
- result = {**command, "status": "environment_failure", "cases": []}
- if command["timed_out"] or command["returncode"] not in {0, 1}:
+ result = {
+ **command,
+ "status": "environment_failure",
+ "cases": [],
+ "reason": "Pytest did not produce a valid completed test report",
+ }
+ if command["timed_out"]:
+ result["reason"] = "Pytest timed out"
+ return result
+ if command["returncode"] not in {0, 1, 2}:
+ result["reason"] = f"Pytest exited with code {command['returncode']}"
return result
if not report.is_file() or report.stat().st_size > 5_000_000:
return result
@@ -155,6 +167,14 @@ def pytest_result(command: dict, report: Path) -> dict:
"detail": detail,
}
)
+ if command["returncode"] == 2:
+ errors = [
+ case["detail"] for case in result["cases"] if case["state"] == "error"
+ ]
+ if errors:
+ result["status"] = "collection_failure"
+ result["reason"] = "Pytest collection failed: " + "\n".join(errors)[-6000:]
+ return result
states = [case["state"] for case in result["cases"]]
ids = [case["id"] for case in result["cases"]]
if (
@@ -168,25 +188,85 @@ def pytest_result(command: dict, report: Path) -> dict:
result["status"] = "test_failure"
elif command["returncode"] == 0 and "failure" not in states and "passed" in states:
result["status"] = "passed"
+ if result["status"] != "environment_failure":
+ result["reason"] = None
return result
-def run_tests(repo: Path, paths: list[str], env: dict[str, str], report: Path) -> dict:
- setup = execute(["uv", "sync", "--frozen"], repo, env, timeout=300)
+def run_tests(
+ repo: Path,
+ paths: list[str],
+ env: dict[str, str],
+ report: Path,
+ *,
+ setup: dict,
+ inputs: VerificationInputs,
+ timeout: int = 600,
+) -> dict:
if setup["returncode"]:
- return {"status": "environment_failure", "setup": setup, "cases": []}
+ return {
+ "status": "environment_failure",
+ "reason": "Dependency setup failed",
+ "setup": setup,
+ "cases": [],
+ }
+ if changes := inputs.changes():
+ return reject_mutations(
+ {"status": "not_run", "cases": [], "setup": setup}, changes
+ )
lock = repo / "uv.lock"
lock_sha = hashlib.sha256(lock.read_bytes()).hexdigest() if lock.exists() else None
+ stage_home = tempfile.mkdtemp(prefix=report.stem + "-home-", dir=report.parent)
+ stage_tmp = tempfile.mkdtemp(prefix=report.stem + "-tmp-", dir=report.parent)
+ stage_cache = tempfile.mkdtemp(prefix=report.stem + "-cache-", dir=report.parent)
+ stage_env = {**env, "HOME": stage_home, "TMPDIR": stage_tmp}
result = execute(
- ["uv", "run", "--no-sync", "pytest", "-n", "0", f"--junitxml={report}", *paths],
+ [
+ "uv",
+ "run",
+ "--no-sync",
+ "--no-config",
+ "--no-env-file",
+ "pytest",
+ "-n",
+ "0",
+ "-o",
+ f"cache_dir={stage_cache}",
+ f"--junitxml={report}",
+ *paths,
+ ],
repo,
- env,
- timeout=600,
+ stage_env,
+ timeout=timeout,
+ )
+ return reject_mutations(
+ {
+ **pytest_result(result, report),
+ "setup": setup,
+ "lock_sha256": lock_sha,
+ "input_sha256": digest(
+ {
+ "source": inputs.source,
+ "installed": inputs.installed,
+ "metadata": inputs.metadata,
+ }
+ ),
+ },
+ inputs.changes(),
)
- return {**pytest_result(result, report), "setup": setup, "lock_sha256": lock_sha}
def outcomes(base: dict, head: dict) -> dict:
+ if base["status"] not in {"passed", "test_failure"} or head["status"] not in {
+ "passed",
+ "test_failure",
+ }:
+ return {
+ "fixed_tests": [],
+ "regressed_tests": [],
+ "unmatched_tests": [],
+ "interpretation": "Incomplete test runs cannot establish behavior transitions.",
+ }
before = {case["id"]: case for case in base["cases"]}
after = {case["id"]: case for case in head["cases"]}
return {
@@ -270,9 +350,6 @@ def verify(
raise ValueError("Independent probes must not replace existing files")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(source)
- selected = [*paths, *spec.probes]
- baseline = run_tests(base, selected, env, directory / "base.xml")
- candidate = run_tests(head, selected, env, directory / "head.xml")
parents = sorted({str(PurePosixPath(p).parent) for p in paths})
tracked = git(
head, env, "ls-tree", "-r", "--name-only", "HEAD", "--", "tests"
@@ -285,6 +362,61 @@ def verify(
and path.endswith(".py")
and path not in paths
]
+ base_inputs = VerificationInputs(base)
+ head_inputs = VerificationInputs(head)
+ setups = {}
+ for repo, inputs in ((base, base_inputs), (head, head_inputs)):
+ setups[repo] = execute(["uv", "sync", "--frozen"], repo, env, timeout=300)
+ inputs.installed_inputs()
+ head_inputs.seal_metadata()
+ selected = [*paths, *spec.probes]
+ baseline = run_tests(
+ base,
+ selected,
+ env,
+ directory / "base.xml",
+ setup=setups[base],
+ inputs=base_inputs,
+ )
+ candidate = run_tests(
+ head,
+ selected,
+ env,
+ directory / "head.xml",
+ setup=setups[head],
+ inputs=head_inputs,
+ )
+ probe_results = {}
+ comparison = outcomes(baseline, candidate)
+ if baseline["status"] == "collection_failure" and candidate["status"] in {
+ "passed",
+ "test_failure",
+ }:
+ baseline["status"] = "baseline_collection_incompatible"
+ baseline["reason"] += (
+ "\nAuthor tests cannot collect on baseline. Supply a standalone baseline-compatible behavior probe; do not copy implementation helpers onto baseline."
+ )
+ if spec.probes:
+ probe_base = run_tests(
+ base,
+ list(spec.probes),
+ env,
+ directory / "probe-base.xml",
+ setup=baseline["setup"],
+ inputs=base_inputs,
+ timeout=60,
+ )
+ probe_head = run_tests(
+ head,
+ list(spec.probes),
+ env,
+ directory / "probe-head.xml",
+ setup=candidate["setup"],
+ inputs=head_inputs,
+ timeout=60,
+ )
+ probe_results = {"probe_base": probe_base, "probe_head": probe_head}
+ comparison = outcomes(probe_base, probe_head)
limitations = [
"Current target-branch composition and full-suite/static validation remain separate checks.",
"Author tests are not independent contract verification; supplied probes are identified separately.",
@@ -295,7 +427,14 @@ def verify(
)
neighbors = []
adjacent = (
- run_tests(head, neighbors, env, directory / "adjacent.xml")
+ run_tests(
+ head,
+ neighbors,
+ env,
+ directory / "adjacent.xml",
+ setup=setups[head],
+ inputs=head_inputs,
+ )
if neighbors
else {
"status": "not_run",
@@ -303,19 +442,44 @@ def verify(
"reason": "No sibling modules within the verification budget",
}
)
+ base_changes = base_inputs.changes()
+ head_changes = head_inputs.changes()
+ baseline = reject_mutations(baseline, base_changes)
+ candidate = reject_mutations(candidate, head_changes)
+ if "probe_base" in probe_results:
+ probe_results["probe_base"] = reject_mutations(
+ probe_results["probe_base"], base_changes
+ )
+ probe_results["probe_head"] = reject_mutations(
+ probe_results["probe_head"], head_changes
+ )
+ adjacent = reject_mutations(adjacent, head_changes)
status = "verification_recorded"
- if any(
- r["status"] == "environment_failure" for r in (baseline, candidate, adjacent)
- ):
+ reason = None
+ if baseline["status"] == "baseline_collection_incompatible" and not probe_results:
+ status = "evidence_needed"
+ reason = baseline["reason"]
+ stages = (baseline, candidate, adjacent, *probe_results.values())
+ if any(r["status"] == "collection_failure" for r in stages):
+ status = "evidence_needed"
+ reason = "Test collection failed; repair the test inputs before requesting verification again."
+ if any(r["status"] == "environment_failure" for r in stages):
status = "environment_failure"
+ reason = "Verification could not complete; inspect stage diagnostics before retrying."
+ if any(r["status"] == "input_mutation" for r in stages):
+ status = "evidence_needed"
+ reason = "Verification inputs were modified; retained test output cannot establish behavior transitions."
+ comparison = outcomes({"status": "input_mutation"}, candidate)
return {
**result,
"status": status,
+ "reason": reason,
+ **probe_results,
"base": baseline,
"head": candidate,
"adjacent": adjacent,
"adjacent_tests": neighbors,
- "comparison": outcomes(baseline, candidate),
+ "comparison": comparison,
"limitations": limitations,
}
diff --git a/.github/agentic/flows/agentic_verification_inputs.py b/.github/agentic/flows/agentic_verification_inputs.py
new file mode 100644
index 000000000..2b5764bba
--- /dev/null
+++ b/.github/agentic/flows/agentic_verification_inputs.py
@@ -0,0 +1,102 @@
+from __future__ import annotations
+
+import hashlib
+import os
+import stat
+from dataclasses import dataclass, field
+from pathlib import Path
+
+
+def manifest(root: Path, *, source: bool) -> dict[str, tuple[int, str]]:
+ files = {}
+ for directory, names, leaves in os.walk(root, followlinks=False):
+ parent = Path(directory)
+ files[parent.relative_to(root).as_posix() + "/"] = (
+ parent.stat().st_mode,
+ "directory",
+ )
+ for name in list(names):
+ path = parent / name
+ if source and path == root / name and name in {".git", ".venv"}:
+ names.remove(name)
+ elif path.is_symlink():
+ names.remove(name)
+ leaves.append(name)
+ for name in leaves:
+ path = parent / name
+ relative = path.relative_to(root).as_posix()
+ try:
+ mode = path.lstat().st_mode
+ if stat.S_ISLNK(mode):
+ content = os.readlink(path).encode()
+ elif stat.S_ISREG(mode):
+ with path.open("rb") as source_file:
+ fingerprint = hashlib.file_digest(
+ source_file, "sha256"
+ ).hexdigest()
+ files[relative] = (mode, fingerprint)
+ continue
+ else:
+ content = b"special file"
+ files[relative] = (mode, hashlib.sha256(content).hexdigest())
+ except OSError:
+ files[relative] = (0, "unreadable")
+ return files
+
+
+@dataclass
+class VerificationInputs:
+ repo: Path
+ source: dict = field(init=False)
+ installed: dict | None = None
+ metadata: dict | None = None
+
+ def __post_init__(self) -> None:
+ self.source = manifest(self.repo, source=True)
+
+ def installed_inputs(self) -> None:
+ self.installed = manifest(self.repo / ".venv", source=False)
+
+ def seal_metadata(self) -> None:
+ if (self.repo / ".git").is_dir():
+ self.metadata = manifest(self.repo / ".git", source=False)
+
+ def changes(self) -> list[str]:
+ changed = []
+ for prefix, expected, actual in (
+ ("", self.source, manifest(self.repo, source=True)),
+ (
+ ".git/",
+ self.metadata,
+ manifest(self.repo / ".git", source=False)
+ if self.metadata is not None
+ else None,
+ ),
+ (
+ ".venv/",
+ self.installed,
+ manifest(self.repo / ".venv", source=False)
+ if self.installed is not None
+ else None,
+ ),
+ ):
+ if expected is not None and actual is not None:
+ changed.extend(
+ prefix + name
+ for name in expected.keys() | actual.keys()
+ if expected.get(name) != actual.get(name)
+ )
+ return sorted(changed)
+
+
+def reject_mutations(result: dict, changes: list[str]) -> dict:
+ if not changes:
+ return result
+ return {
+ **result,
+ "test_status": result.get("test_status", result["status"]),
+ "status": "input_mutation",
+ "reason": "Verification inputs changed during execution; discard transitions and repair the test inputs.",
+ "input_changes": changes[:100],
+ "input_changes_truncated": len(changes) > 100,
+ }
diff --git a/.github/agentic/tests/test_agentic_existing_review.py b/.github/agentic/tests/test_agentic_existing_review.py
index cd4708563..0cf914ee3 100644
--- a/.github/agentic/tests/test_agentic_existing_review.py
+++ b/.github/agentic/tests/test_agentic_existing_review.py
@@ -8,6 +8,7 @@ from prefect.testing.utilities import prefect_test_harness
from flows.agentic_existing_review import (
start_verification,
+ summary,
unadmitted_selection,
verification_result,
verification_specs,
@@ -211,3 +212,38 @@ def test_failed_verification_retry_is_idempotent_and_success_is_reused():
assert start_verification(runtime, spec, "native-parent").id == retried.id
client.set_flow_run_state(retried.id, Completed(), force=True)
assert start_verification(runtime, spec, "next-native-parent").id == retried.id
+
+
+def test_summary_preserves_collection_diagnosis_and_probe_results():
+ result = summary(
+ {
+ "run_id": "retained-run",
+ "spec": {
+ "pr_number": 6311,
+ "head_sha": "a" * 40,
+ "probes": {"tests/agentic_probes/test_behavior.py": "source"},
+ },
+ "status": "evidence_needed",
+ "reason": "Supply a baseline-compatible probe",
+ "usage": {},
+ "base": {
+ "status": "baseline_collection_incompatible",
+ "reason": "ImportError: new_helper",
+ "returncode": 2,
+ "command": ["pytest"],
+ "output_tail": "x" * 7000,
+ "cases": [
+ {"id": "test_helper", "state": "error", "detail": "new_helper"}
+ ],
+ },
+ "probe_base": {"status": "test_failure", "cases": []},
+ }
+ )
+ assert result["reason"] == "Supply a baseline-compatible probe"
+ stage = result["tests"]["base"]
+ assert stage["reason"] == "ImportError: new_helper"
+ assert stage["returncode"] == 2
+ assert stage["failures"][0]["detail"] == "new_helper"
+ assert len(stage["output_tail"]) == 6000
+ assert stage["output_truncated"]
+ assert result["tests"]["probe_base"]["status"] == "test_failure"
diff --git a/.github/agentic/tests/test_agentic_pr_verification.py b/.github/agentic/tests/test_agentic_pr_verification.py
index 14daf0d06..0cffbd69d 100644
--- a/.github/agentic/tests/test_agentic_pr_verification.py
+++ b/.github/agentic/tests/test_agentic_pr_verification.py
@@ -247,3 +247,189 @@ def test_old_contribution_fetches_history_before_computing_changed_tests(tmp_pat
assert result["baseline_sha"] == trunk
assert result["status"] == "evidence_needed"
assert result["changed_tests"] == []
+
+
+def test_real_collection_import_error_retains_diagnostics_without_fix_claim(tmp_path):
+ (tmp_path / "test_import.py").write_text("from pathlib import missing_helper\n")
+ report = tmp_path / "junit.xml"
+ command = execute(
+ [sys.executable, "-m", "pytest", "test_import.py", f"--junitxml={report}"],
+ tmp_path,
+ environment(tmp_path / "home"),
+ )
+ result = pytest_result(command, report)
+ assert result["status"] == "collection_failure"
+ assert "missing_helper" in result["reason"]
+ assert result["cases"][0]["state"] == "error"
+ assert "ImportError" in result["output_tail"]
+ assert not outcomes(result, result)["fixed_tests"]
+
+
[email protected]("with_probe", [False, True])
+def test_new_helper_import_uses_independent_behavior_probe(tmp_path, with_probe):
+ repo = tmp_path / "origin"
+ repo.mkdir()
+ for args in (
+ ("init",),
+ ("config", "user.name", "Test"),
+ ("config", "user.email", "[email protected]"),
+ ):
+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)
+ (repo / "pyproject.toml").write_text(
+ '[project]\nname="verification-fixture"\nversion="0.1"\nrequires-python=">=3.12"\ndependencies=["pytest>=8,<10", "pytest-xdist"]\n[tool.pytest.ini_options]\npythonpath=["."]\n'
+ )
+ (repo / "implementation.py").write_text("def behavior():\n return 1\n")
+ subprocess.run(["uv", "lock"], cwd=repo, check=True, capture_output=True)
+ base = commit(repo, "Baseline public behavior")
+ (repo / "implementation.py").write_text(
+ "def new_helper():\n return 2\ndef behavior():\n return new_helper()\n"
+ )
+ (repo / "tests").mkdir()
+ (repo / "tests/test_helper.py").write_text(
+ "from implementation import new_helper\ndef test_helper():\n assert new_helper() == 2\n"
+ )
+ head = commit(repo, "Fix behavior with new helper")
+ spec = VerificationSpec(
+ issue_number=6294,
+ pr_number=6311,
+ head_sha=head,
+ trunk_sha=base,
+ trunk_ref="main",
+ evidence_revision="c" * 64,
+ probes={
+ "tests/agentic_probes/test_behavior.py": "from implementation import behavior\ndef test_behavior():\n assert behavior() == 2\n"
+ }
+ if with_probe
+ else {},
+ )
+ directory = tmp_path / "verification"
+ directory.mkdir()
+ result = verify(spec, directory, str(repo))
+ assert result["base"]["status"] == "baseline_collection_incompatible"
+ assert "new_helper" in result["base"]["reason"]
+ assert result["head"]["status"] == "passed"
+ assert result["status"] == (
+ "verification_recorded" if with_probe else "evidence_needed"
+ )
+ if with_probe:
+ assert result["probe_base"]["status"] == "test_failure"
+ assert result["probe_head"]["status"] == "passed"
+ assert result["comparison"]["fixed_tests"] == [
+ "tests.agentic_probes.test_behavior::test_behavior"
+ ]
+ else:
+ assert not result["comparison"]["fixed_tests"]
+ assert "probe" in result["reason"]
+
+
+def test_partial_failures_from_incomplete_collection_do_not_establish_transitions():
+ base = {
+ "status": "collection_failure",
+ "cases": [
+ {"id": "test_behavior", "state": "failure"},
+ {"id": "test_helper", "state": "error"},
+ ],
+ }
+ head = {"status": "passed", "cases": [{"id": "test_behavior", "state": "passed"}]}
+ assert outcomes(base, head)["fixed_tests"] == []
+
+
+ "mutation",
+ [
+ "probe",
+ "source",
+ "config",
+ "dependency",
+ "cache",
+ "metadata",
+ "home",
+ "fallback",
+ "peer",
+ "adjacent",
+ ],
+)
+def test_author_collection_mutations_cannot_establish_a_fix(tmp_path, mutation):
+ repo = tmp_path / "origin"
+ repo.mkdir()
+ for args in (
+ ("init",),
+ ("config", "user.name", "Test"),
+ ("config", "user.email", "[email protected]"),
+ ):
+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)
+ (repo / "pyproject.toml").write_text(
+ '[project]\nname="verification-fixture"\nversion="0.1"\nrequires-python=">=3.12"\ndependencies=["pytest>=8,<10", "pytest-xdist"]\n[tool.pytest.ini_options]\npythonpath=["."]\n'
+ )
+ implementation = "def behavior():\n return 1\n"
+ if mutation in {"cache", "home"}:
+ data = (
+ "Path('.pytest_cache/behavior.json')"
+ if mutation == "cache"
+ else "Path.home() / 'behavior.json'"
+ )
+ implementation = f"from pathlib import Path\ndef behavior():\n p = {data}\n return int(p.read_text()) if p.exists() else 1\n"
+ (repo / "implementation.py").write_text(implementation)
+ subprocess.run(["uv", "lock"], cwd=repo, check=True, capture_output=True)
+ if mutation == "adjacent":
+ (repo / "tests").mkdir()
+ (repo / "tests/test_neighbor.py").write_text(
+ "from pathlib import Path\ndef test_neighbor():\n (Path.cwd().parent / 'base/implementation.py').write_text('def behavior():\\n return 0\\n')\n"
+ )
+ base = commit(repo, "Broken behavior")
+ (repo / "implementation.py").write_text(
+ implementation + "def new_helper():\n return 0\n"
+ )
+ (repo / "tests").mkdir(exist_ok=True)
+ attacks = {
+ "cache": "p = root / '.pytest_cache/behavior.json'\np.parent.mkdir(exist_ok=True)\np.write_text(str(2 if hasattr(implementation, 'new_helper') else 1))\n",
+ "metadata": "p = root / '.git'\nif p.is_dir():\n p = p / 'HEAD'\np.write_text('ref: refs/heads/forged\\n')\n",
+ "home": "(Path.home() / 'behavior.json').write_text(str(2 if hasattr(implementation, 'new_helper') else 1))\n",
+ "fallback": "",
+ "adjacent": "",
+ "peer": "if root.name == 'head':\n (root.parent / 'base/implementation.py').write_text('def behavior():\\n return 0\\n')\n",
+ "probe": "p = root / 'tests/agentic_probes/test_behavior.py'\np.write_text('def test_behavior():\\n assert ' + str(hasattr(implementation, 'new_helper')) + '\\n')\n",
+ "source": "p = root / 'implementation.py'\np.write_text('def behavior():\\n return ' + str(2 if hasattr(implementation, 'new_helper') else 1) + '\\ndef new_helper():\\n return 0\\n')\n",
+ "config": "(root / 'tests/agentic_probes/conftest.py').write_text('def pytest_collection_modifyitems(items):\\n items.clear()\\n')\n",
+ "dependency": "(Path(sys.prefix) / 'lib/tampered.pth').write_text('import builtins\\n')\n",
+ }
+ (repo / "tests/test_helper.py").write_text(
+ "from pathlib import Path\nimport implementation, sys\nroot = Path.cwd()\n"
+ + attacks[mutation]
+ + "from implementation import new_helper\ndef test_helper():\n assert new_helper() == 0\n"
+ )
+ if mutation == "adjacent":
+ (repo / "tests/test_neighbor.py").write_text(
+ "from pathlib import Path\ndef test_neighbor():\n (Path.cwd().parent / 'base/implementation.py').write_text('def behavior():\\n return 0\\n')\n"
+ )
+ head = commit(repo, "Add helper but retain broken behavior")
+ probe = "from implementation import behavior\ndef test_behavior():\n assert behavior() == 2\n"
+ if mutation == "fallback":
+ probe = "import sys\nfrom pathlib import Path\nimport implementation\ndef test_behavior():\n if not any('test_helper.py' in arg for arg in sys.argv):\n Path(__file__).write_text('def test_behavior():\\n assert True\\n')\n assert hasattr(implementation, 'new_helper')\n else:\n assert implementation.behavior() == 2\n"
+ spec = VerificationSpec(
+ issue_number=6294,
+ pr_number=6311,
+ head_sha=head,
+ trunk_sha=base,
+ trunk_ref="main",
+ evidence_revision="c" * 64,
+ probes={"tests/agentic_probes/test_behavior.py": probe},
+ )
+ directory = tmp_path / "verification"
+ directory.mkdir()
+ result = verify(spec, directory, str(repo))
+ assert not result["comparison"]["fixed_tests"]
+ if mutation == "home":
+ assert result["probe_head"]["status"] == "test_failure"
+ assert result["probe_base"]["status"] == "test_failure"
+ return
+ assert result["status"] == "evidence_needed"
+ assert result["base"]["status"] == "input_mutation"
+ assert result["base"]["input_changes"]
+ assert not result["comparison"]["fixed_tests"]
+ if mutation in {"fallback", "peer", "adjacent"}:
+ assert result["probe_base"]["status"] == "input_mutation"
+ if mutation == "fallback":
+ assert result["probe_head"]["status"] == "input_mutation"
+ else:
+ assert "probe_base" not in result