"""Software engineering: fix a bug in a small Python module so its tests pass (hidden tests too).""" from typing import Literal from pydantic import Field from ..core import Action, ProxyTask, Step, clip, run_python class RepoAction(Action): tool: Literal["list_files", "read_file", "write_file", "run_tests", "submit"] = Field( description="list_files, read_file (path), write_file (path, content: the full new file), " "run_tests, or submit when you are done (ends the episode).") path: str = Field(default="", description="File path for read_file / write_file.") content: str = Field(default="", description="Complete new file content for write_file.") BUGS = [ { # 1-indexed pagination off by one "module": "pager.py", "buggy": '''def paginate(items, page, per_page): """Return the items on a 1-indexed page.""" if page < 1 or per_page < 1: raise ValueError("page and per_page must be positive") start = page * per_page return items[start:start + per_page] ''', "fixed": '''def paginate(items, page, per_page): """Return the items on a 1-indexed page.""" if page < 1 or per_page < 1: raise ValueError("page and per_page must be positive") start = (page - 1) * per_page return items[start:start + per_page] ''', "visible": '''from pager import paginate items = list(range(1, {n})) assert paginate(items, 1, {k}) == items[:{k}], paginate(items, 1, {k}) assert paginate(items, 2, {k}) == items[{k}:{k2}] print("visible tests passed") ''', "hidden": '''from pager import paginate items = list("abcdefghij") assert paginate(items, 4, 3) == ["j"] assert paginate(items, 5, 3) == [] try: paginate(items, 0, 3) raise SystemExit("expected ValueError") except ValueError: pass print("hidden tests passed") ''', "issue": "Users report that the first page of results is skipped: page 1 shows what should be page 2.", }, { # duration parser ignores seconds "module": "durations.py", "buggy": '''import re UNITS = {"h": 3600, "m": 60} def parse_duration(text): """Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.""" total = 0 for amount, unit in re.findall(r"(\\d+)([hms])", text.strip().lower()): total += int(amount) * UNITS.get(unit, 0) return total ''', "fixed": '''import re UNITS = {"h": 3600, "m": 60, "s": 1} def parse_duration(text): """Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.""" total = 0 for amount, unit in re.findall(r"(\\d+)([hms])", text.strip().lower()): total += int(amount) * UNITS.get(unit, 0) return total ''', "visible": '''from durations import parse_duration assert parse_duration("{h}h{m}m") == {hm} assert parse_duration("{m}m{s}s") == {ms}, parse_duration("{m}m{s}s") print("visible tests passed") ''', "hidden": '''from durations import parse_duration assert parse_duration("2H5M10S") == 7510 assert parse_duration("90s") == 90 assert parse_duration("") == 0 print("hidden tests passed") ''', "issue": "Durations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.", }, { # dedupe loses order and case-folding "module": "contacts.py", "buggy": '''def dedupe_emails(emails): """Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.""" return list(set(e.strip() for e in emails)) ''', "fixed": '''def dedupe_emails(emails): """Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.""" seen, out = set(), [] for e in emails: key = e.strip().lower() if key not in seen: seen.add(key) out.append(e.strip()) return out ''', "visible": '''from contacts import dedupe_emails got = dedupe_emails(["{a}@x.org", " {b}@y.com", "{A}@X.org", "{c}@z.net"]) assert got == ["{a}@x.org", "{b}@y.com", "{c}@z.net"], got print("visible tests passed") ''', "hidden": '''from contacts import dedupe_emails assert dedupe_emails([]) == [] assert dedupe_emails(["B@b.io", "a@a.io", "b@B.IO ", "A@a.io"]) == ["B@b.io", "a@a.io"] print("hidden tests passed") ''', "issue": "The contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.", }, { # moving average drops the last window "module": "smooth.py", "buggy": '''def moving_average(values, window): """Average of each full window of `window` consecutive values.""" if window < 1: raise ValueError("window must be positive") return [sum(values[i:i + window]) / window for i in range(len(values) - window)] ''', "fixed": '''def moving_average(values, window): """Average of each full window of `window` consecutive values.""" if window < 1: raise ValueError("window must be positive") return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)] ''', "visible": '''from smooth import moving_average got = moving_average([{v}], 2) assert got == {want}, got print("visible tests passed") ''', "hidden": '''from smooth import moving_average assert moving_average([5], 1) == [5] assert moving_average([1, 2], 3) == [] assert moving_average([2, 4, 6], 3) == [4] print("hidden tests passed") ''', "issue": "The smoothed series is always one point shorter than it should be.", }, { # tier boundary uses > instead of >= "module": "pricing.py", "buggy": '''TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount) def discounted_total(total): """Apply the best discount tier whose minimum the order total reaches.""" for minimum, rate in TIERS: if total > minimum: return round(total * (1 - rate), 2) return round(total, 2) ''', "fixed": '''TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount) def discounted_total(total): """Apply the best discount tier whose minimum the order total reaches.""" for minimum, rate in TIERS: if total >= minimum: return round(total * (1 - rate), 2) return round(total, 2) ''', "visible": '''from pricing import discounted_total assert discounted_total({t}) == {tw} assert discounted_total(500) == 475.0, discounted_total(500) print("visible tests passed") ''', "hidden": '''from pricing import discounted_total assert discounted_total(1000) == 900.0 assert discounted_total(499.99) == 499.99 assert discounted_total(1200) == 1080.0 print("hidden tests passed") ''', "issue": "Customers whose order total is exactly a tier minimum (for example 500.00) get no discount.", }, ] class RepoFix(ProxyTask): family = "software-repofix" domain = "software-engineering" Action = RepoAction max_steps = 10 finish_action = {"tool": "submit"} def setup(self): bug = BUGS[self.seed % len(BUGS)] r = self.rng n, k = r.randint(12, 30), r.randint(3, 5) h, m, s = r.randint(1, 5), r.randint(1, 59), r.randint(1, 59) a, b, c = r.choice(["ana", "li", "omar"]), r.choice(["kim", "raj"]), r.choice(["zoe", "ben"]) vals = [r.randint(1, 9) * 2 for _ in range(r.randint(4, 6))] t = r.choice([1500, 2000, 1000.5]) fmt = dict(n=n, k=k, k2=2 * k, h=h, m=m, s=s, hm=h * 3600 + m * 60, ms=m * 60 + s, a=a, b=b, c=c, A=a.upper(), v=", ".join(map(str, vals)), want=[(vals[i] + vals[i + 1]) / 2 for i in range(len(vals) - 1)], t=t, tw=round(t * 0.9, 2)) test_name = "test_" + bug["module"] self.module = bug["module"] self.files = {bug["module"]: bug["buggy"], test_name: bug["visible"].format(**fmt), "ISSUE.md": f"# Bug report\n\n{bug['issue']}\n\nRun the tests with run_tests. " "Fix the module (not the tests).\n"} self.test_name = test_name self.hidden = bug["hidden"] self.fixed = bug["fixed"] def reset(self): return {"output": "You are working in a small Python repository. Read ISSUE.md, fix the bug in the " "module so all tests pass, then submit. Files: " + ", ".join(sorted(self.files)), "steps_left": self.max_steps} def _tests(self, hidden=False): files = dict(self.files) cmd = f"python {self.test_name}" if hidden: files["test_hidden.py"] = self.hidden cmd += " && python test_hidden.py" return run_python(files, ["sh", "-c", cmd]) def act(self, a): left = self.max_steps - self.steps if a.tool == "list_files": return Step({"output": "\n".join(sorted(self.files)), "steps_left": left}) if a.tool == "read_file": path = a.path.strip().lstrip("./") if path not in self.files: return Step({"output": f"No such file: {a.path}", "steps_left": left}) return Step({"output": clip(self.files[path]), "steps_left": left}) if a.tool == "write_file": path = a.path.strip().lstrip("./") if path.startswith("test_"): return Step({"output": "Tests are read-only; fix the module instead.", "steps_left": left}) if not path or not a.content: return Step({"output": "write_file needs path and content.", "steps_left": left}) self.files[path] = a.content return Step({"output": f"Wrote {len(a.content)} characters to {path}.", "steps_left": left}) if a.tool == "run_tests": code, out = self._tests() return Step({"output": f"exit code {code}\n{clip(out, 2000)}", "steps_left": left}) code, out = self._tests(hidden=True) return Step({"output": "Submitted.", "steps_left": 0}, True, 1.0 if code == 0 else 0.0) def oracle(self): return [{"tool": "read_file", "path": "ISSUE.md"}, {"tool": "read_file", "path": self.module}, {"tool": "write_file", "path": self.module, "content": self.fixed}, {"tool": "run_tests"}, {"tool": "submit"}]