File size: 6,973 Bytes
8c857d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Single-sample LiveCodeBench execution harness (one subprocess per candidate).

Runs an extracted code candidate against a problem's hidden test suite and prints
a JSON verdict to stdout. Isolated in its own process so a crash / sys.exit / TLE
in untrusted model code is contained (the parent imposes an overall timeout too).

Usage:
  python lcb_exec_harness.py <code_file> <tests_json_file>

tests_json_file: {"inputs":[...], "outputs":[...], "testtype":"stdin"|"functional",
                  "fn_name":"...", "time_limit":int}
Verdict (stdout, last line): {"passed":bool,"error":"","n_passed":int,"n_total":int,
                              "first_fail":int}

Test semantics (standard LCB):
  * stdin (atcoder): feed input to stdin, run as __main__ script, compare stdout
    line-wise rstrip + overall strip.
  * functional (leetcode): each test `input` is newline-joined JSON args; parse each
    line with json.loads, call Solution().<fn_name>(*args) (or a bare global fn),
    json-compare against json.loads(output) with a float / list fallback.
"""
from __future__ import annotations

import io
import json
import os
import signal
import sys

# --- resource cap (best-effort; this process is the disposable subprocess) ---
# RLIMIT_AS is the only defense against single-opcode memory bombs ([0]*b,
# bytearray(b)): SIGALRM fires only between bytecodes, so a C-level allocation
# fault-ins RAM until the container cgroup OOMs. See lcb_public_probe_harness.
try:
    import resource

    def _limit_mem(mem_bytes: int) -> None:
        try:
            resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes))
            resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
        except (ValueError, OSError):
            pass
except Exception:  # pragma: no cover — non-POSIX fallback
    def _limit_mem(mem_bytes: int) -> None:
        return None


def _set_alarm(seconds: float) -> None:
    def _handler(signum, frame):
        raise TimeoutError(f"time limit exceeded ({seconds}s)")

    signal.signal(signal.SIGALRM, _handler)
    signal.setitimer(signal.ITIMER_REAL, max(0.1, seconds))


def _cancel_alarm() -> None:
    signal.setitimer(signal.ITIMER_REAL, 0)


def _norm_out(s: str) -> str:
    return "\n".join(line.rstrip() for line in str(s).strip().split("\n"))


def _eq(got, want) -> bool:
    if got == want:
        return True
    try:
        if abs(float(got) - float(want)) < 1e-6:
            return True
    except (TypeError, ValueError):
        pass
    try:
        if list(got) == list(want):
            return True
    except TypeError:
        pass
    return False


def _mk_stdin(text: str):
    """Text stream over a real byte buffer, so `sys.stdin.buffer` works.

    A bare io.StringIO has no `.buffer`, which made every candidate using the
    standard competitive-programming idiom `sys.stdin.buffer.read()` die with
    AttributeError and score as a wrong answer regardless of correctness.
    """
    return io.TextIOWrapper(io.BytesIO(text.encode()), encoding="utf-8", newline="")


def _mk_stdout():
    """(text_stream, raw_bytes) — `.buffer` works; write_through keeps ordering
    correct when a candidate mixes print() and sys.stdout.buffer.write()."""
    raw = io.BytesIO()
    return io.TextIOWrapper(raw, encoding="utf-8", newline="", write_through=True), raw


def _stdout_value(stream, raw) -> str:
    try:
        stream.flush()
    except Exception:  # noqa: BLE001  (candidate may have closed it)
        pass
    return raw.getvalue().decode("utf-8", "replace")


def run_stdin(code, inputs, outputs, tl):
    for i, (inp, exp) in enumerate(zip(inputs, outputs)):
        stdin_text = inp if isinstance(inp, str) else "\n".join(str(x) for x in inp)
        want = _norm_out(exp if isinstance(exp, str) else str(exp))
        old_in, old_out = sys.stdin, sys.stdout
        sys.stdin = _mk_stdin(stdin_text)
        buf, buf_raw = _mk_stdout()
        sys.stdout = buf
        try:
            _set_alarm(tl)
            try:
                exec(compile(code, "<candidate>", "exec"), {"__name__": "__main__"})
            except SystemExit:
                pass
            _cancel_alarm()
        except Exception as e:  # noqa: BLE001
            _cancel_alarm()
            sys.stdin, sys.stdout = old_in, old_out
            return False, f"{type(e).__name__}: {e}", i
        finally:
            sys.stdin, sys.stdout = old_in, old_out
        if _norm_out(_stdout_value(buf, buf_raw)) != want:
            return False, "wrong_answer", i
    return True, "", len(inputs)


def run_functional(code, fn_name, inputs, outputs, tl):
    g = {"__name__": "__lcb_harness__"}
    try:
        exec(compile(code, "<candidate>", "exec"), g)
    except Exception as e:  # noqa: BLE001
        return False, f"import_error: {type(e).__name__}: {e}", 0

    def resolve():
        if "Solution" in g:
            return getattr(g["Solution"](), fn_name)
        if fn_name in g and callable(g[fn_name]):
            return g[fn_name]
        return None

    if resolve() is None:
        return False, f"no_callable:{fn_name}", 0

    for i, (inp, exp) in enumerate(zip(inputs, outputs)):
        try:
            lines = inp.split("\n") if isinstance(inp, str) else list(inp)
            args = [json.loads(line) for line in lines]
        except Exception:  # noqa: BLE001
            args = [inp]
        try:
            want = json.loads(exp) if isinstance(exp, str) else exp
        except Exception:  # noqa: BLE001
            want = exp
        try:
            fn = resolve()  # fresh Solution() per test
            _set_alarm(tl)
            got = fn(*args)
            _cancel_alarm()
        except Exception as e:  # noqa: BLE001
            _cancel_alarm()
            return False, f"{type(e).__name__}: {e}", i
        if not _eq(got, want):
            return False, "wrong_answer", i
    return True, "", len(inputs)


def main() -> int:
    _limit_mem(int(os.environ.get("LCB_EXEC_MEM_MB", "4096")) * 1024 * 1024)
    code = open(sys.argv[1]).read()
    tests = json.load(open(sys.argv[2]))
    inputs, outputs = tests["inputs"], tests["outputs"]
    tl = float(tests.get("time_limit", 6))
    testtype = tests.get("testtype", "stdin")
    fn_name = tests.get("fn_name", "")
    try:
        if testtype == "functional" and fn_name:
            passed, err, fail_idx = run_functional(code, fn_name, inputs, outputs, tl)
        else:
            passed, err, fail_idx = run_stdin(code, inputs, outputs, tl)
    except Exception as e:  # noqa: BLE001  (harness-level guard)
        passed, err, fail_idx = False, f"harness_error: {type(e).__name__}: {e}", -1
    n_total = len(inputs)
    n_passed = n_total if passed else max(0, fail_idx)
    print(json.dumps({
        "passed": passed, "error": err,
        "n_passed": n_passed, "n_total": n_total, "first_fail": fail_idx,
    }))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())