File size: 10,288 Bytes
ab59633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""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"}]