omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / research / om-bench / bench / ombench.py
| 1 | #!/usr/bin/env python3 |
| 2 | """om-bench (#653) driver: generation arms, candidate execution, comparator, denominator guard. |
| 3 | |
| 4 | Disclosed host tool (Python 3.12, outside the Omega build closure). The Omega arms are additionally |
| 5 | judged by the seeded .om runner seed/qualification/om2/gate.om; `crosscheck` requires both judges to |
| 6 | agree case by case, so this comparator is never the only judge of an Omega candidate. |
| 7 | |
| 8 | ombench.py gen --arm {a,b,aeq,fpy,fc} --split SPLIT --run DIR [--tasks T1,T2] |
| 9 | ombench.py judge --run DIR --split SPLIT # run final candidates on every case |
| 10 | ombench.py gatelist --run DIR --split SPLIT # gate.om case list for Omega candidates |
| 11 | ombench.py crosscheck --run DIR --gate-log LOG # agree with gate.om verdicts or exit 1 |
| 12 | ombench.py summary --run DIR # aggregate counts (no task contents) |
| 13 | """ |
| 14 | import argparse, ast, hashlib, json, os, re, shutil, signal, subprocess, sys, time, urllib.request |
| 15 | |
| 16 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 17 | REPO = os.environ.get("OMB_REPO", os.path.abspath(os.path.join(HERE, "..", "..", ".."))) |
| 18 | sys.path.insert(0, HERE) |
| 19 | from benchlib import SEALED |
| 20 | OMC = os.path.join(REPO, "seed/out/omc") |
| 21 | OMC_SHA = "2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f" |
| 22 | MAX_TOKENS = 2048 |
| 23 | LLM = os.environ.get("OMB_LLM", "http://127.0.0.1:18653") |
| 24 | TASKROOTS = ([os.environ["OMB_TASKROOT"]] if os.environ.get("OMB_TASKROOT") else |
| 25 | [os.path.join(HERE, "pubtasks"), os.path.join(SEALED, "tasks")]) |
| 26 | RUN_DEADLINE = 10.0 |
| 27 | COMPILE_DEADLINE = 60.0 |
| 28 | REPAIRS = 3 |
| 29 | AEQ_SAMPLES = 4 |
| 30 | SEED = 653 |
| 31 | CPU_CORES = 2 # llama-server: taskset -c 3-4, -t 2 (cores shared on the box; see CONTRACT.md section 4) |
| 32 | CLUSTERS = os.path.join(SEALED, "clusters.json") |
| 33 | |
| 34 | ERRMEAN = { |
| 35 | 1: "compiler I/O", 2: "compiler I/O", 3: "unknown name or field", 4: "line ends too early", |
| 36 | 5: "extra words on the line", 6: "malformed number", 7: "type mismatch (no implicit conversions; " |
| 37 | "both operands, a name and its value, an argument and its parameter must have the same type)", |
| 38 | 8: "number out of range", 9: "word in a disallowed place", 10: "duplicate name", |
| 39 | 11: "ambiguous bare number: give it a type, e.g. ulong 0", 12: "too many live names or temporaries " |
| 40 | "(16 registers): split the function", 13: "non-function name longer than 8 characters", |
| 41 | 14: "capacity", 15: "missing end", 16: "syntax error or unknown word", 17: "line after ret, break, " |
| 42 | "continue, trap or exit in the same block", 18: "missing ret on some path", 19: "global passed as an " |
| 43 | "argument, or the same array twice in one call", 20: "write to a view or text", |
| 44 | 21: "constant index out of range", 22: "bad text literal", 23: "size capacity", |
| 45 | } |
| 46 | |
| 47 | COMMON_IO = None |
| 48 | |
| 49 | |
| 50 | def sha256(b): |
| 51 | return hashlib.sha256(b).hexdigest() |
| 52 | |
| 53 | |
| 54 | def sha_file(p): |
| 55 | with open(p, "rb") as f: |
| 56 | return sha256(f.read()) |
| 57 | |
| 58 | |
| 59 | def load_common_io(): |
| 60 | sys.path.insert(0, HERE) |
| 61 | import benchlib |
| 62 | return benchlib.COMMON_IO |
| 63 | |
| 64 | |
| 65 | def task_dirs(split): |
| 66 | for root in TASKROOTS: |
| 67 | d = os.path.join(root, split) |
| 68 | if os.path.isdir(d): |
| 69 | return d, sorted(os.listdir(d)) |
| 70 | sys.exit(f"FATAL split {split}: no task directory") |
| 71 | |
| 72 | |
| 73 | def fault(tid, reason): |
| 74 | print(f"CORPUS FAULT [{tid}] {reason}") |
| 75 | sys.exit(1) |
| 76 | |
| 77 | |
| 78 | def load_task(split, tid): |
| 79 | d, _ = task_dirs(split) |
| 80 | td = os.path.join(d, tid) |
| 81 | for f in ("meta.json", "statement.txt"): |
| 82 | if not os.path.isfile(os.path.join(td, f)): |
| 83 | fault(tid, f"missing {f}") |
| 84 | meta = json.load(open(os.path.join(td, "meta.json"))) |
| 85 | stmt = open(os.path.join(td, "statement.txt")).read().strip() |
| 86 | if "cases" not in meta or not meta["cases"]: |
| 87 | fault(tid, "no cases") |
| 88 | if not stmt: |
| 89 | fault(tid, "empty statement") |
| 90 | cases = [] |
| 91 | for c in meta["cases"]: |
| 92 | for k in ("n", "visible", "exit"): |
| 93 | if k not in c or c[k] is None: |
| 94 | fault(tid, f"case missing {k}") |
| 95 | n = c["n"] |
| 96 | cases.append({"n": n, "visible": c["visible"], "exit": c["exit"], |
| 97 | "in": os.path.join(td, f"{n:02d}.in"), "out": os.path.join(td, f"{n:02d}.out")}) |
| 98 | for k in ("in", "out"): |
| 99 | if not os.path.isfile(cases[-1][k]): |
| 100 | fault(tid, f"case {n} missing .{k}") |
| 101 | if sum(1 for c in cases if c["visible"]) != 2: |
| 102 | fault(tid, "visible example count is not 2") |
| 103 | return {"tid": tid, "dir": td, "statement": stmt, "cases": cases, "family": meta.get("family")} |
| 104 | |
| 105 | |
| 106 | def host_words(): |
| 107 | src = open(os.path.join(REPO, "seed/omc/genkw.awk")).read() |
| 108 | words = set() |
| 109 | for m in re.finditer(r"([a-z0-9]+):(\d+)", src): |
| 110 | if int(m.group(2)) >= 100: |
| 111 | words.add(m.group(1)) |
| 112 | if len(words) < 50: |
| 113 | sys.exit("FATAL host word table not parsed") |
| 114 | return words |
| 115 | |
| 116 | |
| 117 | LANG = { |
| 118 | "om": ("Omega", "om"), |
| 119 | "py": ("Python 3", "python"), |
| 120 | "c": ("C (C11, compiled with gcc -O2, only the standard library)", "c"), |
| 121 | } |
| 122 | |
| 123 | |
| 124 | def system_prompt(lang): |
| 125 | if lang == "om": |
| 126 | card = open(os.path.join(HERE, "..", "REFERENCE-CARD.md")).read() |
| 127 | return ("You write complete Omega programs. Follow this reference card exactly.\n\n" + card) |
| 128 | return f"You write complete {LANG[lang][0]} programs." |
| 129 | |
| 130 | |
| 131 | def user_prompt(task, lang): |
| 132 | ex = [] |
| 133 | for c in task["cases"]: |
| 134 | if c["visible"]: |
| 135 | i = open(c["in"], "rb").read().decode("ascii") |
| 136 | o = open(c["out"], "rb").read().decode("ascii") |
| 137 | ex.append(f"Example input:\n```\n{i}```\nExpected output:\n```\n{o}```") |
| 138 | fence = LANG[lang][1] |
| 139 | return (f"Task: {task['statement']}\n\nInput and output rules: {COMMON_IO}\n\n" + "\n\n".join(ex) + |
| 140 | f"\n\nWrite one complete {LANG[lang][0]} program that solves the task for every valid input, " |
| 141 | f"not only the examples. Reply with the program in a single ```{fence} code block.") |
| 142 | |
| 143 | |
| 144 | def chat(messages, temperature, seed): |
| 145 | body = {"messages": messages, "temperature": temperature, "seed": seed, "max_tokens": MAX_TOKENS, |
| 146 | "cache_prompt": True, "stream": False} |
| 147 | if temperature == 0: |
| 148 | body["top_k"] = 1 |
| 149 | req = urllib.request.Request(LLM + "/v1/chat/completions", data=json.dumps(body).encode(), |
| 150 | headers={"Content-Type": "application/json"}) |
| 151 | t0 = time.time() |
| 152 | with urllib.request.urlopen(req, timeout=3600) as r: |
| 153 | resp = json.loads(r.read()) |
| 154 | wall = time.time() - t0 |
| 155 | msg = resp["choices"][0]["message"]["content"] |
| 156 | u = resp.get("usage", {}) |
| 157 | t = resp.get("timings", {}) |
| 158 | return msg, {"wall_s": round(wall, 3), "prompt_tokens": u.get("prompt_tokens"), |
| 159 | "completion_tokens": u.get("completion_tokens"), "prompt_n_processed": t.get("prompt_n"), |
| 160 | "prompt_ms": t.get("prompt_ms"), "predicted_ms": t.get("predicted_ms"), |
| 161 | "finish_reason": resp["choices"][0].get("finish_reason"), "model": resp.get("model"), |
| 162 | "system_fingerprint": resp.get("system_fingerprint")} |
| 163 | |
| 164 | |
| 165 | FENCE = re.compile(r"```[A-Za-z0-9_+-]*[ \t]*\n(.*?)(```|\Z)", re.S) |
| 166 | |
| 167 | |
| 168 | def extract(text): |
| 169 | m = FENCE.search(text) |
| 170 | if not m: |
| 171 | return None |
| 172 | code = m.group(1) |
| 173 | if code and not code.endswith("\n"): |
| 174 | code += "\n" |
| 175 | return code |
| 176 | |
| 177 | |
| 178 | def compile_om(src_path, out_path): |
| 179 | with open(src_path, "rb") as fi, open(out_path, "wb") as fo: |
| 180 | try: |
| 181 | p = subprocess.run([OMC], stdin=fi, stdout=fo, stderr=subprocess.PIPE, timeout=COMPILE_DEADLINE) |
| 182 | except subprocess.TimeoutExpired: |
| 183 | return 124, "compile timeout" |
| 184 | os.chmod(out_path, 0o700) |
| 185 | return p.returncode, p.stderr.decode(errors="replace") |
| 186 | |
| 187 | |
| 188 | def compile_c(src_path, out_path): |
| 189 | try: |
| 190 | p = subprocess.run(["gcc", "-O2", "-std=gnu11", "-o", out_path, src_path, "-lm"], |
| 191 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=COMPILE_DEADLINE) |
| 192 | except subprocess.TimeoutExpired: |
| 193 | return 124, "compile timeout" |
| 194 | return p.returncode, p.stdout.decode(errors="replace") |
| 195 | |
| 196 | |
| 197 | def compile_py(src_path, _out): |
| 198 | p = subprocess.run([sys.executable, "-I", "-c", |
| 199 | "import sys,ast;ast.parse(open(sys.argv[1]).read())", src_path], |
| 200 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT) |
| 201 | return p.returncode, p.stdout.decode(errors="replace") |
| 202 | |
| 203 | |
| 204 | def build(lang, src_path, workdir): |
| 205 | out = os.path.join(workdir, "prog") |
| 206 | if lang == "om": |
| 207 | rc, err = compile_om(src_path, out) |
| 208 | elif lang == "c": |
| 209 | rc, err = compile_c(src_path, out) |
| 210 | else: |
| 211 | rc, err = compile_py(src_path, out) |
| 212 | return rc, err |
| 213 | |
| 214 | |
| 215 | PY_OK_MODULES = {"sys", "math", "collections", "itertools", "functools", "heapq", "bisect", "string", "re", |
| 216 | "fractions", "decimal", "operator", "array", "statistics", "typing", "dataclasses", "copy"} |
| 217 | PY_BAD_CALLS = {"open", "exec", "eval", "compile", "__import__", "breakpoint", "globals", "vars"} |
| 218 | PY_BAD = re.compile(r"\b(import|from)\b|open\s*\(|exec\s*\(|eval\s*\(|__import__") |
| 219 | |
| 220 | |
| 221 | def py_scan(code): |
| 222 | """Python: imports outside an allowlist, or file/exec calls. Falls back to a coarse regex when the |
| 223 | candidate does not parse (it would fail at run time anyway, but is still not executed if flagged).""" |
| 224 | try: |
| 225 | tree = ast.parse(code) |
| 226 | except (SyntaxError, ValueError): |
| 227 | return sorted(set(m.group(0).strip() for m in PY_BAD.finditer(code) |
| 228 | if not m.group(0).startswith(("import", "from")))) |
| 229 | found = [] |
| 230 | for node in ast.walk(tree): |
| 231 | if isinstance(node, ast.Import): |
| 232 | found += ["import " + a.name for a in node.names if a.name.split(".")[0] not in PY_OK_MODULES] |
| 233 | elif isinstance(node, ast.ImportFrom): |
| 234 | if (node.module or "").split(".")[0] not in PY_OK_MODULES: |
| 235 | found.append("from " + (node.module or ".")) |
| 236 | elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in PY_BAD_CALLS: |
| 237 | found.append(node.func.id + "(") |
| 238 | elif isinstance(node, ast.Attribute) and node.attr in ("system", "popen", "fork", "remove", "unlink"): |
| 239 | found.append("." + node.attr) |
| 240 | return sorted(set(found)) |
| 241 | |
| 242 | |
| 243 | C_BAD = re.compile(r"\b(fopen|open|system|popen|fork|exec[lv]p?e?|socket|connect|unlink|remove|rename|" |
| 244 | r"mmap|ptrace|kill|dlopen|syscall)\s*\(|#\s*include\s*<(sys/socket|netinet/|arpa/|" |
| 245 | r"dlfcn|sys/ptrace)") |
| 246 | |
| 247 | |
| 248 | def authz_scan(lang, code, hostw): |
| 249 | """Static scan: candidates may touch only stdin, stdout and exit. Returns list of findings.""" |
| 250 | if lang == "om": |
| 251 | found = [] |
| 252 | for ln in code.split("\n"): |
| 253 | toks = ln.split() |
| 254 | if toks and toks[0] == "note": |
| 255 | continue |
| 256 | for t in toks: |
| 257 | if t in hostw: |
| 258 | found.append(t) |
| 259 | # fds other than 0 (read) / 1 (write) |
| 260 | for k, t in enumerate(toks): |
| 261 | if t in ("read", "pread") and k + 1 < len(toks) and toks[k + 1] != "0": |
| 262 | found.append(f"{t}-fd:{toks[k + 1]}") |
| 263 | if t in ("write", "pwrite") and k + 1 < len(toks) and toks[k + 1] not in ("1", "2"): |
| 264 | found.append(f"{t}-fd:{toks[k + 1]}") |
| 265 | return sorted(set(found)) |
| 266 | if lang == "py": |
| 267 | return py_scan(code) |
| 268 | return sorted(set(m.group(0).strip() for m in C_BAD.finditer(code))) |
| 269 | |
| 270 | |
| 271 | def run_case(lang, workdir, case): |
| 272 | prog = os.path.join(workdir, "prog") |
| 273 | if lang == "py": |
| 274 | cmd = [sys.executable, "-I", os.path.join(workdir, "prog.py")] |
| 275 | else: |
| 276 | cmd = [prog] |
| 277 | exe = os.path.join(workdir, "exec") |
| 278 | os.makedirs(exe, exist_ok=True) |
| 279 | with open(case["in"], "rb") as fi: |
| 280 | t0 = time.time() |
| 281 | try: |
| 282 | p = subprocess.Popen(cmd, stdin=fi, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=exe, |
| 283 | start_new_session=True, env={"PATH": "/usr/bin:/bin", "LANG": "C"}, |
| 284 | preexec_fn=lambda: __import__("resource").setrlimit( |
| 285 | __import__("resource").RLIMIT_FSIZE, (1 << 24, 1 << 24))) |
| 286 | except OSError as e: |
| 287 | return {"status": "exec_fail", "detail": str(e)} |
| 288 | try: |
| 289 | so, se = p.communicate(timeout=RUN_DEADLINE) |
| 290 | except subprocess.TimeoutExpired: |
| 291 | os.killpg(p.pid, signal.SIGKILL) |
| 292 | p.communicate() |
| 293 | return {"status": "timeout", "wall_s": RUN_DEADLINE} |
| 294 | wall = time.time() - t0 |
| 295 | want = open(case["out"], "rb").read() |
| 296 | rc = p.returncode |
| 297 | r = {"rc": rc, "wall_s": round(wall, 4), "stdout_sha256": sha256(so), "stdout_len": len(so)} |
| 298 | if rc < 0: |
| 299 | r["status"] = "signal" |
| 300 | elif so == want and rc == case["exit"]: |
| 301 | r["status"] = "pass" |
| 302 | elif rc != case["exit"]: |
| 303 | r["status"] = "trap" if (lang == "om" and 100 <= rc <= 114) else "bad_exit" |
| 304 | elif len(so) == 0 and len(want) > 0: |
| 305 | r["status"] = "empty_output" |
| 306 | else: |
| 307 | r["status"] = "wrong_output" |
| 308 | return r |
| 309 | |
| 310 | |
| 311 | MECH_CASE = {"exec_fail", "timeout", "signal", "trap", "bad_exit", "empty_output"} |
| 312 | |
| 313 | |
| 314 | def classify(rec): |
| 315 | """Task-level class. Mechanical = needs a hand repair of syntax, wiring, target code or integration.""" |
| 316 | if rec.get("authz"): |
| 317 | return "authz_violation" |
| 318 | if rec["code_sha256"] is None: |
| 319 | return "no_code" |
| 320 | if rec["compile_rc"] != 0: |
| 321 | return "compile_refused" |
| 322 | sts = [c["status"] for c in rec["cases"]] |
| 323 | if all(s == "pass" for s in sts): |
| 324 | return "pass" |
| 325 | if any(s in MECH_CASE for s in sts): |
| 326 | return "runtime_mechanical" |
| 327 | return "wrong_output" |
| 328 | |
| 329 | |
| 330 | def arm_lang(arm): |
| 331 | return {"a": "om", "b": "om", "aeq": "om", "fpy": "py", "fc": "c"}[arm] |
| 332 | |
| 333 | |
| 334 | def src_name(lang): |
| 335 | return {"om": "prog.om", "py": "prog.py", "c": "prog.c"}[lang] |
| 336 | |
| 337 | |
| 338 | def write_candidate(workdir, lang, code): |
| 339 | os.makedirs(workdir, exist_ok=True) |
| 340 | p = os.path.join(workdir, src_name(lang)) |
| 341 | with open(p, "w") as f: |
| 342 | f.write(code) |
| 343 | return p |
| 344 | |
| 345 | |
| 346 | def feedback_text(err, code): |
| 347 | m = re.search(r"line (\d+): error (\d+)", err) |
| 348 | if not m: |
| 349 | return f"The compiler refused the program. Its message was:\n{err.strip()}\nReply with the corrected complete program in a single ```om code block." |
| 350 | ln, k = int(m.group(1)), int(m.group(2)) |
| 351 | lines = code.split("\n") |
| 352 | src = lines[ln - 1] if 0 < ln <= len(lines) else "" |
| 353 | return (f"The Omega compiler refused the program: `omc: line {ln}: error {k}` ({ERRMEAN.get(k, 'see card')}). " |
| 354 | f"Line {ln} is: `{src}`\nFix it and reply with the corrected complete program in a single ```om code block.") |
| 355 | |
| 356 | |
| 357 | def gen_task(arm, task, rundir, log): |
| 358 | lang = arm_lang(arm) |
| 359 | tdir = os.path.join(rundir, "cand", task["tid"]) |
| 360 | if os.path.exists(os.path.join(tdir, "gen.json")): |
| 361 | return |
| 362 | os.makedirs(tdir, exist_ok=True) |
| 363 | sysm = {"role": "system", "content": system_prompt(lang)} |
| 364 | usr = {"role": "user", "content": user_prompt(task, lang)} |
| 365 | attempts = [] |
| 366 | final_code = None |
| 367 | if arm in ("a", "fpy", "fc"): |
| 368 | text, meta = chat([sysm, usr], 0, SEED) |
| 369 | attempts.append({"k": 0, "reply_sha256": sha256(text.encode()), "reply": text, **meta}) |
| 370 | final_code = extract(text) |
| 371 | elif arm == "b": |
| 372 | msgs = [sysm, usr] |
| 373 | for k in range(REPAIRS + 1): |
| 374 | text, meta = chat(msgs, 0, SEED) |
| 375 | code = extract(text) |
| 376 | at = {"k": k, "reply_sha256": sha256(text.encode()), "reply": text, **meta} |
| 377 | final_code = code |
| 378 | if code is None: |
| 379 | fb = "Your reply had no code block. Reply with the complete program in a single ```om code block." |
| 380 | else: |
| 381 | wd = os.path.join(tdir, f"try{k}") |
| 382 | sp = write_candidate(wd, lang, code) |
| 383 | rc, err = build(lang, sp, wd) |
| 384 | at["compile_rc"], at["compile_err"] = rc, err[:2000] |
| 385 | if rc == 0: |
| 386 | attempts.append(at) |
| 387 | break |
| 388 | fb = feedback_text(err, code) |
| 389 | at["feedback"] = fb |
| 390 | attempts.append(at) |
| 391 | msgs = msgs + [{"role": "assistant", "content": text}, {"role": "user", "content": fb}] |
| 392 | elif arm == "aeq": |
| 393 | for k in range(AEQ_SAMPLES): |
| 394 | text, meta = chat([sysm, usr], 0.8, SEED + 1 + k) |
| 395 | code = extract(text) |
| 396 | at = {"k": k, "reply_sha256": sha256(text.encode()), "reply": text, **meta} |
| 397 | final_code = code |
| 398 | if code is not None: |
| 399 | wd = os.path.join(tdir, f"try{k}") |
| 400 | sp = write_candidate(wd, lang, code) |
| 401 | rc, err = build(lang, sp, wd) |
| 402 | at["compile_rc"] = rc |
| 403 | attempts.append(at) |
| 404 | if rc == 0: |
| 405 | break |
| 406 | else: |
| 407 | attempts.append(at) |
| 408 | if final_code is not None: |
| 409 | write_candidate(tdir, lang, final_code) |
| 410 | rec = {"tid": task["tid"], "arm": arm, "lang": lang, "attempts": attempts, |
| 411 | "code_sha256": sha256(final_code.encode()) if final_code is not None else None, |
| 412 | "llm_wall_s": round(sum(a["wall_s"] for a in attempts), 3), |
| 413 | "prompt_tokens": sum(a["prompt_tokens"] or 0 for a in attempts), |
| 414 | "prompt_tokens_processed": sum(a["prompt_n_processed"] or 0 for a in attempts), |
| 415 | "completion_tokens": sum(a["completion_tokens"] or 0 for a in attempts)} |
| 416 | with open(os.path.join(tdir, "gen.json"), "w") as f: |
| 417 | json.dump(rec, f, indent=1) |
| 418 | log.write(json.dumps({"tid": task["tid"], "arm": arm, "attempts": len(attempts), |
| 419 | "completion_tokens": rec["completion_tokens"], "llm_wall_s": rec["llm_wall_s"], |
| 420 | "t": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}) + "\n") |
| 421 | log.flush() |
| 422 | |
| 423 | |
| 424 | def judge(rundir, split, arm): |
| 425 | lang = arm_lang(arm) |
| 426 | hostw = host_words() |
| 427 | _, tids = task_dirs(split) |
| 428 | out = [] |
| 429 | for tid in tids: |
| 430 | task = load_task(split, tid) |
| 431 | tdir = os.path.join(rundir, "cand", tid) |
| 432 | gp = os.path.join(tdir, "gen.json") |
| 433 | if not os.path.exists(gp): |
| 434 | out.append({"tid": tid, "class": "NOT_RUN"}) |
| 435 | continue |
| 436 | gen = json.load(open(gp)) |
| 437 | rec = {"tid": tid, "code_sha256": gen["code_sha256"], "compile_rc": None, "cases": [], "authz": []} |
| 438 | if gen["code_sha256"] is not None: |
| 439 | code = open(os.path.join(tdir, src_name(lang))).read() |
| 440 | rec["authz"] = authz_scan(lang, code, hostw) |
| 441 | jd = os.path.join(tdir, "judge") |
| 442 | if os.path.exists(jd): |
| 443 | shutil.rmtree(jd) |
| 444 | os.makedirs(jd) |
| 445 | sp = write_candidate(jd, lang, code) |
| 446 | t0 = time.time() |
| 447 | rc, err = build(lang, sp, jd) |
| 448 | rec["compile_s"] = round(time.time() - t0, 3) |
| 449 | rec["compile_rc"], rec["compile_err"] = rc, err[:500] |
| 450 | if rc == 0 and not rec["authz"]: |
| 451 | if lang != "py": |
| 452 | rec["bin_sha256"] = sha_file(os.path.join(jd, "prog")) |
| 453 | for c in task["cases"]: |
| 454 | r = run_case(lang, jd, c) |
| 455 | r["n"], r["visible"] = c["n"], c["visible"] |
| 456 | rec["cases"].append(r) |
| 457 | rec["class"] = classify(rec) |
| 458 | rec["n_cases"] = len(task["cases"]) |
| 459 | out.append(rec) |
| 460 | missing = [r["tid"] for r in out if r["class"] == "NOT_RUN"] |
| 461 | with open(os.path.join(rundir, f"verdicts-{split}.jsonl"), "w") as f: |
| 462 | for r in out: |
| 463 | f.write(json.dumps(r, sort_keys=True) + "\n") |
| 464 | if len(out) != len(tids): |
| 465 | sys.exit(f"DENOMINATOR FAULT verdicts={len(out)} manifest={len(tids)}") |
| 466 | if missing: |
| 467 | print(f"NOT_RUN {len(missing)} of {len(tids)}: {' '.join(missing)}") |
| 468 | sys.exit(2) |
| 469 | print(f"judged {len(out)}/{len(tids)}", json.dumps(counts(out), sort_keys=True)) |
| 470 | |
| 471 | |
| 472 | def counts(rows): |
| 473 | c = {} |
| 474 | for r in rows: |
| 475 | c[r["class"]] = c.get(r["class"], 0) + 1 |
| 476 | return c |
| 477 | |
| 478 | |
| 479 | def gatelist(rundir, split): |
| 480 | _, tids = task_dirs(split) |
| 481 | lines = [f"deadline {int(RUN_DEADLINE)}"] |
| 482 | for tid in tids: |
| 483 | task = load_task(split, tid) |
| 484 | src = os.path.join(rundir, "cand", tid, "prog.om") |
| 485 | if not os.path.exists(src): |
| 486 | lines.append(f"{tid}.nocode notrun no-code-block") |
| 487 | continue |
| 488 | for c in task["cases"]: |
| 489 | lines.append(f"{tid}.{c['n']:02d} run {os.path.relpath(src, REPO)} file:{os.path.relpath(c['in'], REPO)} " |
| 490 | f"file:{os.path.relpath(c['out'], REPO)} any {c['exit']}") |
| 491 | p = os.path.join(rundir, f"gate-{split}.cases") |
| 492 | with open(p, "w") as f: |
| 493 | f.write("\n".join(lines) + "\n") |
| 494 | print(p, len(lines) - 1) |
| 495 | |
| 496 | |
| 497 | def crosscheck(rundir, split, gate_log): |
| 498 | verdict = {} |
| 499 | log = open(gate_log, errors="replace").read() |
| 500 | # A crash or setup failure can leave no verdicts, or only a passing prefix. |
| 501 | # Candidate FAIL/NOT_RUN/INVALID outcomes remain visible, not process success. |
| 502 | final = re.search(r"^OM2GATE (PASS|FAIL|INVALID|NOT_RUN) cases=(\d+) pass=(\d+) fail=(\d+) invalid=(\d+) not_run=(\d+)\n?\Z", log, re.M) |
| 503 | if final is None or "MISMATCH: every case is NOT_RUN" in log: |
| 504 | print("INVALID incomplete gate report or compiler identity mismatch") |
| 505 | return 1 |
| 506 | for ln in log.splitlines(): |
| 507 | m = re.match(r"VERDICT (\S+) (PASS|FAIL|INVALID|NOT_RUN)\b", ln) |
| 508 | if m: |
| 509 | if m.group(1) in verdict: |
| 510 | print("INVALID duplicate gate verdict") |
| 511 | return 1 |
| 512 | verdict[m.group(1)] = m.group(2) |
| 513 | reported = tuple(int(n) for n in final.groups()[1:]) |
| 514 | actual = (len(verdict), *(sum(v == kind for v in verdict.values()) |
| 515 | for kind in ("PASS", "FAIL", "INVALID", "NOT_RUN"))) |
| 516 | if reported != actual or not verdict: |
| 517 | print("INVALID gate report counts do not match verdicts") |
| 518 | return 1 |
| 519 | outcome = ("INVALID" if actual[3] else "FAIL" if actual[2] else |
| 520 | "NOT_RUN" if actual[4] else "PASS") |
| 521 | if final.group(1) != outcome: |
| 522 | print("INVALID gate outcome does not match verdicts") |
| 523 | return 1 |
| 524 | rows = [json.loads(l) for l in open(os.path.join(rundir, f"verdicts-{split}.jsonl"))] |
| 525 | agree = disagree = 0 |
| 526 | bad = [] |
| 527 | expected = set() |
| 528 | for r in rows: |
| 529 | if r["code_sha256"] is None: |
| 530 | name = f"{r['tid']}.nocode" |
| 531 | expected.add(name) |
| 532 | if verdict.get(name) == "NOT_RUN": |
| 533 | agree += 1 |
| 534 | else: |
| 535 | disagree += 1 |
| 536 | bad.append((name, "expected-no-code-NOT_RUN", verdict.get(name))) |
| 537 | continue |
| 538 | task = load_task(split, r["tid"]) |
| 539 | byn = {c["n"]: c["status"] for c in r["cases"]} |
| 540 | for c in task["cases"]: |
| 541 | name = f"{r['tid']}.{c['n']:02d}" |
| 542 | expected.add(name) |
| 543 | g = verdict.get(name) |
| 544 | if g is None: |
| 545 | bad.append((name, "missing-in-gate", byn.get(c["n"]))) |
| 546 | disagree += 1 |
| 547 | continue |
| 548 | if r["class"] in ("compile_refused", "authz_violation"): |
| 549 | ok = g != "PASS" |
| 550 | else: |
| 551 | ok = (byn.get(c["n"]) == "pass") == (g == "PASS") |
| 552 | if ok: |
| 553 | agree += 1 |
| 554 | else: |
| 555 | disagree += 1 |
| 556 | bad.append((name, g, byn.get(c["n"]))) |
| 557 | if set(verdict) - expected: |
| 558 | print("INVALID unexpected gate verdicts") |
| 559 | return 1 |
| 560 | print(f"crosscheck agree={agree} disagree={disagree}") |
| 561 | for b_ in bad[:20]: |
| 562 | print("DISAGREE", *b_) |
| 563 | return 1 if disagree else 0 |
| 564 | |
| 565 | |
| 566 | def summary(rundir, split, arm): |
| 567 | """Publishable aggregate: sealed task and family names only as keyed opaque ids (benchlib.opaque).""" |
| 568 | if os.path.exists(os.path.join(rundir, f"summary-{split}.json")): |
| 569 | sys.exit("REFUSED existing summary; preserve it and use a new run directory") |
| 570 | if arm_lang(arm) == "om": |
| 571 | if crosscheck(rundir, split, os.path.join(rundir, "gate.log")): |
| 572 | sys.exit("INVALID Omega gate crosscheck; summary not written") |
| 573 | sys.path.insert(0, HERE) |
| 574 | from benchlib import opaque |
| 575 | merge = {} |
| 576 | if os.path.exists(CLUSTERS): |
| 577 | for grp in json.load(open(CLUSTERS))["merge"]: |
| 578 | for f in grp: |
| 579 | merge[f] = "+".join(sorted(grp)) |
| 580 | _, tids = task_dirs(split) |
| 581 | vp = os.path.join(rundir, f"verdicts-{split}.jsonl") |
| 582 | rows = {r["tid"]: r for r in (json.loads(l) for l in open(vp))} |
| 583 | if sorted(rows) != tids: |
| 584 | sys.exit(f"DENOMINATOR FAULT verdicts={len(rows)} manifest={len(tids)}") |
| 585 | out = [] |
| 586 | for tid in tids: |
| 587 | task = load_task(split, tid) |
| 588 | fam = task["family"] |
| 589 | r = rows[tid] |
| 590 | gp = os.path.join(rundir, "cand", tid, "gen.json") |
| 591 | g = json.load(open(gp)) if os.path.exists(gp) else {} |
| 592 | att = g.get("attempts", []) |
| 593 | first = None |
| 594 | if att and arm == "b": |
| 595 | first = att[0].get("compile_rc") == 0 |
| 596 | cases = r.get("cases", []) |
| 597 | out.append({"task": opaque(split, tid), "family": opaque(split, fam), |
| 598 | "cluster": opaque(split, merge.get(fam, fam)), "class": r["class"], |
| 599 | "attempts": len(att), "first_compiles": first, |
| 600 | "reply0_sha256": att[0]["reply_sha256"] if att else None, |
| 601 | "code_sha256": r.get("code_sha256"), |
| 602 | "completion_tokens": g.get("completion_tokens"), |
| 603 | "prompt_tokens": g.get("prompt_tokens"), |
| 604 | "prompt_tokens_processed": g.get("prompt_tokens_processed"), |
| 605 | "llm_wall_s": g.get("llm_wall_s"), "compile_s": r.get("compile_s"), |
| 606 | "cases_pass": sum(1 for c in cases if c["status"] == "pass"), "n_cases": r.get("n_cases"), |
| 607 | "case_wall_s": round(sum(c.get("wall_s", 0) for c in cases), 4)}) |
| 608 | tot = {"arm": arm, "split": split, "n": len(out), "classes": counts(out), |
| 609 | "completion_tokens": sum(o["completion_tokens"] or 0 for o in out), |
| 610 | "prompt_tokens_processed": sum(o["prompt_tokens_processed"] or 0 for o in out), |
| 611 | "llm_wall_s": round(sum(o["llm_wall_s"] or 0 for o in out), 3), |
| 612 | "cpu_core_s_modeled": round(CPU_CORES * sum(o["llm_wall_s"] or 0 for o in out), 3)} |
| 613 | p = os.path.join(rundir, f"summary-{split}.json") |
| 614 | with open(p, "w") as f: |
| 615 | json.dump({"totals": tot, "tasks": out}, f, indent=1, sort_keys=True) |
| 616 | print(p, json.dumps(tot, sort_keys=True)) |
| 617 | |
| 618 | |
| 619 | def main(): |
| 620 | global COMMON_IO |
| 621 | COMMON_IO = load_common_io() |
| 622 | ap = argparse.ArgumentParser() |
| 623 | ap.add_argument("cmd") |
| 624 | ap.add_argument("--arm") |
| 625 | ap.add_argument("--split") |
| 626 | ap.add_argument("--run") |
| 627 | ap.add_argument("--tasks") |
| 628 | ap.add_argument("--gate-log") |
| 629 | a = ap.parse_args() |
| 630 | if sha_file(OMC) != OMC_SHA: |
| 631 | sys.exit("FATAL omc sha256 mismatch") |
| 632 | if a.cmd == "gen": |
| 633 | os.makedirs(a.run, exist_ok=True) |
| 634 | _, tids = task_dirs(a.split) |
| 635 | if a.tasks: |
| 636 | want = a.tasks.split(",") |
| 637 | tids = [t for t in tids if t in want] |
| 638 | with open(os.path.join(a.run, "gen.log"), "a") as log: |
| 639 | for tid in tids: |
| 640 | gen_task(a.arm, load_task(a.split, tid), a.run, log) |
| 641 | elif a.cmd == "judge": |
| 642 | judge(a.run, a.split, a.arm) |
| 643 | elif a.cmd == "gatelist": |
| 644 | gatelist(a.run, a.split) |
| 645 | elif a.cmd == "crosscheck": |
| 646 | sys.exit(crosscheck(a.run, a.split, a.gate_log)) |
| 647 | elif a.cmd == "summary": |
| 648 | summary(a.run, a.split, a.arm) |
| 649 | else: |
| 650 | sys.exit("unknown command") |
| 651 | |
| 652 | |
| 653 | if __name__ == "__main__": |
| 654 | main() |