Download scripts/lcb_exec_harness.py from tts-sft/round4-sft-eval: direct link, hf CLI and curl.
- Browser
- Download file 6.97 kB
-
https://huggingface.co/datasets/tts-sft/round4-sft-eval/resolve/main/scripts/lcb_exec_harness.py
- Command line
-
hf download hf://datasets/tts-sft/round4-sft-eval/scripts/lcb_exec_harness.py
-
curl -L -o lcb_exec_harness.py https://huggingface.co/datasets/tts-sft/round4-sft-eval/resolve/main/scripts/lcb_exec_harness.py
6.97 kB
| #!/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()) | |