interplane.Get Omega
Read in your language

omega-mcp

aien-dev/omega-mcp

Brought by drakestapleton

branch main Branches Tags History

omega-mcp / tools / check-reference.py

306 lines · 13816 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Oracle for data/reference.json and data/examples/*.om (a verification tool, not part of the server).
3
4The pin is the PIN file at the repository root (two lines: `omega-mv REV` and `omc-sha256 SHA`).
5Checks, against omega-mv at the pinned commit (read with `git show REV:path`, never the worktree):
6 1. the keyword set equals the compiler's keyword table (fn kw + fn kw2 in seed/omc/omc.om),
7 re-derived here from the source, with the same keyword id and source line; data/reference.json names
8 the PIN revision and omc;
9 2. every citation `omega-mv@<pin8> path:A[-B]` names lines A..B whose text contains its quote;
10 3. every word, error and trap entry has the required members; every word's example contains the word;
11 4. every example compiles with the pinned omc and meets its expectation (run in a bwrap sandbox);
12 5. the compiler I/O errors 1 and 2 reproduce as described.
13--self-test also runs three negative controls (a moved citation, a wrong example expectation, a missing
14keyword) and requires each to be detected.
15Exit 0 when every check passes; 1 with the failures listed otherwise.
16"""
17import argparse, copy, hashlib, json, os, re, subprocess, sys, tempfile
18
19ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
20
21
22def read_pin():
23 """(omega-mv revision, omc sha256) from the PIN file, the only place the pin is written."""
24 k = open(os.path.join(ROOT, "PIN")).read().split()
25 if len(k) != 4 or k[0] != "omega-mv" or k[2] != "omc-sha256" or not re.fullmatch(r"[0-9a-f]{40}", k[1]) \
26 or not re.fullmatch(r"[0-9a-f]{64}", k[3]):
27 raise SystemExit("PIN: expected two lines, `omega-mv <40 hex>` and `omc-sha256 <64 hex>`")
28 return k[1], k[3]
29
30
31PIN, OMC_SHA = read_pin()
32REF_RE = re.compile(r"^omega-mv@" + PIN[:8] + r" ([A-Za-z0-9_./-]+):(\d+)(?:-(\d+))?$")
33WORD_KEYS = ["table", "id", "category", "profile", "form", "arity", "types", "result", "summary", "citations", "example"]
34ENTRY_KEYS = ["meaning", "cause", "fix", "citations"]
35
36
37class Src:
38 def __init__(self, repo):
39 self.repo, self.cache = repo, {}
40
41 def lines(self, path):
42 if path not in self.cache:
43 out = subprocess.run(["git", "-C", self.repo, "show", PIN + ":" + path], capture_output=True, check=True)
44 self.cache[path] = out.stdout.decode().split("\n")
45 return self.cache[path]
46
47
48def kwtable(src):
49 """(word, id, line, table) for every entry of fn kw / fn kw2, decoded like omc's packed words."""
50 L = src.lines("seed/omc/omc.om")
51 start = L.index("fn kw w ulong to ulong")
52 out, packed, w, line, table = [], None, None, None, "kw"
53 for i in range(start, len(L)):
54 s = L[i]
55 if s.startswith("fn kw2 "):
56 table = "kw2"
57 if s.startswith("fn ") and not s.startswith("fn kw"):
58 break
59 m = re.match(r"packed = or ulong (\d+) shl ulong (\d+) 8$", s)
60 if m:
61 packed = int(m[1]) | int(m[2]) << 8
62 continue
63 m = re.match(r"packed = or packed shl ulong (\d+) (\d+)$", s)
64 if m:
65 packed |= int(m[1]) << int(m[2])
66 continue
67 m = re.match(r"if eq w (\d+)$", s)
68 if m:
69 w, line = int(m[1]), i + 1
70 continue
71 if s == "if eq w packed":
72 w, line = packed, i + 1
73 continue
74 m = re.match(r"ret (\d+)$", s)
75 if m and w is not None:
76 out.append((w.to_bytes(8, "little").rstrip(b"\0").decode(), int(m[1]), line, table))
77 w = None
78 return out
79
80
81def norm(s):
82 return " ".join(s.split())
83
84
85def check_cites(src, where, cites, errs):
86 if not isinstance(cites, list) or not cites:
87 errs.append(f"{where}: no citations")
88 return
89 for c in cites:
90 m = REF_RE.match(c.get("ref", ""))
91 if not m:
92 errs.append(f"{where}: bad citation ref {c.get('ref')!r}")
93 continue
94 path, a = m[1], int(m[2])
95 b = int(m[3]) if m[3] else a
96 try:
97 L = src.lines(path)
98 except subprocess.CalledProcessError:
99 errs.append(f"{where}: {path} does not exist at the pin")
100 continue
101 if not (1 <= a <= b <= len(L)):
102 errs.append(f"{where}: {path}:{a}-{b} outside the file ({len(L)} lines)")
103 continue
104 if norm(c.get("quote", "")) == "" or norm(c["quote"]) not in norm(" ".join(L[a - 1:b])):
105 errs.append(f"{where}: {path}:{a}-{b} does not contain {c.get('quote')!r}")
106
107
108def tokens(text):
109 return set(re.sub(r"([()])", r" \1 ", text).split())
110
111
112def sandbox_run(binary, timeout):
113 cmd = ["/usr/bin/bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--clearenv",
114 "--ro-bind", binary, "/p", "--tmpfs", "/w", "--chdir", "/w", "/p"]
115 try:
116 r = subprocess.run(cmd, stdin=subprocess.DEVNULL, capture_output=True, timeout=timeout)
117 return r.returncode, r.stdout
118 except subprocess.TimeoutExpired:
119 return "timeout", b""
120
121
122def check_example(omc, eid, source, exp, errs, tmp):
123 where = f"example {eid}"
124 p = os.path.join(tmp, eid)
125 r = subprocess.run([omc], input=source.encode(), capture_output=True, timeout=60)
126 mode = exp.get("mode")
127 if mode == "error":
128 want = f"omc: line {exp['line']}: error {exp['code']}\n".encode()
129 if r.returncode != exp["code"] or not r.stderr.startswith(want):
130 errs.append(f"{where}: wanted error {exp['code']} line {exp['line']}, got rc {r.returncode} {r.stderr[:80]!r}")
131 return
132 if r.returncode != 0:
133 errs.append(f"{where}: compile failed rc {r.returncode} {r.stderr[:80]!r}")
134 return
135 if mode == "compile":
136 return
137 with open(p, "wb") as f:
138 f.write(r.stdout)
139 os.chmod(p, 0o700)
140 rc, out = sandbox_run(p, 20)
141 if mode == "trap":
142 if rc != 100 + exp["trap"]:
143 errs.append(f"{where}: wanted trap {exp['trap']} (exit {100 + exp['trap']}), got {rc}")
144 elif mode == "run":
145 if rc != exp["exit"]:
146 errs.append(f"{where}: wanted exit {exp['exit']}, got {rc} stdout {out[:60]!r}")
147 if "stdout" in exp and out.decode("utf-8", "replace") != exp["stdout"]:
148 errs.append(f"{where}: wanted stdout {exp['stdout']!r}, got {out[:80]!r}")
149 else:
150 errs.append(f"{where}: unknown mode {mode!r}")
151
152
153def check(ref, exdir, src, omc, run_examples=True):
154 errs = []
155 table = kwtable(src)
156 if not table:
157 errs.append("keyword table: the decoder found no entries at the pin")
158 if ref.get("pin") != {"omega_mv": PIN, "omc_sha256": OMC_SHA}:
159 errs.append(f"reference.json pin {ref.get('pin')} is not PIN")
160 words = ref.get("words", {})
161 want = {w: (i, line, t) for w, i, line, t in table}
162 for w in sorted(set(want) - set(words)):
163 errs.append(f"keyword {w!r} has no lookup entry")
164 for w in sorted(set(words) - set(want)):
165 errs.append(f"lookup entry {w!r} is not a compiler keyword")
166 examples = ref.get("examples", {})
167 for w, e in words.items():
168 for k in WORD_KEYS:
169 if k not in e:
170 errs.append(f"word {w}: missing {k}")
171 if w in want:
172 i, line, t = want[w]
173 if e.get("id") != i or e.get("table") != t:
174 errs.append(f"word {w}: id/table {e.get('id')}/{e.get('table')} != {i}/{t}")
175 first = (e.get("citations") or [{}])[0].get("ref", "")
176 if first != f"omega-mv@{PIN[:8]} seed/omc/omc.om:{line}-{line + 1}":
177 errs.append(f"word {w}: first citation {first!r} is not its keyword-table line {line}")
178 check_cites(src, f"word {w}", e.get("citations"), errs)
179 ex = e.get("example")
180 if ex not in examples:
181 errs.append(f"word {w}: example {ex!r} missing")
182 elif os.path.exists(os.path.join(exdir, ex + ".om")):
183 if w not in tokens(open(os.path.join(exdir, ex + ".om")).read()):
184 errs.append(f"word {w}: example {ex} does not use the word")
185 for sect, lo, hi, holes in (("errors", 1, 30, set()), ("traps", 1, 14, set())):
186 d = ref.get(sect, {})
187 keys = {str(k) for k in range(lo, hi + 1) if k not in holes}
188 if set(d) != keys:
189 errs.append(f"{sect}: keys {sorted(set(d) ^ keys)} differ")
190 for k, e in d.items():
191 for m in ENTRY_KEYS:
192 if not e.get(m):
193 errs.append(f"{sect} {k}: missing {m}")
194 check_cites(src, f"{sect} {k}", e.get("citations"), errs)
195 ex = e.get("example")
196 if ex is None:
197 if not e.get("reproduce") and not e.get("example_note"):
198 errs.append(f"{sect} {k}: neither example, reproduce nor example_note")
199 continue
200 exp = examples.get(ex)
201 if exp is None:
202 errs.append(f"{sect} {k}: example {ex!r} missing")
203 elif sect == "errors" and (exp.get("mode") != "error" or exp.get("code") != int(k)):
204 errs.append(f"errors {k}: example {ex} expects {exp}")
205 elif sect == "traps" and (exp.get("mode") != "trap" or exp.get("trap") != int(k)):
206 errs.append(f"traps {k}: example {ex} expects {exp}")
207 for t, e in ref.get("topics", {}).items():
208 check_cites(src, f"topic {t}", e.get("citations"), errs)
209 if "summary" not in e:
210 errs.append(f"topic {t}: missing summary")
211 if e.get("example") is not None and e["example"] not in examples:
212 errs.append(f"topic {t}: example {e['example']!r} missing")
213 files = {f[:-3] for f in os.listdir(exdir) if f.endswith(".om")}
214 if files != set(examples):
215 errs.append(f"example files and expectations differ: {sorted(files ^ set(examples))}")
216 for eid in examples:
217 if not re.fullmatch(r"[a-z0-9_]{1,63}", eid):
218 errs.append(f"example id {eid!r} is not [a-z0-9_]{{1,63}}")
219 if run_examples:
220 with tempfile.TemporaryDirectory() as tmp:
221 for eid in sorted(set(examples) & files):
222 check_example(omc, eid, open(os.path.join(exdir, eid + ".om")).read(), examples[eid], errs, tmp)
223 for k in ("1", "2", "26"):
224 rep = ref.get("errors", {}).get(k, {}).get("reproduce")
225 if rep:
226 errs += check_reproduce(omc, int(k), tmp)
227 return errs
228
229
230def check_reproduce(omc, code, tmp):
231 """error 1: stdin is a directory (read fails); error 2: stdout is /dev/full (write fails);
232 error 26: the environment entry OMC_MEMORY_MAX is malformed."""
233 if code == 1:
234 d = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
235 try:
236 r = subprocess.run([omc], stdin=d, capture_output=True)
237 finally:
238 os.close(d)
239 elif code == 26:
240 r = subprocess.run([omc], stdin=subprocess.DEVNULL, capture_output=True, env={"OMC_MEMORY_MAX": "12x"})
241 else:
242 p = os.path.join(tmp, "ok.om")
243 open(p, "w").write("fn main to int\nret 0\nend\n")
244 with open(p, "rb") as i, open("/dev/full", "wb") as o:
245 r = subprocess.run([omc], stdin=i, stdout=o, stderr=subprocess.PIPE)
246 if r.returncode != code or f"error {code}\n".encode() not in r.stderr:
247 return [f"errors {code}: reproduce gave rc {r.returncode} {r.stderr!r}"]
248 return []
249
250
251def main():
252 ap = argparse.ArgumentParser()
253 ap.add_argument("--omega-src", required=True, help="a git clone of aien-dev/omega-mv containing the pin")
254 ap.add_argument("--omc", required=True, help="the pinned omc binary")
255 ap.add_argument("--data", default=os.path.join(os.path.dirname(__file__), "..", "data"))
256 ap.add_argument("--self-test", action="store_true", help="also run the negative controls")
257 a = ap.parse_args()
258 if hashlib.sha256(open(a.omc, "rb").read()).hexdigest() != OMC_SHA:
259 print("FAIL omc is not the pinned binary")
260 return 1
261 src = Src(a.omega_src)
262 raw = open(os.path.join(a.data, "reference.json"), "rb").read()
263 ref = json.loads(raw)
264 exdir = os.path.join(a.data, "examples")
265 errs = check(ref, exdir, src, a.omc)
266 if len(raw) > 393216:
267 errs.append(f"reference.json is {len(raw)} bytes, over the server's 393216")
268 for e in errs:
269 print("FAIL", e)
270 nw, ne = len(ref["words"]), len(ref["examples"])
271 print(f"words {nw} errors {len(ref['errors'])} traps {len(ref['traps'])} topics {len(ref['topics'])} "
272 f"examples {ne} bytes {len(raw)} failures {len(errs)}")
273 rc = 1 if errs else 0
274 if a.self_test:
275 rc |= self_test(ref, exdir, src, a.omc)
276 print("PASS" if rc == 0 else "FAIL")
277 return rc
278
279
280def self_test(ref, exdir, src, omc):
281 rc = 0
282 m1 = copy.deepcopy(ref)
283 c = m1["words"]["add"]["citations"][0]
284 path, a, b = re.match(r"^(.*):(\d+)-(\d+)$", c["ref"]).groups()
285 c["ref"] = f"{path}:{int(a) + 3}-{int(b) + 3}"
286 m2 = copy.deepcopy(ref)
287 m2["examples"]["hello"]["exit"] = m2["examples"]["hello"]["exit"] + 1
288 m3 = copy.deepcopy(ref)
289 del m3["words"]["mapbind"]
290 for name, mut, run in (("moved citation", m1, False), ("wrong expectation", m2, True), ("missing keyword", m3, False)):
291 if run:
292 m = copy.deepcopy(mut)
293 m["examples"] = {"hello": mut["examples"]["hello"]}
294 errs = []
295 with tempfile.TemporaryDirectory() as tmp:
296 check_example(omc, "hello", open(os.path.join(exdir, "hello.om")).read(), m["examples"]["hello"], errs, tmp)
297 else:
298 errs = check(mut, exdir, src, omc, run_examples=False)
299 ok = bool(errs)
300 print(f"negative control ({name}): {'DETECTED' if ok else 'MISSED'}: {errs[:1]}")
301 rc |= 0 if ok else 1
302 return rc
303
304
305if __name__ == "__main__":
306 sys.exit(main())