File size: 12,502 Bytes
072246b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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,
    }