File size: 18,220 Bytes
f93f1b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
"""Small agent test (ARCHITECTURE.md 6.6): QuixBugs Python, one `bash` tool, through llama-server tool calling.

  python3 agent.py --url http://127.0.0.1:PORT --version V --tasks /srv/prune/data/quixbugs --out /srv/prune/out \
      [--n 40] [--fetch]

Tasks: the 40 programs in python_programs/ minus node.py (a helper) and the nine *_test.py scripts (old test drivers):
  bitcount breadth_first_search bucketsort depth_first_search detect_cycle find_first_in_sorted find_in_sorted
  flatten gcd get_factors hanoi is_valid_parenthesization kheapsort knapsack kth lcs_length levenshtein lis
  longest_common_subsequence max_sublist_sum mergesort minimum_spanning_tree next_palindrome next_permutation
  pascal possible_change powerset quicksort reverse_linked_list rpn_eval shortest_path_length
  shortest_path_lengths shortest_paths shunting_yard sieve sqrt subsequences to_base topological_ordering wrap
Each task dir mirrors the repo layout so the repo's own pytest tests run unchanged: conftest.py,
python_programs/<id>.py, python_testcases/{test_<id>.py, load_testdata.py, node.py}, json_testcases/<id>.json.
correct_python_programs/ is never copied. Grading copies only the model's python_programs/<id>.py into a fresh
copy of the original tests and runs them with pytest-timeout (10 s per test). Slow cases are skipped exactly as the
repo does by default (no --runslow): the last knapsack case and the fourth levenshtein case.

Commands run in one throwaway container per task, `docker run -d --rm --network none -v <dir>:/work -w /work
prune-agent-py:1 sleep 900`, via `docker exec ... timeout 60 bash -lc <cmd>` (docker run per command took 8 s on a
loaded pod, exec 2 s). The image is python:3.12-slim plus pytest and pytest-timeout, built once. If Docker does not work, commands run locally as user `nobody` and the
summary says sandbox "local".

Output: <out>/per_problem/<V>__agent.jsonl, one line per task, resumable by id; last stdout line is the summary JSON.
"""
import argparse
import base64
import concurrent.futures as cf
import contextlib
import json
import os
import shlex
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
import uuid

IMAGE = 'prune-agent-py:1'
DOCKERFILE = b'FROM python:3.12-slim\nRUN pip install --no-cache-dir pytest==8.3.3 pytest-timeout==2.3.1\n'
TARBALL = 'https://codeload.github.com/jkoppel/QuixBugs/tar.gz/master'
MAX_TURNS, MAX_TOKENS, WALL_S, CMD_S, OUT_CHARS, GRADE_S = 20, 4000, 300, 60, 4000, 180
EFFORT = 0.2  # MAX_TOKENS, WALL_S and EFFORT can be changed from the command line (rerun arms)
WRITE_TOOL = False  # --write-tool: also offer write_file(path, content), so code need not travel in a heredoc
TOOLS = [{'type': 'function', 'function': {
    'name': 'bash',
    'description': 'Run a bash command in the task directory /work (no network, 60 s limit). Returns exit code and output.',
    'parameters': {'type': 'object', 'properties': {'command': {'type': 'string', 'description': 'The command to run'}},
                   'required': ['command']}}}]
WRITE = {'type': 'function', 'function': {
    'name': 'write_file',
    'description': 'Write a whole file in /work, replacing it. Give the full new file content as plain text.',
    'parameters': {'type': 'object', 'properties': {
        'path': {'type': 'string', 'description': 'Path relative to /work, e.g. python_programs/x.py'},
        'content': {'type': 'string', 'description': 'The complete new file content'}},
        'required': ['path', 'content']}}}
SYSTEM_W = ('You are a careful software engineer fixing a bug in a small Python program. You have two tools: bash, '
            'which runs a shell command in the task directory /work (Python 3.12 and pytest are installed; no network), '
            'and write_file, which replaces a whole file with the content you give. Use write_file to edit code. '
            'Work step by step: read the code, run the tests, edit the file, re-run the tests. '
            'When you are finished, reply with a one-line summary and no tool call.')
SYSTEM = ('You are a careful software engineer fixing a bug in a small Python program. You have one tool, bash, '
          'which runs a shell command in the task directory /work (Python 3.12 and pytest are installed; no network). '
          'Work step by step: read the code, run the tests, edit the file, re-run the tests. '
          'When you are finished, reply with a one-line summary and no tool call.')


def test_cmd(tid):
    return f'python -m pytest -q -p no:cacheprovider --timeout=10 python_testcases/test_{tid}.py'


def user_prompt(tid):
    return (f'The program python_programs/{tid}.py has a bug: it does not do what its tests expect.\n'
            f'Its tests are in python_testcases/test_{tid}.py (test data, if any, is in json_testcases/). '
            f'Run them from /work with:\n  {test_cmd(tid)}\n'
            f'Fix the bug in place by editing python_programs/{tid}.py '
            + ('(write the whole fixed file with write_file). ' if WRITE_TOOL else '(for example with python or sed). ') +
            f'Do not edit the tests. The bug is usually small.')


# ---------- tasks ----------

def fetch(dst):
    os.makedirs(dst, exist_ok=True)
    tgz = os.path.join(dst, 'quixbugs.tar.gz')
    subprocess.run(['curl', '-sSL', '--retry', '5', '-o', tgz, TARBALL], check=True)
    subprocess.run(['tar', '-xzf', tgz, '-C', dst, '--strip-components', '1'], check=True)


def task_ids(root):
    d = os.path.join(root, 'python_programs')
    return sorted(f[:-3] for f in os.listdir(d)
                  if f.endswith('.py') and f != 'node.py' and not f.endswith('_test.py'))


def prepare(root, tid, dst):
    """Copy one task's files (never correct_python_programs) into dst, keeping the repo layout."""
    files = ['conftest.py', f'python_programs/{tid}.py', f'python_testcases/test_{tid}.py',
             'python_testcases/load_testdata.py', 'python_testcases/node.py']
    if os.path.exists(os.path.join(root, f'json_testcases/{tid}.json')):
        files.append(f'json_testcases/{tid}.json')
    for f in files:
        os.makedirs(os.path.dirname(os.path.join(dst, f)), exist_ok=True)
        shutil.copy(os.path.join(root, f), os.path.join(dst, f))
    os.chmod(dst, 0o777)
    for base, dirs, fs in os.walk(dst):
        for x in dirs + fs:
            os.chmod(os.path.join(base, x), 0o777 if x in dirs else 0o666)


# ---------- sandbox ----------

def truncate(s, n=OUT_CHARS):
    return s if len(s) <= n else s[:n // 2] + f'\n...[{len(s) - n} chars cut]...\n' + s[-n // 2:]


@contextlib.contextmanager
def docker_box(workdir):
    """One container per task dir (cheaper than docker run per command); yields run(cmd, timeout) -> (rc, out).
    The container sleeps 900 s at most, so it goes away even if this process is killed."""
    name = 'prune-agent-' + uuid.uuid4().hex[:12]
    subprocess.run(['docker', 'run', '-d', '--rm', '--name', name, '--network', 'none', '--memory', '2g',
                    '--pids-limit', '256', '-v', f'{workdir}:/work', '-w', '/work', IMAGE, 'sleep', '900'],
                   capture_output=True, check=True)

    def run(cmd, timeout):
        t = max(1, int(timeout))
        try:
            p = subprocess.run(['docker', 'exec', name, 'timeout', '-k', '5', str(t), 'bash', '-lc', cmd],
                               capture_output=True, text=True, errors='replace', timeout=t + 30)
            out = p.stdout + p.stderr
            return p.returncode, out + (f'\n[timed out after {t} s]' if p.returncode in (124, 137) else '')
        except subprocess.TimeoutExpired:
            return 124, f'[timed out after {t} s]'
    try:
        yield run
    finally:
        subprocess.run(['docker', 'rm', '-f', name], capture_output=True)


@contextlib.contextmanager
def local_box(workdir):
    """Fallback without Docker: unprivileged user `nobody` (when root) in the task dir."""
    pre = ['runuser', '-u', 'nobody', '--'] if os.geteuid() == 0 else []

    def run(cmd, timeout):
        try:
            p = subprocess.run(pre + ['bash', '-c', cmd], cwd=workdir, capture_output=True, text=True,
                               errors='replace', timeout=timeout,
                               env={'PATH': f'{os.path.dirname(sys.executable)}:/usr/bin:/bin', 'HOME': workdir})
            return p.returncode, p.stdout + p.stderr
        except subprocess.TimeoutExpired:
            return 124, f'[timed out after {timeout:.0f} s]'
    yield run


def pick_box():
    if subprocess.run(['docker', 'image', 'inspect', IMAGE], capture_output=True).returncode != 0:
        subprocess.run(['docker', 'build', '-q', '-t', IMAGE, '-'], input=DOCKERFILE, capture_output=True)
    try:
        ok = subprocess.run(['docker', 'run', '--rm', '--network', 'none', IMAGE, 'python', '-m', 'pytest', '--version'],
                            capture_output=True, timeout=120).returncode == 0
    except Exception:
        ok = False
    return (docker_box, 'docker') if ok else (local_box, 'local')


# ---------- model ----------

def make_chat(url):
    def chat(messages, timeout):
        body = {'messages': messages, 'tools': TOOLS + ([WRITE] if WRITE_TOOL else []), 'max_tokens': MAX_TOKENS, 'temperature': 0,
                'chat_template_kwargs': {'reasoning_effort': EFFORT}}
        req = urllib.request.Request(url.rstrip('/') + '/v1/chat/completions', data=json.dumps(body).encode(),
                                     headers={'Content-Type': 'application/json'})
        return json.loads(urllib.request.urlopen(req, timeout=max(timeout, 1)).read())
    return chat


def parse_call(tc):
    """Return (command, None) for a valid bash call, else (None, error text).
    With WRITE_TOOL, a write_file call becomes a bash command that decodes the content from base64 into the file."""
    fn = (tc or {}).get('function') or {}
    names = ('bash', 'write_file') if WRITE_TOOL else ('bash',)
    if fn.get('name') not in names:
        return None, f'unknown tool {fn.get("name")!r}; the tools are {", ".join(names)}'
    args = fn.get('arguments')
    if isinstance(args, str):
        try:
            args = json.loads(args)
        except ValueError:
            return None, 'arguments are not valid JSON'
    if fn['name'] == 'write_file':
        if not isinstance(args, dict) or not isinstance(args.get('path'), str) or not isinstance(args.get('content'), str):
            return None, 'arguments must be {"path": "<relative path>", "content": "<file text>"}'
        path = args['path'].strip()
        if path.startswith('/work/'):
            path = path[6:]
        if not path or path.startswith('/') or '..' in path.split('/'):
            return None, 'path must be relative to /work'
        b64 = base64.b64encode(args['content'].encode()).decode()
        q = shlex.quote(path)
        return f'mkdir -p "$(dirname {q})" && echo {b64} | base64 -d > {q} && echo "wrote $(wc -c < {q}) bytes to {path}"', None
    if not isinstance(args, dict) or not isinstance(args.get('command'), str) or not args['command'].strip():
        return None, 'arguments must be {"command": "<non-empty string>"}'
    return args['command'], None


def session(tid, run, chat, clock=time.monotonic, log=None):
    """Run one agent session; run(cmd, timeout) executes a command in the task dir. Returns {turns, tokens, invalid_tool_calls, hit_limit, err}.
    If log is a list, every model turn (with its reasoning text and token counts) and tool output is appended to it."""
    t0 = clock()
    msgs = [{'role': 'system', 'content': SYSTEM_W if WRITE_TOOL else SYSTEM}, {'role': 'user', 'content': user_prompt(tid)}]
    r = {'turns': 0, 'tokens': 0, 'invalid_tool_calls': 0, 'hit_limit': None, 'err': None}
    while True:
        left = WALL_S - (clock() - t0)
        if left <= 0:
            r['hit_limit'] = 'wall'
            break
        if r['turns'] >= MAX_TURNS:
            r['hit_limit'] = 'turns'
            break
        try:
            d = chat(msgs, left)
        except Exception as e:
            r['err'] = f'{type(e).__name__}: {e}'[:200]
            r['hit_limit'] = 'wall' if WALL_S - (clock() - t0) <= 0 else None
            break
        r['turns'] += 1
        r['tokens'] += (d.get('usage') or {}).get('completion_tokens', 0)
        c = d['choices'][0]
        m = c.get('message') or {}
        calls = m.get('tool_calls') or []
        if log is not None:
            u = d.get('usage') or {}
            log.append({'turn': r['turns'], 'finish': c.get('finish_reason'), 'prompt_tokens': u.get('prompt_tokens'),
                        'completion_tokens': u.get('completion_tokens'), 'reasoning': m.get('reasoning_content'),
                        'content': m.get('content'), 'tool_calls': calls})
        if c.get('finish_reason') == 'length':
            r['hit_limit'] = 'max_tokens'
            break
        if not calls:
            break
        msgs.append({'role': 'assistant', 'content': m.get('content') or '', 'tool_calls': calls})
        for i, tc in enumerate(calls):
            cmd, bad = parse_call(tc)
            if bad:
                r['invalid_tool_calls'] += 1
                out = 'error: ' + bad
            else:
                left = WALL_S - (clock() - t0)
                rc, txt = run(cmd, max(1, min(CMD_S, left)))
                out = truncate(f'exit code {rc}\n{txt}')
            if log is not None:
                log.append({'tool_out': out})
            msgs.append({'role': 'tool', 'tool_call_id': tc.get('id') or f'call_{r["turns"]}_{i}', 'content': out})
    return r


def grade(root, tid, workdir, box):
    """Fresh copy of the original tests plus the model's program; True if all tests pass."""
    with tempfile.TemporaryDirectory(prefix=f'qb_grade_{tid}_') as g:
        prepare(root, tid, g)
        shutil.copy(os.path.join(workdir, f'python_programs/{tid}.py'), os.path.join(g, f'python_programs/{tid}.py'))
        with box(g) as run:
            rc, _ = run(test_cmd(tid), GRADE_S)
        return rc == 0


def run_task(root, tid, chat, box, tdir=None):
    log = [] if tdir else None
    with tempfile.TemporaryDirectory(prefix=f'qb_{tid}_') as w:
        prepare(root, tid, w)
        with box(w) as run:
            r = session(tid, run, chat, log=log)
        if tdir and os.path.exists(os.path.join(w, f'python_programs/{tid}.py')):
            log.append({'final_program': open(os.path.join(w, f'python_programs/{tid}.py')).read()})
        try:
            ok = grade(root, tid, w, box)
        except FileNotFoundError:  # the model deleted its program
            ok = False
    row = {'id': tid, 'ok': ok, 'turns': r['turns'], 'tokens': r['tokens'],
           'invalid_tool_calls': r['invalid_tool_calls'], 'hit_limit': r['hit_limit']}
    if r['err']:
        row['err'] = r['err']
    if tdir:
        os.makedirs(tdir, exist_ok=True)
        json.dump({**row, 'log': log}, open(os.path.join(tdir, f'{tid}.json'), 'w'), indent=1)
    return row


def summarize(version, rows):
    n = len(rows)
    correct = sum(bool(x['ok']) for x in rows)
    return {'version': version, 'test': 'agent', 'n': n, 'correct': correct,
            'score': round(correct / n, 4) if n else 0.0,
            'invalid_tool_calls': sum(x['invalid_tool_calls'] for x in rows),
            'mean_turns': round(sum(x['turns'] for x in rows) / n, 2) if n else 0.0,
            'mean_tokens': round(sum(x['tokens'] for x in rows) / n, 1) if n else 0.0,
            'hit_limit': sum(1 for x in rows if x['hit_limit'])}


def run(url, version, root, out, n, chat=None, box=None, workers=12, shard=None, transcripts=False):
    ids = task_ids(root)[:n]
    if shard:  # 'k/m': this process takes every m-th task starting at k
        k, m = map(int, shard.split('/'))
        ids = ids[k::m]
    tdir = os.path.join(out, 'transcripts', version) if transcripts else None
    path = os.path.join(out, 'per_problem', f'{version}__agent.jsonl')
    os.makedirs(os.path.dirname(path), exist_ok=True)
    done = {}
    if os.path.exists(path):
        for line in open(path):
            if line.strip():
                x = json.loads(line)
                done[x['id']] = x
    sandbox = 'given'
    if box is None:
        box, sandbox = pick_box()
        print(json.dumps({'sandbox': sandbox}), file=sys.stderr)
    chat = chat or make_chat(url)
    lock = threading.Lock()

    def one(tid):
        row = run_task(root, tid, chat, box, tdir)
        with lock, open(path, 'a') as f:
            f.write(json.dumps(row) + '\n')
            done[tid] = row
        print(json.dumps(row), file=sys.stderr)

    todo = [t for t in ids if t not in done]
    with cf.ThreadPoolExecutor(workers) as ex:
        list(ex.map(one, todo))
    s = summarize(version, [done[t] for t in ids])
    s['sandbox'] = sandbox
    return s


def main():
    global MAX_TOKENS, WALL_S, EFFORT, WRITE_TOOL
    ap = argparse.ArgumentParser()
    ap.add_argument('--url', required=True)
    ap.add_argument('--version', required=True)
    ap.add_argument('--tasks', required=True)
    ap.add_argument('--out', required=True)
    ap.add_argument('--n', type=int, default=40)
    ap.add_argument('--fetch', action='store_true')
    ap.add_argument('--max-tokens', type=int, default=MAX_TOKENS)
    ap.add_argument('--wall', type=int, default=WALL_S)
    ap.add_argument('--effort', type=float, default=EFFORT)
    ap.add_argument('--workers', type=int, default=12)
    ap.add_argument('--shard', help='k/m: run every m-th task from k')
    ap.add_argument('--write-tool', action='store_true', help='also offer write_file(path, content)')
    ap.add_argument('--transcripts', action='store_true', help='save every turn to <out>/transcripts/<version>/')
    a = ap.parse_args()
    MAX_TOKENS, WALL_S, EFFORT, WRITE_TOOL = a.max_tokens, a.wall, a.effort, a.write_tool
    if a.fetch:
        fetch(a.tasks)
    ids = task_ids(a.tasks)
    if len(ids) != 40:
        sys.exit(f'expected 40 QuixBugs Python programs, found {len(ids)}')
    print(json.dumps(run(a.url, a.version, a.tasks, a.out, a.n, workers=a.workers, shard=a.shard, transcripts=a.transcripts)))


if __name__ == '__main__':
    main()