Datasets:
Download klein_code_bench/runner.py from klein-ml/klein-code-bench: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/datasets/klein-ml/klein-code-bench/resolve/main/klein_code_bench/runner.py
- Command line
-
hf download hf://datasets/klein-ml/klein-code-bench/klein_code_bench/runner.py
-
curl -L -o runner.py https://huggingface.co/datasets/klein-ml/klein-code-bench/resolve/main/klein_code_bench/runner.py
12.5 kB
| """Dependency-free local evaluator. This is process isolation, NOT a security sandbox.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import selectors | |
| import shutil | |
| import signal | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| DATA = Path(__file__).parent / "data" | |
| MAX_OUTPUT = 1_048_576 | |
| EXCLUDED = {".git", ".venv", "venv", "__pycache__", "node_modules", ".env"} | |
| def load_tasks(subset=None, data_dir=None): | |
| root = Path(data_dir) if data_dir else DATA | |
| tiers = [subset] if subset else ["easy", "intermediate", "hard", "max"] | |
| if any(t not in {"easy", "intermediate", "hard", "max"} for t in tiers): | |
| raise ValueError("Unknown subset") | |
| for tier in tiers: | |
| for line in (root / f"{tier}.jsonl").read_text(encoding="utf-8").splitlines(): | |
| if line.strip(): | |
| yield json.loads(line) | |
| def find_task(task_id, data_dir=None): | |
| for row in load_tasks(data_dir=data_dir): | |
| if row["task_id"] == task_id: | |
| return row | |
| raise ValueError(f"Unknown task: {task_id}") | |
| def equal(actual, expected): | |
| if isinstance(expected, bool) or expected is None or isinstance(expected, str): | |
| return type(actual) is type(expected) and actual == expected | |
| if type(expected) in (int, float): | |
| if type(actual) not in (int, float): | |
| return False | |
| if type(actual) is int and type(expected) is int: | |
| return actual == expected | |
| return ( | |
| math.isfinite(actual) | |
| and math.isfinite(expected) | |
| and math.isclose(actual, expected, rel_tol=1e-9, abs_tol=1e-9) | |
| ) | |
| if isinstance(expected, list): | |
| return ( | |
| isinstance(actual, list) | |
| and len(actual) == len(expected) | |
| and all(equal(a, b) for a, b in zip(actual, expected)) | |
| ) | |
| if isinstance(expected, dict): | |
| return ( | |
| isinstance(actual, dict) | |
| and actual.keys() == expected.keys() | |
| and all(equal(actual[k], expected[k]) for k in expected) | |
| ) | |
| return False | |
| def strict_json(line): | |
| def invalid(value): | |
| raise ValueError(f"Nonfinite JSON constant: {value}") | |
| return json.loads(line, parse_constant=invalid) | |
| def kill_group(process): | |
| if os.name == "posix": | |
| try: | |
| os.killpg(process.pid, signal.SIGKILL) | |
| except ProcessLookupError: | |
| pass | |
| elif process.poll() is None: | |
| process.kill() | |
| process.wait() | |
| def child_environment(home): | |
| # Do not inherit credentials, PYTHONPATH, proxies, or user site configuration. | |
| return { | |
| "PATH": os.defpath, | |
| "HOME": str(home), | |
| "LANG": "C.UTF-8", | |
| "LC_ALL": "C.UTF-8", | |
| "TZ": "UTC", | |
| "PYTHONHASHSEED": "0", | |
| } | |
| def copy_project(source, target): | |
| """No symlinks, special files, or environment files may enter a submission.""" | |
| source = Path(source).resolve() | |
| if not source.is_dir(): | |
| raise ValueError(f"Solution directory does not exist: {source}") | |
| count = size = 0 | |
| for root, dirs, files in os.walk(source, followlinks=False): | |
| base = Path(root) | |
| dirs[:] = sorted( | |
| d for d in dirs if d not in EXCLUDED and not (base / d).is_symlink() | |
| ) | |
| relative = base.relative_to(source) | |
| (target / relative).mkdir(parents=True, exist_ok=True) | |
| for name in sorted(files): | |
| if ( | |
| name in EXCLUDED | |
| or name.startswith(".env.") | |
| or name.endswith((".pyc", ".token")) | |
| ): | |
| continue | |
| path = base / name | |
| if path.is_symlink() or not path.is_file(): | |
| raise ValueError( | |
| f"Submission contains a symlink or special file: {relative / name}" | |
| ) | |
| count += 1 | |
| size += path.stat().st_size | |
| if count > 2000 or size > 20_000_000: | |
| raise ValueError("Submission exceeds 2000 files / 20 MB") | |
| shutil.copyfile(path, target / relative / name) | |
| def run_session(project, state, session, *, durable=False, timeout=10.0): | |
| if os.name != "posix": | |
| raise RuntimeError( | |
| "The local evaluator requires POSIX process groups and pipe selectors" | |
| ) | |
| argv = [sys.executable, "-E", "-s", "-S", "main.py"] | |
| if durable: | |
| argv += ["--state-dir", str(state)] | |
| start = time.monotonic() | |
| deadline = start + timeout | |
| process = subprocess.Popen( | |
| argv, | |
| cwd=project, | |
| env=child_environment(state.parent / "home"), | |
| stdin=subprocess.PIPE, | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE, | |
| start_new_session=True, | |
| bufsize=0, | |
| ) | |
| selector = selectors.DefaultSelector() | |
| for pipe in (process.stdin, process.stdout, process.stderr): | |
| os.set_blocking(pipe.fileno(), False) | |
| selector.register(process.stdout, selectors.EVENT_READ, "out") | |
| selector.register(process.stderr, selectors.EVENT_READ, "err") | |
| buffer = b"" | |
| stderr = bytearray() | |
| output_bytes = passed = 0 | |
| failure = None | |
| actual = None | |
| def read_events(wait): | |
| nonlocal buffer, output_bytes | |
| for key, _ in selector.select(max(0, wait)): | |
| if key.data == "in": | |
| continue | |
| chunk = os.read(key.fileobj.fileno(), 65536) | |
| if not chunk: | |
| selector.unregister(key.fileobj) | |
| continue | |
| if key.data == "out": | |
| buffer += chunk | |
| output_bytes += len(chunk) | |
| if output_bytes > MAX_OUTPUT: | |
| raise ValueError("stdout exceeded 1 MiB") | |
| elif len(stderr) < 8192: | |
| stderr.extend(chunk[: 8192 - len(stderr)]) | |
| try: | |
| if len(session["requests"]) != len(session["expected"]): | |
| raise ValueError("Invalid acceptance session lengths") | |
| for index, (request, expected) in enumerate( | |
| zip(session["requests"], session["expected"]) | |
| ): | |
| actual = None | |
| wire = ( | |
| request | |
| if isinstance(request, str) | |
| else json.dumps(request, ensure_ascii=True, allow_nan=False) | |
| ) + "\n" | |
| pending = memoryview(wire.encode("utf-8")) | |
| selector.register(process.stdin, selectors.EVENT_WRITE, "in") | |
| while pending: | |
| if time.monotonic() >= deadline: | |
| raise TimeoutError("session timeout while sending request") | |
| try: | |
| written = os.write(process.stdin.fileno(), pending) | |
| pending = pending[written:] | |
| except BlockingIOError: | |
| read_events(min(0.02, deadline - time.monotonic())) | |
| selector.unregister(process.stdin) | |
| while b"\n" not in buffer: | |
| remaining = deadline - time.monotonic() | |
| if remaining <= 0: | |
| raise TimeoutError( | |
| "session timeout waiting for flushed JSON response" | |
| ) | |
| read_events(min(0.05, remaining)) | |
| if process.poll() is not None and b"\n" not in buffer: | |
| raise ValueError( | |
| f"process exited before response (code {process.returncode})" | |
| ) | |
| line, buffer = buffer.split(b"\n", 1) | |
| actual = strict_json(line.decode("utf-8")) | |
| if not equal(actual, expected): | |
| failure = { | |
| "request_index": index, | |
| "reason": "response mismatch", | |
| "expected": expected, | |
| "actual": actual, | |
| } | |
| break | |
| passed += 1 | |
| if failure is None: | |
| if durable: | |
| # Test persistence after acknowledgement without graceful shutdown hooks. | |
| kill_group(process) | |
| else: | |
| process.stdin.close() | |
| while process.poll() is None or selector.get_map(): | |
| if time.monotonic() >= deadline: | |
| raise TimeoutError("process did not exit cleanly on EOF") | |
| read_events(min(0.02, deadline - time.monotonic())) | |
| if process.returncode: | |
| raise ValueError(f"nonzero exit code {process.returncode}") | |
| # Catch extra lines even if the child has exited or was force-killed. | |
| read_events(0) | |
| if buffer: | |
| raise ValueError("extra stdout beyond one JSON response per request") | |
| except (ValueError, OSError, TimeoutError, UnicodeError) as error: | |
| failure = { | |
| "request_index": passed, | |
| "reason": str(error), | |
| "timed_out": isinstance(error, TimeoutError), | |
| } | |
| finally: | |
| kill_group(process) | |
| selector.close() | |
| for pipe in (process.stdin, process.stdout, process.stderr): | |
| if not pipe.closed: | |
| pipe.close() | |
| return { | |
| "passed": failure is None, | |
| "assertions_passed": passed, | |
| "assertions": len(session["expected"]), | |
| "duration": time.monotonic() - start, | |
| "failure": failure, | |
| "stderr": stderr.decode("utf-8", errors="replace") if failure else "", | |
| } | |
| def evaluate(task, solution, *, timeout=None, tests=None, fail_fast=False): | |
| """A task passes only when every scenario and every restart session passes.""" | |
| traces = tests if tests is not None else json.loads(task["acceptance_tests"]) | |
| if not traces: | |
| raise ValueError("Refusing an empty acceptance suite") | |
| source = Path(solution).resolve() | |
| reports = [] | |
| began = time.monotonic() | |
| with tempfile.TemporaryDirectory(prefix="klein-bench-") as temporary: | |
| root = Path(temporary) | |
| clean = root / "submission" | |
| clean.mkdir() | |
| rejection = None | |
| try: | |
| copy_project(source, clean) | |
| except ValueError as error: | |
| rejection = str(error) | |
| if rejection or not (clean / "main.py").is_file(): | |
| return { | |
| "task_id": task["task_id"], | |
| "subset": task["subset"], | |
| "passed": False, | |
| "resolved": False, | |
| "reason": rejection or "main.py is missing", | |
| "scenarios": [], | |
| "duration": time.monotonic() - began, | |
| } | |
| source_hash = hashlib.sha256() | |
| for file in sorted(p for p in clean.rglob("*") if p.is_file()): | |
| source_hash.update(str(file.relative_to(clean)).encode()) | |
| source_hash.update(b"\0" + file.read_bytes() + b"\0") | |
| for index, trace in enumerate(traces): | |
| scenario = root / str(index) | |
| project, state = scenario / "project", scenario / "state" | |
| project.mkdir(parents=True) | |
| state.mkdir() | |
| (scenario / "home").mkdir() | |
| copy_project(clean, project) | |
| sessions = [] | |
| for session in trace["sessions"]: | |
| report = run_session( | |
| project, | |
| state, | |
| session, | |
| durable=task["subset"] == "max", | |
| timeout=timeout or task["timeout_seconds"], | |
| ) | |
| sessions.append(report) | |
| if not report["passed"]: | |
| break | |
| reports.append( | |
| { | |
| "name": trace["name"], | |
| "passed": all(s["passed"] for s in sessions), | |
| "sessions": sessions, | |
| } | |
| ) | |
| if fail_fast and not reports[-1]["passed"]: | |
| break | |
| passed = len(reports) == len(traces) and all(r["passed"] for r in reports) | |
| return { | |
| "task_id": task["task_id"], | |
| "subset": task["subset"], | |
| "passed": passed, | |
| "resolved": passed, | |
| "scenarios_passed": sum(r["passed"] for r in reports), | |
| "scenarios_total": len(traces), | |
| "assertions_passed": sum( | |
| s["assertions_passed"] for r in reports for s in r["sessions"] | |
| ), | |
| "assertions_total": sum( | |
| len(s["expected"]) for t in traces for s in t["sessions"] | |
| ), | |
| "source_sha256": source_hash.hexdigest(), | |
| "duration": time.monotonic() - began, | |
| "scenarios": reports, | |
| } | |