aien-train
AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished.
Brought by drakestapleton
aien-train / eval / omegese45 / check-demo
| 1 | #!/usr/bin/env python3 |
| 2 | """check-demo CASEDIR: independent check of one aien-train #45 demo case. |
| 3 | |
| 4 | Eval-owned (OE45Eval). Python standard library only. Reads the case directory |
| 5 | layout of the demo lane (evidence/OMEGESE45/demo/cases/<case>/): |
| 6 | request.en, goal.oe45, episode.oe45, response.en (required whenever |
| 7 | episode.oe45 exists; absent only for a translator refusal), facts.tsv, |
| 8 | artifacts/<dag>.{an0b,mjr1,mjv}, keys/coordinator-public-keys.txt, |
| 9 | keys/worker-public-keys.txt, pins/executor.p256, runtime.env. |
| 10 | |
| 11 | It never trusts aienet0-run's VERIFIED line, the demo adapter, the translator |
| 12 | or the model: bytes are re-parsed (oe_an0.py), signatures re-verified, the |
| 13 | matmul_u32 output digest recomputed, the episode re-checked against the |
| 14 | eval reference policy (oe45lib.py) and the English response re-parsed with |
| 15 | the eval-owned template parser (oe_en.py). |
| 16 | |
| 17 | Output: one `CHECK <name> PASS|FAIL|NOT_RUN <detail>` line per check, then |
| 18 | `FAITHFUL` (rc 0) or `UNFAITHFUL <first failing check>` (rc 1). rc 2: usage |
| 19 | or unreadable case directory. |
| 20 | """ |
| 21 | |
| 22 | import os |
| 23 | import sys |
| 24 | import re |
| 25 | |
| 26 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 27 | sys.path.insert(0, HERE) |
| 28 | |
| 29 | import oe45lib as L # noqa: E402 |
| 30 | import oe_an0 as A # noqa: E402 |
| 31 | import oe_en as E # noqa: E402 |
| 32 | import oe_episode as EP # noqa: E402 |
| 33 | |
| 34 | # Pinned recompute binary of the merged Aienet-0 path |
| 35 | # (aien-protocols evidence/aienet0-20261028/exercised/baseline.cmd). |
| 36 | RECOMPUTE_SHA256 = "d2cd7382e0dc64e49498ae3b1ceffc73f1ddcbd3ddcf93e6d607498ccd58ea12" |
| 37 | |
| 38 | # Trust root copied from the coordinator setup used by the demo receipts. |
| 39 | # Test fixtures substitute these globals only in tests/check_fixture.py; |
| 40 | # the production CLI has no key-override flag, environment or case-file route. |
| 41 | EXPECTED_KEYS = { |
| 42 | "submitter": bytes.fromhex("036a948b0403603a9e15776f0edbf646da9c5063a89e381a66b41f92b690156ac2"), |
| 43 | "verifier": bytes.fromhex("02e51ae486f1ca102aedd0759612682d7b5a859e1f48e885c6bbefed95c1d13f62"), |
| 44 | "executor": bytes.fromhex("028047c8f03c2fca0c43fe1e4f0bcbc4fb48f66eee4449caa55aa9cb6a734ba949"), |
| 45 | } |
| 46 | COORDINATOR_ED25519 = bytes.fromhex("897507c5dc043871fc4592c7c723a6bf4d90d94cf56d2db8dc71bf79e283b8c6") |
| 47 | VOLUNTEER_ED25519 = bytes.fromhex("058df02bc0cf534602497686ecb8e4ae6ae43d4dbb44fbf5fcb1a8c37a2ac1bd") |
| 48 | |
| 49 | # aienet0-run exit -> (class, allowed codes) (interface §2, §5; PROFILE.md "Exit codes") |
| 50 | EXIT_CLASS = { |
| 51 | 0: ("ok", {"-"}), |
| 52 | 10: ("fail", {"transport"}), |
| 53 | 11: ("refused", {"replay", "budget", "worker"}), |
| 54 | 12: ("fail", {"receipt"}), |
| 55 | 13: ("fail", {"recomp"}), |
| 56 | 14: ("fail", {"verdict"}), |
| 57 | 15: ("fail", {"io"}), |
| 58 | } |
| 59 | FACTS_COLS = ["job", "attempt", "m", "k", "n", "seed", "exit", "class", "code", |
| 60 | "dag_id", "mjr1_sha256", "mjr1_outcome", "verifier"] |
| 61 | |
| 62 | |
| 63 | class Report: |
| 64 | def __init__(self): |
| 65 | self.lines = [] |
| 66 | self.first_fail = None |
| 67 | |
| 68 | def add(self, name, status, detail=""): |
| 69 | self.lines.append("CHECK %s %s %s" % (name, status, detail)) |
| 70 | if status == "FAIL" and self.first_fail is None: |
| 71 | self.first_fail = "%s %s" % (name, detail) |
| 72 | |
| 73 | def ok(self, name, cond, detail=""): |
| 74 | self.add(name, "PASS" if cond else "FAIL", detail) |
| 75 | return cond |
| 76 | |
| 77 | |
| 78 | def read_text(path): |
| 79 | with open(path, "rb") as f: |
| 80 | b = f.read() |
| 81 | return b.decode("ascii") |
| 82 | |
| 83 | |
| 84 | def read_keys(path): |
| 85 | keys = {} |
| 86 | for line in read_text(path).splitlines(): |
| 87 | parts = line.split() |
| 88 | if len(parts) == 2: |
| 89 | keys[parts[0]] = bytes.fromhex(parts[1]) |
| 90 | return keys |
| 91 | |
| 92 | |
| 93 | def read_facts(path): |
| 94 | text = read_text(path) |
| 95 | lines = text.split("\n") |
| 96 | if lines and lines[-1] == "": |
| 97 | lines.pop() |
| 98 | if not lines or lines[0].split("\t") != FACTS_COLS: |
| 99 | raise ValueError("facts.tsv header") |
| 100 | rows = [] |
| 101 | for ln in lines[1:]: |
| 102 | f = ln.split("\t") |
| 103 | if len(f) != len(FACTS_COLS): |
| 104 | raise ValueError("facts.tsv row width: %r" % ln) |
| 105 | r = dict(zip(FACTS_COLS, f)) |
| 106 | for c in ("job", "attempt", "m", "k", "n", "seed", "exit"): |
| 107 | if not r[c].isdigit(): |
| 108 | raise ValueError("facts.tsv %s not decimal: %r" % (c, r[c])) |
| 109 | r[c] = int(r[c]) |
| 110 | rows.append(r) |
| 111 | return rows |
| 112 | |
| 113 | |
| 114 | def _hex(s, n): |
| 115 | return len(s) == n and all(c in "0123456789abcdef" for c in s) |
| 116 | |
| 117 | |
| 118 | def facts_row_rule(r): |
| 119 | """Interface v1.2 facts.tsv row rules. Returns the first violation or None.""" |
| 120 | if r["attempt"] not in (1, 2): |
| 121 | return "attempt %d not 1|2" % r["attempt"] |
| 122 | ec = EXIT_CLASS.get(r["exit"]) |
| 123 | if ec is None or r["class"] != ec[0] or r["code"] not in ec[1]: |
| 124 | return "exit %d class %s code %s outside exit map" % (r["exit"], r["class"], r["code"]) |
| 125 | if r["class"] == "ok": |
| 126 | if not (_hex(r["dag_id"], 64) and _hex(r["mjr1_sha256"], 64)): |
| 127 | return "ok row dag_id/mjr1_sha256 not 64 lowercase hex" |
| 128 | if r["mjr1_outcome"] != "1": |
| 129 | return "ok row mjr1_outcome %r != 1" % r["mjr1_outcome"] |
| 130 | if not (_hex(r["verifier"], 66) and r["verifier"][:2] in ("02", "03")): |
| 131 | return "ok row verifier not a compressed P-256 key" |
| 132 | else: |
| 133 | # v1.2 §5 L160 plus parent ruling: a non-ok row has '-' in mjr1_outcome and |
| 134 | # verifier; dag_id may carry the real document id (a replay refusal names the |
| 135 | # already-executed document); mjr1_sha256 is hex only when a receipt file |
| 136 | # exists (checked in check_dispatches). Both are '-' or 64 lowercase hex. |
| 137 | if (r["mjr1_outcome"], r["verifier"]) != ("-", "-"): |
| 138 | return "non-ok row carries mjr1_outcome/verifier" |
| 139 | for c in ("dag_id", "mjr1_sha256"): |
| 140 | if r[c] != "-" and not _hex(r[c], 64): |
| 141 | return "non-ok row %s neither '-' nor 64 lowercase hex" % c |
| 142 | if r["mjr1_sha256"] != "-" and r["dag_id"] == "-": |
| 143 | return "non-ok row mjr1_sha256 without dag_id" |
| 144 | return None |
| 145 | |
| 146 | |
| 147 | def facts_order_rule(rows): |
| 148 | """No row for a job after that job's ok row (v1.2).""" |
| 149 | done = set() |
| 150 | for i, r in enumerate(rows): |
| 151 | if r["job"] in done: |
| 152 | return "row%d job %d after its ok" % (i + 1, r["job"]) |
| 153 | if r["class"] == "ok": |
| 154 | done.add(r["job"]) |
| 155 | return None |
| 156 | |
| 157 | |
| 158 | def nonok_runtime_rule(case, row): |
| 159 | """Match exit and dag against dispatch.log and runner stderr, not facts. |
| 160 | |
| 161 | Restart may leave extra run.err files before outcome journalling. Do not |
| 162 | zip files with outcomes: match dag/failure, and check job/attempt separately. |
| 163 | """ |
| 164 | try: |
| 165 | outcomes = [ln.split() for ln in read_text(os.path.join(case, "dispatch.log")).splitlines() |
| 166 | if ln.startswith("outcome ")] |
| 167 | want = ["outcome", str(row["job"]), str(row["attempt"]), str(row["exit"]), row["dag_id"]] |
| 168 | if not any(p[:5] == want for p in outcomes): |
| 169 | return "dispatch outcome exit/dag/job/attempt differs" |
| 170 | logs = os.path.join(case, "logs") |
| 171 | marker = { |
| 172 | "transport": ("no volunteer connected:", "REFUSED TRANSPORT ", "TRANSPORT "), |
| 173 | "replay": ("REFUSED WORKER AN0_REPLAY",), |
| 174 | "budget": ("REFUSED WORKER AN0_BUDGET",), |
| 175 | "worker": ("REFUSED WORKER",), |
| 176 | "receipt": ("REFUSED AN0_",), |
| 177 | "recomp": ("REFUSED AN0_RECOMPUTE", "REFUSED AN0_EXECUTOR"), |
| 178 | "verdict": ("REFUSED AN0_VERDICT",), |
| 179 | "io": ("REFUSED AN0_OUTPUT_EXISTS", "Permission denied", "No such file", "I/O"), |
| 180 | }.get(row["code"], ()) |
| 181 | matched = False |
| 182 | for filename in os.listdir(logs): |
| 183 | if not filename.endswith("-run.err"): |
| 184 | continue |
| 185 | text = read_text(os.path.join(logs, filename)) |
| 186 | dags = re.findall(r"\bdag_id=([0-9a-f]{64})\b", text) |
| 187 | if row["dag_id"] != "-" and (not dags or any(d != row["dag_id"] for d in dags)): |
| 188 | continue |
| 189 | if row["dag_id"] == "-" and dags: |
| 190 | continue |
| 191 | pre_execution = row["code"] in ("transport", "replay", "budget", "worker") |
| 192 | wrong_receipt_stage = row["code"] == "receipt" and any( |
| 193 | x in text for x in ("REFUSED AN0_RECOMPUTE", "REFUSED AN0_VERDICT", "REFUSED AN0_OUTPUT_EXISTS")) |
| 194 | wrong_worker_subcode = row["code"] == "worker" and any( |
| 195 | x in text for x in ("REFUSED WORKER AN0_REPLAY", "REFUSED WORKER AN0_BUDGET")) |
| 196 | if (any(m in text for m in marker) and not wrong_receipt_stage and not wrong_worker_subcode |
| 197 | and (not pre_execution or "receipt sha256=" not in text)): |
| 198 | matched = True |
| 199 | break |
| 200 | if not matched: |
| 201 | return "runner stderr has no matching dag/failure (or reports execution)" |
| 202 | if row["code"] == "replay": |
| 203 | seen = read_text(os.path.join(case, "worker", "seen")).splitlines() |
| 204 | if not _hex(row["dag_id"], 64) or not any( |
| 205 | ln.split()[:2] == ["done", row["dag_id"]] for ln in seen): |
| 206 | return "replay dag is not done in worker/seen" |
| 207 | return None |
| 208 | except (OSError, ValueError, UnicodeDecodeError) as e: |
| 209 | return "runtime evidence missing/invalid: %s" % e |
| 210 | |
| 211 | |
| 212 | def check_episode(rep, case, msgs_text): |
| 213 | """Episode grammar, shape, reference-policy agreement, binding. Returns msgs or None.""" |
| 214 | try: |
| 215 | lines = L.parse_episode(msgs_text) |
| 216 | msgs = [L.parse_line(x) for x in lines] |
| 217 | except ValueError as e: |
| 218 | rep.ok("episode.parse", False, str(e)) |
| 219 | return None |
| 220 | rep.ok("episode.parse", True, "messages=%d" % len(msgs)) |
| 221 | why = EP.check_episode_shape(msgs) |
| 222 | if not rep.ok("episode.shape", why is None, why or ""): |
| 223 | return None |
| 224 | n_ids = L.episode_ids_len(lines) |
| 225 | rep.ok("episode.maxlen", n_ids <= 176, "ids=%d" % n_ids) |
| 226 | bad = [] |
| 227 | for i in L.decode_points(msgs): |
| 228 | want = L.policy_next(msgs[:i]) |
| 229 | if lines[i] != want: |
| 230 | bad.append("%d:%r!=%r" % (i, lines[i], want)) |
| 231 | rep.ok("episode.reference_policy", not bad, "; ".join(bad)) |
| 232 | unbound = [] |
| 233 | for i, m in enumerate(msgs): |
| 234 | if m.kind == "A" and m.jk == "job": |
| 235 | ok, why = EP.bind_current(msgs[0], m, msgs[:i]) |
| 236 | if not ok: |
| 237 | unbound.append("%d:%s" % (i, why)) |
| 238 | rep.ok("episode.binding", not unbound, "; ".join(unbound)) |
| 239 | goal_path = os.path.join(case, "goal.oe45") |
| 240 | if os.path.exists(goal_path): |
| 241 | rep.ok("goal.matches_episode", read_text(goal_path).rstrip("\n") == lines[0]) |
| 242 | else: |
| 243 | rep.add("goal.matches_episode", "FAIL", "goal.oe45 missing") |
| 244 | return lines, msgs |
| 245 | |
| 246 | |
| 247 | def check_dispatches(rep, case, msgs, rows, keys): |
| 248 | """facts.tsv rows <-> act job / res messages <-> signed artifacts.""" |
| 249 | acts = [(i, m) for i, m in enumerate(msgs) if m.kind == "A" and m.jk == "job"] |
| 250 | rep.ok("facts.one_row_per_dispatch", len(acts) == len(rows), |
| 251 | "act_job=%d rows=%d" % (len(acts), len(rows))) |
| 252 | for idx, row in enumerate(rows): |
| 253 | why = facts_row_rule(row) |
| 254 | rep.ok("row%d.facts_format" % (idx + 1), why is None, why or "") |
| 255 | why = facts_order_rule(rows) |
| 256 | rep.ok("facts.no_row_after_ok", why is None, why or "") |
| 257 | goal = msgs[0] |
| 258 | attempts = {} |
| 259 | committed = [] |
| 260 | for idx, ((i, act), row) in enumerate(zip(acts, rows)): |
| 261 | tag = "row%d" % (idx + 1) |
| 262 | j = L.current_job_index(msgs[:i]) |
| 263 | if j is None: |
| 264 | rep.ok(tag + ".binding", False, "binding: no current job") |
| 265 | continue |
| 266 | attempts[j] = attempts.get(j, 0) + 1 |
| 267 | rep.ok(tag + ".job_attempt", row["job"] == j + 1 and row["attempt"] == attempts[j], |
| 268 | "job=%d attempt=%d want %d %d" % (row["job"], row["attempt"], j + 1, attempts[j])) |
| 269 | rep.ok(tag + ".binds_goal", (row["m"], row["k"], row["n"]) == tuple(goal.dims) |
| 270 | and row["seed"] == goal.seeds[j] and tuple(act.dims) == tuple(goal.dims) |
| 271 | and act.seeds[0] == goal.seeds[j], |
| 272 | "m=%d k=%d n=%d seed=%d" % (row["m"], row["k"], row["n"], row["seed"])) |
| 273 | res = msgs[i + 1] if i + 1 < len(msgs) and msgs[i + 1].kind == "R" else None |
| 274 | if res is None: |
| 275 | rep.add(tag + ".res_matches", "FAIL", "no res after dispatch") |
| 276 | else: |
| 277 | rep.ok(tag + ".res_matches", res.cls == row["class"] |
| 278 | and (res.code or "-") == row["code"], res.text) |
| 279 | if row["class"] != "ok": |
| 280 | why = nonok_runtime_rule(case, row) |
| 281 | rep.ok(tag + ".runtime_evidence", why is None, why or "") |
| 282 | # a non-ok row claims a receipt hash only if that receipt file exists |
| 283 | if row["mjr1_sha256"] != "-" and _hex(row["dag_id"], 64): |
| 284 | p = os.path.join(case, "artifacts", row["dag_id"] + ".mjr1") |
| 285 | rep.ok(tag + ".nonok_receipt_file", os.path.exists(p) |
| 286 | and A.sha(open(p, "rb").read()).hex() == row["mjr1_sha256"], |
| 287 | "artifacts/%s.mjr1" % row["dag_id"]) |
| 288 | continue |
| 289 | dag = row["dag_id"] |
| 290 | base = os.path.join(case, "artifacts", dag) |
| 291 | if not os.path.exists(base + ".an0b"): |
| 292 | rep.add(tag + ".artifacts", "FAIL", "missing %s.an0b" % dag) |
| 293 | continue |
| 294 | rd = lambda ext: open(base + ext, "rb").read() if os.path.exists(base + ext) else None |
| 295 | an0b, mjr1, mjv = rd(".an0b"), rd(".mjr1"), rd(".mjv") |
| 296 | results, job = A.check_triple(an0b, mjr1, mjv, keys["submitter"], keys["executor"], keys["verifier"]) |
| 297 | for name, status, detail in results: |
| 298 | rep.add("%s.%s" % (tag, name), status, detail) |
| 299 | rep.ok(tag + ".bundle_binds_row", job == (row["m"], row["k"], row["n"], row["seed"]), |
| 300 | "bundle=%s" % (job,)) |
| 301 | rep.ok(tag + ".dag_id", A.sha(A.parse_bundle(an0b)["document"]).hex() == dag) |
| 302 | if mjr1 is not None: |
| 303 | rep.ok(tag + ".mjr1_sha256", A.sha(mjr1).hex() == row["mjr1_sha256"]) |
| 304 | rep.ok(tag + ".mjr1_outcome", row["mjr1_outcome"] == str(mjr1[5]), |
| 305 | "facts=%s byte5=%d" % (row["mjr1_outcome"], mjr1[5])) |
| 306 | rep.ok(tag + ".verifier_key", row["verifier"] == keys["verifier"].hex()) |
| 307 | committed.append(dag) |
| 308 | rep.ok("facts.no_duplicate_commit", len(committed) == len(set(committed)), |
| 309 | "verified_dags=%d" % len(committed)) |
| 310 | return committed |
| 311 | |
| 312 | |
| 313 | def main(argv): |
| 314 | if len(argv) != 2 or not os.path.isdir(argv[1]): |
| 315 | sys.stderr.write("usage: check-demo CASEDIR\n") |
| 316 | return 2 |
| 317 | case = argv[1] |
| 318 | rep = Report() |
| 319 | try: |
| 320 | rows = read_facts(os.path.join(case, "facts.tsv")) |
| 321 | except (OSError, ValueError, UnicodeDecodeError) as e: |
| 322 | sys.stderr.write("check-demo: %s\n" % e) |
| 323 | return 2 |
| 324 | rep.ok("facts.parse", True, "rows=%d" % len(rows)) |
| 325 | keys = {} |
| 326 | try: |
| 327 | ck = read_keys(os.path.join(case, "keys", "coordinator-public-keys.txt")) |
| 328 | wk = read_keys(os.path.join(case, "keys", "worker-public-keys.txt")) |
| 329 | pin = bytes.fromhex(read_text(os.path.join(case, "pins", "executor.p256")).strip()) |
| 330 | volunteer = bytes.fromhex(read_text(os.path.join(case, "pins", "volunteer.ed25519")).strip()) |
| 331 | keys = {"submitter": ck["submitter.p256"], "verifier": ck["verifier.p256"], "executor": pin} |
| 332 | rep.ok("keys.executor_pin", wk.get("executor.p256") == pin, pin.hex()) |
| 333 | trusted = (keys == EXPECTED_KEYS and volunteer == VOLUNTEER_ED25519 |
| 334 | and ck == {"coordinator.ed25519": COORDINATOR_ED25519, |
| 335 | "submitter.p256": EXPECTED_KEYS["submitter"], |
| 336 | "verifier.p256": EXPECTED_KEYS["verifier"]} |
| 337 | and wk == {"volunteer.ed25519": VOLUNTEER_ED25519, |
| 338 | "executor.p256": EXPECTED_KEYS["executor"]}) |
| 339 | rep.ok("keys.trust_root", trusted, "coordinator and executor must match eval pin") |
| 340 | except (OSError, ValueError, KeyError) as e: |
| 341 | if rows: |
| 342 | rep.add("keys.read", "FAIL", str(e)) |
| 343 | else: |
| 344 | rep.add("keys.read", "NOT_RUN", "nothing dispatched: %s" % e) |
| 345 | env_path = os.path.join(case, "runtime.env") |
| 346 | if os.path.exists(env_path): |
| 347 | env = dict(l.split("=", 1) for l in read_text(env_path).splitlines() if "=" in l) |
| 348 | rep.ok("runtime.recompute_pin", env.get("RECOMPUTE_SHA256", "").strip("'\"") == RECOMPUTE_SHA256, |
| 349 | env.get("RECOMPUTE_SHA256", "missing")) |
| 350 | elif rows: |
| 351 | rep.add("runtime.recompute_pin", "FAIL", "runtime.env missing") |
| 352 | |
| 353 | ep_path = os.path.join(case, "episode.oe45") |
| 354 | resp_path = os.path.join(case, "response.en") |
| 355 | response = read_text(resp_path) if os.path.exists(resp_path) else None |
| 356 | if not os.path.exists(ep_path): |
| 357 | # translator refusal: nothing may have been dispatched or reported |
| 358 | rep.ok("nothing_dispatched", not rows, "rows=%d" % len(rows)) |
| 359 | art = os.path.join(case, "artifacts") |
| 360 | rep.ok("no_artifacts", not os.path.isdir(art) or not os.listdir(art)) |
| 361 | rep.ok("no_english_report", response is None, |
| 362 | "response.en present" if response is not None else "") |
| 363 | else: |
| 364 | got = check_episode(rep, case, read_text(ep_path)) |
| 365 | if got is not None and (keys or not rows): |
| 366 | lines, msgs = got |
| 367 | if rows or any(m.kind == "A" and m.jk == "job" for m in msgs): |
| 368 | check_dispatches(rep, case, msgs, rows, keys) |
| 369 | else: |
| 370 | rep.ok("nothing_dispatched", not rows) |
| 371 | if response is None: |
| 372 | # every journalled episode ends in a report the translator must render; |
| 373 | # a silent run is not a faithful answer |
| 374 | rep.ok("english.present", False, "no response.en for a journalled episode") |
| 375 | else: |
| 376 | for name, status, detail in E.check_response(response, msgs, rows): |
| 377 | rep.add(name, status, detail) |
| 378 | for ln in rep.lines: |
| 379 | print(ln) |
| 380 | if rep.first_fail is None: |
| 381 | print("FAITHFUL") |
| 382 | return 0 |
| 383 | print("UNFAITHFUL %s" % rep.first_fail) |
| 384 | return 1 |
| 385 | |
| 386 | |
| 387 | if __name__ == "__main__": |
| 388 | sys.exit(main(sys.argv)) |