File size: 10,402 Bytes
2f04653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
daf7aaa
 
 
 
2f04653
 
 
 
 
daf7aaa
 
 
2f04653
 
 
 
 
daf7aaa
2f04653
daf7aaa
2f04653
 
 
 
daf7aaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f04653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Answer verifiers for distillation data: sandboxed Python unit tests + IFEval-style constraints."""
from __future__ import annotations

import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Optional

# ----------------------------------------------------------------------------- code
_CODE_BLOCK = re.compile(r"```(?:python|py|Python)?[ \t]*\n(.*?)```", re.S)


def extract_code(text: str) -> Optional[str]:
    blocks = _CODE_BLOCK.findall(text.split("</think>")[-1])
    if not blocks:
        return None
    # prefer the longest block that defines something (models sometimes add usage snippets)
    defs = [b for b in blocks if re.search(r"^\s*(def|class) ", b, re.M)]
    return max(defs or blocks, key=len)


def run_sandboxed(files: dict[str, str], argv: str, timeout: int = 30, mem_mb: int = 2048) -> tuple[int, str, str]:
    """Write `files` into a fresh directory and run the shell command `argv` there in a bubblewrap
    sandbox: read-only root, private /tmp, no network, time + memory + file-size limits.
    Returns (returncode, stdout, stderr); returncode -1 means the sandbox itself timed out."""
    bwrap = shutil.which("bwrap")
    if bwrap is None:
        raise RuntimeError("bubblewrap (bwrap) is required to execute generated code safely")
    work = Path(tempfile.mkdtemp(prefix="looped_sbx_"))
    try:
        for name, text in files.items():
            (work / name).write_text(text)
        inner = f"ulimit -v {mem_mb * 1024}; ulimit -f 10240; exec timeout -k 2 {timeout} {argv}"
        cmd = [bwrap, "--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp",
               "--bind", str(work), str(work), "--chdir", str(work), "--unshare-all", "--die-with-parent",
               "--new-session", "--setenv", "HOME", str(work), "--", "/bin/sh", "-c", inner]
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout + 15,
                           env={"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "LANG": "C.UTF-8"})
        return r.returncode, r.stdout, r.stderr
    except subprocess.TimeoutExpired:
        return -1, "", "timeout"
    finally:
        shutil.rmtree(work, ignore_errors=True)


def run_pytest_sandboxed(solution: str, test_code: str, timeout: int = 30, mem_mb: int = 2048) -> tuple[bool, str]:
    """Run `test_code` (which does `from solution import ...`) against `solution` in the sandbox."""
    # Some KodCode test files use the solution's functions without importing them (their own
    # reference solutions fail otherwise); a star-import puts those names in scope. The tests'
    # assertions are unchanged.
    files = {"solution.py": solution, "test_solution.py": "from solution import *  # noqa\n" + test_code}
    rc, out, err = run_sandboxed(files, f"{sys.executable} -I -m pytest -q -x -p no:cacheprovider --no-header "
                                        f"-o addopts='' test_solution.py", timeout, mem_mb)
    return rc == 0, ("timeout" if rc == -1 else (out + err)[-500:])


# ----------------------------------------------------------------------------- competitive programming
_ANY_BLOCK = re.compile(r"```(?:python3?|py|Python)?[ \t]*\n(.*?)```", re.S)

LEETCODE_HEADER = ("from typing import *\nfrom collections import *\nfrom functools import *\nfrom itertools import *\n"
                   "from heapq import *\nfrom bisect import *\nimport math, string, re, sys, heapq, bisect, "
                   "itertools, functools, collections\nsys.setrecursionlimit(1 << 20)\n")

# Runs *inside* the sandbox. stdin problems: one fresh interpreter per test. LeetCode-style
# ("functional") problems: call Solution().<func>(*args) with a per-test alarm. Stops at the first
# failure; prints one JSON line.
_CP_RUNNER = r"""
import json, signal, subprocess, sys
spec = json.load(open("tests.json"))
cases, per = spec["cases"], spec["per_test_timeout"]

def lines(s):
    return [l.strip() for l in s.strip().splitlines()]

def tok_equal(u, v):
    if u == v:
        return True
    try:
        return abs(float(u) - float(v)) <= 1e-6 * max(1.0, abs(float(v)))
    except ValueError:
        return False

def same(out, exp):
    a, b = lines(out), lines(exp)
    if a == b:
        return True
    if len(a) != len(b):
        return False
    for x, y in zip(a, b):
        xs, ys = x.split(), y.split()
        if len(xs) != len(ys) or not all(tok_equal(p, q) for p, q in zip(xs, ys)):
            return False
    return True

def done(k, why=""):
    print(json.dumps({"passed": k, "total": len(cases), "fail": why[:300]}))
    sys.exit(0)

if spec["kind"] == "stdin":
    for k, c in enumerate(cases):
        try:
            r = subprocess.run([sys.executable, "solution.py"], input=c["input"], capture_output=True,
                               text=True, timeout=per)
        except subprocess.TimeoutExpired:
            done(k, "timeout")
        if r.returncode != 0:
            done(k, "runtime error: " + r.stderr[-200:])
        if not same(r.stdout, c["output"]):
            done(k, "wrong answer")
    done(len(cases))
else:
    def alarm(*_):
        raise TimeoutError()
    signal.signal(signal.SIGALRM, alarm)
    ns = {}
    try:
        exec(compile(open("solution.py").read(), "solution.py", "exec"), ns)
        fn = getattr(ns["Solution"](), spec["func_name"])
    except BaseException as e:
        done(0, "load error: " + repr(e))
    for k, c in enumerate(cases):
        try:
            args = [json.loads(x) for x in c["input"].split("\n") if x.strip()]
            exp = json.loads(c["output"])
            signal.alarm(per)
            got = fn(*args)
            signal.alarm(0)
            got = json.loads(json.dumps(got))
        except TimeoutError:
            done(k, "timeout")
        except BaseException as e:
            signal.alarm(0)
            done(k, "runtime error: " + repr(e))
        if got != exp and not (isinstance(got, float) and isinstance(exp, (int, float))
                               and abs(got - exp) <= 1e-6 * max(1.0, abs(exp))):
            done(k, "wrong answer")
    done(len(cases))
"""


def extract_last_code(text: str) -> Optional[str]:
    """Last fenced code block of the final answer (competitive-programming answers put the
    final program last)."""
    blocks = _ANY_BLOCK.findall(text.split("</think>")[-1])
    return blocks[-1] if blocks else None


def run_cp_tests(code: str, kind: str, cases: list[dict], func_name: Optional[str] = None,
                 per_test_timeout: int = 6, total_timeout: int = 180) -> tuple[bool, str]:
    """Run a LiveCodeBench-style program against all its test cases in the sandbox."""
    if kind == "functional":
        code = LEETCODE_HEADER + code
    spec = {"kind": kind, "cases": cases, "func_name": func_name, "per_test_timeout": per_test_timeout}
    rc, out, err = run_sandboxed({"solution.py": code, "tests.json": json.dumps(spec), "runner.py": _CP_RUNNER},
                                 f"{sys.executable} -I runner.py", total_timeout)
    if rc == -1 or not out.strip():
        return False, "timeout" if rc in (-1, 124) else err[-300:]
    try:
        res = json.loads(out.strip().splitlines()[-1])
    except ValueError:
        return False, out[-300:]
    return res["passed"] == res["total"], f"{res['passed']}/{res['total']} {res['fail']}"


# ----------------------------------------------------------------------------- instruction following
def _words(t: str) -> list[str]:
    return re.findall(r"\b\w+\b", t)


def _sentences(t: str) -> list[str]:
    return [s for s in re.split(r"(?<=[.!?])\s+", t.strip()) if s.strip()]


def _cmp(n: int, N: int, q: Optional[str]) -> Optional[bool]:
    if q == "at least":
        return n >= N
    if q in ("at most", "less than"):
        return n <= N if q == "at most" else n < N
    return None  # 'around' etc.: ambiguous -> unsupported


def check_ifeval(text: str, gt: dict) -> Optional[bool]:
    """True/False for supported constraint types, None if unsupported (skip the item)."""
    t = text.split("</think>")[-1].strip()
    f = gt["func_name"]
    N, q = gt.get("N"), gt.get("quantifier")
    if f == "validate_lowercase":
        return t == t.lower() and any(c.isalpha() for c in t)
    if f == "validate_uppercase":
        return t == t.upper() and any(c.isalpha() for c in t)
    if f == "validate_no_commas":
        return "," not in t
    if f == "validate_quotation":
        return len(t) > 2 and t[0] == '"' and t[-1] == '"'
    if f == "validate_json_format":
        s = t
        if s.startswith("```"):
            s = re.sub(r"^```(json)?\s*|\s*```$", "", s)
        try:
            json.loads(s)
            return True
        except ValueError:
            return False
    if f == "validate_end":
        return t.endswith(gt["end_phrase"].strip())
    if f == "validate_title":
        return re.search(r"<<[^<>\n]+>>", t) is not None
    if f == "validate_forbidden_words":
        low = t.lower()
        return not any(re.search(r"\b" + re.escape(w.lower()) + r"\b", low) for w in gt["forbidden_words"])
    if f == "verify_keywords":
        low = t.lower()
        return all(w.lower() in low for w in gt["keyword_list"])
    if f == "verify_postscript":
        return re.search(r"^\s*" + re.escape(gt["postscript_marker"]), t, re.M) is not None
    if f == "validate_placeholders":
        return len(re.findall(r"\[[^\[\]\n]+\]", t)) >= N
    if f == "verify_bullet_points":
        return len(re.findall(r"^\s*[*-]\s", t, re.M)) == N
    if f == "validate_highlighted_sections":
        return len(re.findall(r"\*[^\n*]+\*", t)) >= N
    if f == "validate_sections":
        return len(re.findall(re.escape(gt["section_splitter"]) + r"\s*\d+", t)) == N
    if f == "validate_two_responses":
        parts = [p.strip() for p in t.split("******")]
        return len(parts) == 2 and all(parts) and parts[0] != parts[1]
    if f == "verify_paragraph_count":
        return len([p for p in re.split(r"\s*\*\s\*\s\*\s*", t) if p.strip()]) == N
    if f == "validate_word_constraint":
        return _cmp(len(_words(t)), N, q)
    if f == "verify_sentence_constraint":
        return _cmp(len(_sentences(t)), N, q)
    if f == "validate_frequency_capital_words":
        return _cmp(len([w for w in _words(t) if len(w) > 1 and w.isupper()]), N, q)
    return None