File size: 10,417 Bytes
e042d72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
"""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"}


@lru_cache(maxsize=1)
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


@lru_cache(maxsize=None)
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)