Download source/codedesk/families/bugfix.py from rca-umb/five-desks-code: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/rca-umb/five-desks-code/resolve/main/source/codedesk/families/bugfix.py
- Command line
-
hf download hf://datasets/rca-umb/five-desks-code/source/codedesk/families/bugfix.py
-
curl -L -o bugfix.py https://huggingface.co/datasets/rca-umb/five-desks-code/resolve/main/source/codedesk/families/bugfix.py
10.4 kB
| """Fix a real bug in a real library. | |
| Each instance takes one pinned open-source Python library and one mutant from the build-time catalog: a single | |
| token changed inside a function (a comparison, an operator, a constant, and/or, a `not`) that 1 to 8 of the | |
| library's own tests catch. Level 1 is a failing CI run: the test suite is in the repository and the issue shows | |
| the failing test's output. Level 2 is a user report: the issue shows only the failing check, and the tests that | |
| cover it are removed from the repository, so the policy has to find the code and verify its fix itself. | |
| Grading copies only the library's own source files from the workspace into a clean copy of the original project | |
| and runs the original test files that cover the bug: every catching test must pass and no other test in those | |
| files may fail that passes on the original. Edits to tests, configuration or anything else are ignored. | |
| """ | |
| import ast | |
| import json | |
| import re | |
| import shutil | |
| import tempfile | |
| import xml.etree.ElementTree as ET | |
| from functools import lru_cache | |
| from pathlib import Path | |
| from .. import runner | |
| from ..base import CodingTask, Tool | |
| DATA = Path(__file__).resolve().parents[1] / "data" | |
| # library -> (package path in the source tree, task group) | |
| LIBS = { | |
| "croniter": ("src/croniter", "office"), "isodate": ("src/isodate", "office"), "humanize": ("src/humanize", "office"), | |
| "numpy_financial": ("numpy_financial", "finance"), "uncertainties": ("uncertainties", "science"), | |
| "fluids": ("fluids", "industrial"), "srt": ("srt.py", "media"), "webvtt": ("webvtt", "media"), | |
| "slugify": ("slugify", "media"), "itsdangerous": ("src/itsdangerous", "security"), "jwt": ("jwt", "security"), | |
| "toolz": ("toolz", "software"), "tabulate": ("tabulate", "software"), "inflection": ("inflection", "software"), | |
| "semver": ("src/semver", "software"), "more_itertools": ("more_itertools", "math"), | |
| } | |
| DOMAINS = {"office": "office-white-collar", "finance": "finance-economics", "science": "natural-science", | |
| "industrial": "industrial-physical-systems", "media": "media-content-production", | |
| "security": "cybersecurity", "software": "software-engineering", "math": "mathematics-or-formal-reasoning"} | |
| SKIP = {".egg-info", "docs", ".github", "PKG-INFO", "__pycache__", "benchmarks", "examples"} | |
| def catalog() -> list[dict]: | |
| path = DATA / "catalog.json" | |
| return json.loads(path.read_text()) if path.exists() else [] | |
| def pytest_outcomes(root: Path, files: list[str]) -> dict | None: | |
| """Run the given test files under root as nobody; {test key: passed/failed/skipped}, or None if pytest crashed.""" | |
| xml = root / ".grade.xml" | |
| runner.run("python -m pytest -q -p no:cacheprovider -p no:randomly --tb=no --hypothesis-seed=0 " | |
| f"--junitxml={xml} -o junit_family=xunit1 " + " ".join(files), root, timeout=240) | |
| if not xml.exists(): | |
| return None | |
| outcomes = {} | |
| for case in ET.parse(xml).getroot().iter("testcase"): | |
| key = f"{case.get('file') or case.get('classname')}::{case.get('name')}" | |
| kids = {c.tag for c in case} | |
| outcomes[key] = "failed" if kids & {"failure", "error"} else "skipped" if "skipped" in kids else "passed" | |
| return outcomes | |
| def owned_tmp(prefix: str) -> tempfile.TemporaryDirectory: | |
| tmp = tempfile.TemporaryDirectory(prefix=prefix) | |
| if runner.AS_ROOT: | |
| import os | |
| os.chown(tmp.name, runner.NOBODY, runner.NOBODY) | |
| return tmp | |
| def pristine_outcomes(lib: str, files: tuple[str, ...]) -> dict: | |
| """Outcomes of the same test files on the original library, in this image (tests can depend on run order).""" | |
| with owned_tmp("pristine-") as tmp: | |
| root = Path(tmp) / "repo" | |
| copy_tree(DATA / "libs" / lib, root) | |
| runner.give_to_nobody(Path(tmp)) | |
| return pytest_outcomes(root, list(files)) or {} | |
| def groups() -> list[str]: | |
| present = {LIBS[m["lib"]][1] for m in catalog() if m["lib"] in LIBS} | |
| return [g for g in DOMAINS if g in present] | |
| def copy_tree(src: Path, dst: Path): | |
| def ignore(_, names): | |
| return [n for n in names if n in SKIP or n.endswith(".egg-info") or n.startswith(".")] | |
| shutil.copytree(src, dst, ignore=ignore, dirs_exist_ok=True) | |
| def mutate(text: str, m: dict) -> str: | |
| lines = text.splitlines(keepends=True) | |
| line = lines[m["line"] - 1] | |
| assert line[m["col"]:m["col"] + len(m["old"])] == m["old"], m | |
| lines[m["line"] - 1] = line[:m["col"]] + m["new"] + line[m["col"] + len(m["old"]):] | |
| return "".join(lines) | |
| def test_file(key: str) -> str: | |
| return key.split("::")[0] | |
| def test_name(key: str) -> str: | |
| return key.split("::")[-1].split("[")[0] | |
| def remove_tests(path: Path, names: set[str]): | |
| """Delete the named test functions (with their decorators) from a test file, keeping everything else.""" | |
| src = path.read_text() | |
| tree = ast.parse(src) | |
| spans = [] | |
| for node in ast.walk(tree): | |
| if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names: | |
| first = min([node.lineno] + [d.lineno for d in node.decorator_list]) | |
| spans.append((first, node.end_lineno)) | |
| lines = src.splitlines(keepends=True) | |
| for first, last in sorted(spans, reverse=True): | |
| del lines[first - 1:last] | |
| path.write_text("".join(lines)) | |
| def symptom(failure: str) -> str: | |
| """The failing check from pytest's short traceback, without the test's name or location.""" | |
| keep, grab = [], False | |
| for line in failure.splitlines(): | |
| if re.match(r"^\S+\.py:\d+: in ", line): | |
| grab = True | |
| continue | |
| if grab and line.startswith(" ") and not line.startswith(" E"): | |
| keep.append(line.strip()) | |
| elif line.startswith("E "): | |
| keep.append(line[1:].strip()) | |
| if sum(1 for k in keep if k.startswith(("AssertionError", "assert", "+", "-", "Error", "Value", "Type", "Key", | |
| "Index", "Attribute"))) > 4: | |
| break | |
| elif line.startswith(("=", "_")) and keep: | |
| break | |
| return "\n".join(keep[-8:]) | |
| class LibBugfix(CodingTask): | |
| family = "bugfix" | |
| levels = (1, 2) | |
| max_steps = 30 | |
| def setup(self): | |
| pool = [m for m in catalog() if LIBS.get(m["lib"], (None, None))[1] == self.group] | |
| if self.level == 2: # needs a readable check for the report | |
| pool = [m for m in pool if symptom(m["failure"]).count("\n") >= 1] or pool | |
| assert pool, f"no mutants for {self.group}" | |
| self.m = m = self.opts.get("mutant") or self.rng.choice(pool) # tests and validation can pick one | |
| self.domain = DOMAINS[self.group] | |
| self.lib_root = DATA / "libs" / m["lib"] | |
| self.pkg = LIBS[m["lib"]][0] | |
| copy_tree(self.lib_root, self.ws) | |
| target = self.ws / m["file"] | |
| self.original = target.read_text() | |
| target.write_text(mutate(self.original, m)) | |
| self.killed = m["killed"] | |
| if self.level == 2: | |
| by_file = {} | |
| for key in self.killed: | |
| by_file.setdefault(test_file(key), set()).add(test_name(key)) | |
| for rel, names in by_file.items(): | |
| if (self.ws / rel).exists(): | |
| remove_tests(self.ws / rel, names) | |
| failing = self.killed[0] | |
| if self.level == 1: | |
| report = (f"# CI failure\n\nThe test suite fails on main. One failing test:\n\n pytest '{failing}'\n\n" | |
| f"```\n{m['failure'].strip()[-2500:]}\n```\n\nFix the library (not the tests).\n") | |
| else: | |
| report = ("# Bug report\n\nA user reports that this check fails on the current version:\n\n" | |
| f"```\n{symptom(m['failure'])}\n```\n\nThe expected behaviour is the one the check asserts. Fix " | |
| "the library; the test suite has no test for this yet.\n") | |
| (self.ws / "ISSUE.md").write_text(report) | |
| def brief(self): | |
| name = self.m["lib"].replace("_", "-") | |
| how = ("Run the failing test, find the cause in the library code, fix it" if self.level == 1 else | |
| "Reproduce the problem, find the cause in the library code, fix it") | |
| return (f"SOFTWARE ({self.group}). This repository is the open-source Python library {name}. Read ISSUE.md. " | |
| f"{how}, check that nothing else breaks, then submit. Only changes to the library's own source " | |
| f"({self.pkg}) count.") | |
| def tools(self): | |
| return self.coding_tools(tests=True) + [Tool("submit", "submit your fix (ends the episode)", self.grade, | |
| final=True)] | |
| def grade(self, a=None) -> float: | |
| with owned_tmp("grade-") as tmp: | |
| root = Path(tmp) / "repo" | |
| copy_tree(self.lib_root, root) | |
| src, dst = self.ws / self.pkg, root / self.pkg | |
| # never follow links out of the workspace (the grader runs as root) | |
| if src.is_symlink() or (src.is_dir() and any(p.is_symlink() for p in src.rglob("*"))): | |
| return 0.0 | |
| if src.is_file(): | |
| shutil.copyfile(src, dst) | |
| elif src.is_dir(): | |
| shutil.rmtree(dst) | |
| shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "conftest.py")) | |
| else: | |
| return 0.0 | |
| # some libraries keep their tests inside the package: always grade with the original tests | |
| tests = self.lib_root / self.m["tests_root"] | |
| if tests.is_dir(): | |
| shutil.rmtree(root / self.m["tests_root"], ignore_errors=True) | |
| copy_tree(tests, root / self.m["tests_root"]) | |
| elif tests.is_file(): | |
| shutil.copyfile(tests, root / self.m["tests_root"]) | |
| runner.give_to_nobody(Path(tmp)) | |
| files = sorted({test_file(k) for k in self.killed}) | |
| outcomes = pytest_outcomes(root, files) | |
| if outcomes is None or any(outcomes.get(k) != "passed" for k in self.killed): | |
| return 0.0 | |
| base = pristine_outcomes(self.m["lib"], tuple(files)) | |
| return float(not [k for k, v in outcomes.items() if v == "failed" and base.get(k) == "passed"]) | |
| def oracle(self): | |
| (self.ws / self.m["file"]).write_text(self.original) | |