#!/usr/bin/env python3 # -*- coding: utf-8 -*- r""" eval_code_sandbox.py ==================== Fast, isolated multiprocessing Python 3 execution sandbox for evaluating: 1. **HumanEval+** (`164` EvalPlus tasks) 2. **MBPP+** (`378` EvalPlus tasks) 3. **TurāthCode-50** (`50` identifier-morphology, API-contract, AST/compiler, systems, & Arabic-spec tasks) Every task runs in a clean child subprocess with strict wall-clock timeout (default `6.0s`) and clean stdout/stderr suppression so infinite loops, recursion overflows, or crashes never hang the harness. """ from __future__ import annotations import ast import concurrent.futures import json import os import re import subprocess import sys import tempfile import textwrap from pathlib import Path from typing import Any, Dict, List, Optional, Tuple _CODE_FENCE_RE = re.compile(r"```(?:python|py)?\s*\n(.*?)```", flags=re.DOTALL | re.IGNORECASE) _THINK_RE = re.compile(r".*?", flags=re.DOTALL) def extract_python_code(raw_output: str) -> str: """Robustly extracts Python code from fenced or raw LLM output (strictly post-).""" txt = _THINK_RE.sub("", raw_output) if "" in txt: txt = txt.rsplit("", 1)[-1] txt = txt.replace("<|im_end|>", "").strip() blocks = _CODE_FENCE_RE.findall(txt) if blocks: # Pick the longest valid-looking Python code block for b in sorted(blocks, key=len, reverse=True): b_clean = b.strip() try: ast.parse(b_clean) return b_clean except SyntaxError: pass return blocks[-1].strip() # Fallback: strip any leading prose before `def ` / `class ` / `import ` / `from ` lines = txt.splitlines() for idx, line in enumerate(lines): if re.match(r"^(?:from\s+\S+\s+import|import\s+\S+|def\s+|async\s+def\s+|class\s+|@)", line): return "\n".join(lines[idx:]).strip() return txt def _run_script_subprocess(script_code: str, timeout_sec: float = 6.0, use_temp_cwd: bool = False) -> Tuple[bool, str]: """Executes `script_code` in an isolated Python 3 child process with hard timeout.""" tmp_dir_obj = tempfile.TemporaryDirectory() if use_temp_cwd else None cwd_path = tmp_dir_obj.name if tmp_dir_obj is not None else None with tempfile.NamedTemporaryFile("w", suffix=".py", encoding="utf-8", delete=False, dir=cwd_path) as tf: tf.write(script_code) tmp_path = tf.name try: proc = subprocess.run( [sys.executable, "-I", tmp_path], cwd=cwd_path, capture_output=True, text=True, timeout=timeout_sec, env={"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "PYTHONHASHSEED": "0"}, ) if proc.returncode == 0: return True, "" err = (proc.stderr or proc.stdout or f"exit={proc.returncode}").strip() return False, err[-400:] except subprocess.TimeoutExpired: return False, f"TimeoutError: exceeded {timeout_sec:.1f}s" except Exception as e: return False, f"SandboxError: {type(e).__name__}: {e}" finally: try: os.unlink(tmp_path) except OSError: pass if tmp_dir_obj is not None: try: tmp_dir_obj.cleanup() except Exception: pass def eval_humaneval_plus_one(task: Dict[str, Any], generated_code: str, timeout_sec: float = 8.0) -> Tuple[bool, str]: """Evaluates a single HumanEval+ task against the full EvalPlus hardened `check(candidate)` harness.""" code = extract_python_code(generated_code) entry = task["entry_point"] # If model output omitted the function header and only emitted the indented body, prepend prompt! try: tree = ast.parse(code) has_entry = any( isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and n.name == entry for n in tree.body ) except SyntaxError: has_entry = False if not has_entry: # Try combining original HumanEval prompt header + raw completion combined = task["prompt"] + "\n" + textwrap.indent(code, " ") if not code.startswith((" ", "\t")) else task["prompt"] + code full_prog = f"{combined}\n\n{task['test']}\n\ncheck({entry})\n" else: # Keep imports from prompt (e.g. `from typing import List`) before model's full implementation prompt_imports = "\n".join( l for l in task["prompt"].splitlines() if l.startswith(("from ", "import ")) ) full_prog = f"{prompt_imports}\n{code}\n\n{task['test']}\n\ncheck({entry})\n" return _run_script_subprocess(full_prog, timeout_sec=timeout_sec) def eval_mbpp_plus_one(task: Dict[str, Any], generated_code: str, timeout_sec: float = 8.0) -> Tuple[bool, str]: """Evaluates a single MBPP+ task against the full EvalPlus hardened test script.""" code = extract_python_code(generated_code) imports = "\n".join(task.get("test_imports") or []) test_body = task.get("test") or "\n".join(task.get("test_list") or []) full_prog = f"{imports}\n{code}\n\n{test_body}\n" return _run_script_subprocess(full_prog, timeout_sec=timeout_sec) def eval_turath_code_one(task: Dict[str, Any], generated_code: str, timeout_sec: float = 6.0) -> Tuple[bool, str]: """Evaluates a single TurāthCode-50 task (with optional pre-provided `setup_code` library stubs).""" code = extract_python_code(generated_code) setup = task.get("setup_code", "") test_code = task["test_code"] full_prog = f"{setup}\n\n{code}\n\n{test_code}\n" return _run_script_subprocess(full_prog, timeout_sec=timeout_sec) def eval_bigcodebench_one(task: Dict[str, Any], generated_code: str, timeout_sec: float = 10.0) -> Tuple[bool, str]: """Evaluates a single BigCodeBench-Hard task against its full `unittest` suite in a clean temp cwd.""" code = extract_python_code(generated_code) entry = task.get("entry_point", "task_func") code_prompt = task.get("code_prompt", "") try: tree = ast.parse(code) has_entry = any( isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and n.name == entry for n in tree.body ) except SyntaxError: has_entry = False if not has_entry: combined = code_prompt + "\n" + textwrap.indent(code, " ") if not code.startswith((" ", "\t")) else code_prompt + code full_prog = f"{combined}\n\n{task['test']}\n\nif __name__ == '__main__':\n unittest.main()\n" else: prompt_imports = "\n".join( l for l in code_prompt.splitlines() if l.startswith(("from ", "import ")) ) full_prog = f"{prompt_imports}\n{code}\n\n{task['test']}\n\nif __name__ == '__main__':\n unittest.main()\n" return _run_script_subprocess(full_prog, timeout_sec=timeout_sec, use_temp_cwd=True) def evaluate_batch_parallel( suite_kind: str, tasks: List[Dict[str, Any]], outputs: List[str], max_workers: int = 8, timeout_sec: float = 8.0, ) -> Dict[str, Any]: """Evaluates an entire benchmark suite in parallel across CPU workers.""" fn_map = { "humaneval_plus": eval_humaneval_plus_one, "mbpp_plus": eval_mbpp_plus_one, "turath_code_50": eval_turath_code_one, "bigcodebench_hard": eval_bigcodebench_one, } eval_fn = fn_map[suite_kind] results: List[Dict[str, Any]] = [{} for _ in range(len(tasks))] with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as ex: fut_to_idx = { ex.submit(eval_fn, t, out, timeout_sec): i for i, (t, out) in enumerate(zip(tasks, outputs)) } for fut in concurrent.futures.as_completed(fut_to_idx): idx = fut_to_idx[fut] ok, err = fut.result() t = tasks[idx] results[idx] = { "task_id": str(t.get("task_id", t.get("id", idx))), "category": t.get("category", suite_kind), "passed": bool(ok), "error": err, } passed = sum(1 for r in results if r["passed"]) by_cat: Dict[str, Dict[str, int]] = {} for r in results: c = r["category"] by_cat.setdefault(c, {"passed": 0, "total": 0}) by_cat[c]["total"] += 1 if r["passed"]: by_cat[c]["passed"] += 1 return { "suite": suite_kind, "passed": passed, "total": len(tasks), "pass_at_1_pct": round(100.0 * passed / max(1, len(tasks)), 2), "by_category": {k: f"{v['passed']}/{v['total']}" for k, v in sorted(by_cat.items())}, "details": results, } def _self_test_evalplus() -> None: bdir = Path("/root/rootformer/stage15.2/data/stage18_1/benchmarks") he = [json.loads(l) for l in (bdir / "humanevalplus.jsonl").read_text().splitlines() if l.strip()] mb = [json.loads(l) for l in (bdir / "mbppplus.jsonl").read_text().splitlines() if l.strip()] # Verify canonical solutions on first 10 HumanEval+ and first 10 MBPP+ tasks he_sols = [t["prompt"] + t["canonical_solution"] for t in he[:10]] mb_sols = [t["code"] for t in mb[:10]] r_he = evaluate_batch_parallel("humaneval_plus", he[:10], he_sols, max_workers=6) r_mb = evaluate_batch_parallel("mbpp_plus", mb[:10], mb_sols, max_workers=6) print(f"SANDBOX_SELF_TEST: HumanEval+[:10]={r_he['passed']}/{r_he['total']} | MBPP+[:10]={r_mb['passed']}/{r_mb['total']}") assert r_he["passed"] == 10, f"HumanEval+ canonical failed: {[d for d in r_he['details'] if not d['passed']]}" assert r_mb["passed"] == 10, f"MBPP+ canonical failed: {[d for d in r_mb['details'] if not d['passed']]}" print("EVAL_CODE_SANDBOX_SELF_TEST_PASSED") if __name__ == "__main__": _self_test_evalplus()