interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / bench / multipl-e / eval_om.py

143 lines · 5803 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""MultiPL-E evaluator for Omega programs written by humaneval_to_om.py.
4
5Foreign-harness adapter: MultiPL-E calls ``eval_script(path)`` from
6``evaluation/src/eval_<ext>.py``, so this file is Python. It is not first-party
7Omega and is not part of any Omega product path. Pure standard library.
8
9 OMEGA_OMC=/path/to/omc eval_om.py PROGRAM.om [...] # one JSON result per line
10
11Compile protocol (pinned omc): ``omc < p.om > p 2> p.err``. Only when omc exits
120 with nothing on stderr is ``p`` made executable and run. The omc file must hash
13to OMEGA_OMC_SHA256 (default: the omega-rosetta pin); a mismatch raises before
14anything is compiled, so no result is ever recorded against an unpinned compiler.
15
16Outcome -> MultiPL-E ``status`` (``om_status``, ``om_case``):
17
18 omc nonzero / stderr SyntaxError compile_error omc error code
19 exit 0 + pass line OK pass -
20 exit 0 without pass line Exception no_pass_line -
21 exit 1..98 Exception wrong_answer failing test case (exit - 1)
22 exit 100..199 Exception trap trap code (exit - 100)
23 other exit / signal Exception exit_other exit code
24 over the time limit Timeout timeout -
25
26MultiPL-E's containerized_eval keeps only status/exit_code/stdout/stderr; the
27om_* fields are derivable from exit_code by the table above.
28"""
29
30import hashlib
31import json
32import os
33import re
34import shlex
35import signal
36import subprocess
37import sys
38import tempfile
39from pathlib import Path
40
41# Pin of aien-dev/omega-rosetta omega.ref (omega-mv e5b32567a7aff3ce594e3254a622a846a6cd190b).
42PINNED_OMC_SHA256 = "2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f"
43# Must equal humaneval_to_om.MPE_OK_LINE: the line main writes after the last case holds.
44MPE_OK_LINE = "MultiPL-E Omega: all tests passed"
45COMPILE_TIMEOUT = 30
46MAX_OUTPUT = 2048
47_ERROR_RE = re.compile(r"omc: line (\d+): error (\d+)")
48_checked = {}
49
50
51def omc_path(omc=None) -> str:
52 omc = omc or os.environ.get("OMEGA_OMC")
53 if not omc:
54 raise RuntimeError("eval_om: set OMEGA_OMC to the pinned omc binary")
55 return omc
56
57
58def check_pin(omc: str) -> None:
59 """Raise unless the omc file hashes to the pin. Cached by (path, size, mtime)."""
60 st = os.stat(omc)
61 key = (os.path.realpath(omc), st.st_size, st.st_mtime_ns)
62 want = os.environ.get("OMEGA_OMC_SHA256", PINNED_OMC_SHA256)
63 if _checked.get(key) == want:
64 return
65 h = hashlib.sha256()
66 with open(omc, "rb") as f:
67 for chunk in iter(lambda: f.read(1 << 20), b""):
68 h.update(chunk)
69 got = h.hexdigest()
70 if got != want:
71 raise RuntimeError(f"eval_om: {omc} has sha256 {got}, pin is {want}; refusing to evaluate")
72 _checked[key] = want
73
74
75def _wrap() -> list:
76 """Optional command prefix for omc and the program, e.g. 'nice -n 19 taskset -c 10-14'."""
77 return shlex.split(os.environ.get("OMEGA_EVAL_WRAP", ""))
78
79
80def _run(argv, timeout, stdin=None, stdout=subprocess.PIPE):
81 """Run argv in its own process group; kill the group on timeout.
82 Returns (exit_code or None on timeout, stdout bytes, stderr bytes)."""
83 p = subprocess.Popen(
84 argv, stdin=stdin or subprocess.DEVNULL, stdout=stdout, stderr=subprocess.PIPE, start_new_session=True
85 )
86 try:
87 out, err = p.communicate(timeout=timeout)
88 return p.returncode, out or b"", err or b""
89 except subprocess.TimeoutExpired:
90 os.killpg(p.pid, signal.SIGKILL)
91 out, err = p.communicate()
92 return None, out or b"", err or b""
93
94
95def _text(b: bytes) -> str:
96 return b[:MAX_OUTPUT].decode("utf-8", errors="replace")
97
98
99def eval_script(path: Path, omc=None, timeout=None) -> dict:
100 omc = omc_path(omc)
101 check_pin(omc)
102 if timeout is None:
103 timeout = float(os.environ.get("OMEGA_EVAL_TIMEOUT", "15"))
104 with tempfile.TemporaryDirectory(prefix="eval_om.") as d:
105 exe = os.path.join(d, "p")
106 with open(path, "rb") as src, open(exe, "wb") as dst:
107 rc, _, err = _run(_wrap() + [omc], COMPILE_TIMEOUT, stdin=src, stdout=dst)
108 if rc is None:
109 return {"status": "Timeout", "exit_code": -1, "stdout": "", "stderr": "omc timeout",
110 "om_status": "timeout", "om_case": None}
111 if rc != 0 or err:
112 m = _ERROR_RE.search(err.decode("utf-8", errors="replace"))
113 return {"status": "SyntaxError", "exit_code": rc, "stdout": "", "stderr": _text(err),
114 "om_status": "compile_error", "om_case": int(m.group(2)) if m else None}
115 os.chmod(exe, 0o700)
116 rc, out, err = _run(_wrap() + [exe], timeout)
117 result = {"exit_code": rc if rc is not None else -1, "stdout": _text(out), "stderr": _text(err)}
118 if rc is None:
119 result.update(status="Timeout", om_status="timeout", om_case=None)
120 elif rc == 0 and out.endswith((MPE_OK_LINE + "\n").encode()):
121 result.update(status="OK", om_status="pass", om_case=None)
122 elif rc == 0:
123 result.update(status="Exception", om_status="no_pass_line", om_case=None)
124 elif 1 <= rc <= 98:
125 result.update(status="Exception", om_status="wrong_answer", om_case=rc - 1)
126 elif 100 <= rc <= 199:
127 result.update(status="Exception", om_status="trap", om_case=rc - 100)
128 else:
129 result.update(status="Exception", om_status="exit_other", om_case=rc)
130 return result
131
132
133def main(argv):
134 if not argv or argv[0] in ("-h", "--help"):
135 print(__doc__)
136 return 0 if argv else 2
137 for p in argv:
138 print(json.dumps({"path": p, **eval_script(Path(p))}))
139 return 0
140
141
142if __name__ == "__main__":
143 sys.exit(main(sys.argv[1:]))