"""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("")[-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().(*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("")[-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("")[-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