Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
close SHIP GATE findings: durability proof, F2 wording, fullmatch reachability, stale docstring, duplicated tree walk, vocab contract
monotophic40c7c019b2f0
diff --git a/c/tests/test_eval_glm.py b/c/tests/test_eval_glm.pyindex 581c3fad..49f327a0 100644--- a/c/tests/test_eval_glm.py+++ b/c/tests/test_eval_glm.py@@ -149,6 +149,18 @@ class EvalGlmEvidenceTests(unittest.TestCase):self.assertEqual(value, -8.553458)self.assertEqual((contlen, greedy), (4096, 1))+ def test_direct_call_rejects_trailing_newline_record(self):+ # See parse_score_result's own docstring: _SCORE_RE's "$" anchor+ # matches just before a trailing "\n" as well as at true+ # end-of-string, so fullmatch -> match/search would accept a+ # newline-terminated record fullmatch correctly rejects. The+ # classifier's own callers strip the newline first and are+ # provably out of reach of this (see the docstring), but this+ # function is also called directly -- pin the direct-call+ # contract so a future weakening doesn't slip in unnoticed there.+ with self.assertRaises(EVAL.EvidenceError):+ EVAL.parse_score_result("-8.553458 4096 1\n")+def test_parse_c17g_rejects_trailing_garbage(self):# parse_c17g is only ever reached, elsewhere in this module,# through _SCORE_RE's own "^...$"-anchored capture group, which@@ -357,6 +369,62 @@ class EvalGlmEvidenceTests(unittest.TestCase):# than raise at all.self.assertFalse(EVAL.is_score_preamble(banner.rstrip("\n")))+ def test_oversized_vocab_json_refuses_as_evidence_error(self):+ # Same error-contract class as F3, in a different function:+ # json.loads() raises a bare ValueError (not its+ # json.JSONDecodeError subclass) for an integer literal beyond+ # Python's 4300-digit int-string conversion limit, which+ # score_snapshot_vocab's except clause did not catch -- the+ # bare ValueError escaped main()'s only try/except around this+ # call (which catches EvidenceError to write the INCOMPLETE+ # marker and return before ever launching the engine), so+ # main() crashed outright with NO INCOMPLETE marker written at+ # all, worse than the ordinary prelaunch-refusal contract every+ # other pre-engine-launch failure gets.+ huge_vocab = "1" + "0" * 4300+ with tempfile.TemporaryDirectory() as tmp:+ (pathlib.Path(tmp) / "config.json").write_text(+ '{"vocab_size": ' + huge_vocab + '}\n')+ with self.assertRaises(EVAL.EvidenceError):+ EVAL.score_snapshot_vocab(tmp)++ def test_oversized_vocab_json_marks_incomplete_end_to_end(self):+ # The end-to-end contract test_oversized_vocab_json_refuses_+ # as_evidence_error's unit-level pin implies: main() must reach+ # prelaunch_incomplete() (INCOMPLETE marker written, engine+ # never launched, exit 1) rather than crash uncaught.+ class Encoded:+ ids = [1, 2]++ class FakeTokenizer:+ @staticmethod+ def from_file(path):+ return FakeTokenizer()++ @staticmethod+ def encode(text):+ return Encoded()++ huge_vocab = "1" + "0" * 4300+ with tempfile.TemporaryDirectory() as tmp:+ output = pathlib.Path(tmp) / "results.csv"+ (pathlib.Path(tmp) / "config.json").write_text(+ '{"vocab_size": ' + huge_vocab + '}\n')+ argv = [+ "eval_glm.py", "--snap", tmp, "--tasks", "smoke",+ "--limit", "1", "--glm", "/fake/glm", "--out",+ str(output),+ ]+ tokenizers = types.SimpleNamespace(Tokenizer=FakeTokenizer)+ with mock.patch.object(sys, "argv", argv), \+ mock.patch.dict(sys.modules, {"tokenizers": tokenizers}), \+ mock.patch.object(+ EVAL.subprocess, "Popen",+ side_effect=AssertionError("engine launched")):+ rc = EVAL.main()+ self.assertEqual(rc, 1)+ self.assertIn("# INCOMPLETE:", output.read_text())+def test_banner_kernels_and_load_boundaries_are_exact(self):self.assertEqual(EVAL.parse_engine_banner(self.BANNER)["kernel"], "neon-i8mm")@@ -471,6 +539,93 @@ class EvalGlmEvidenceTests(unittest.TestCase):"# INCOMPLETE: evaluator terminated before a complete ""denominator", text)+ def test_row_is_durable_on_disk_before_the_run_finishes(self):+ # test_result_rows_are_written_and_flushed_incrementally (above)+ # is named for the per-row flush but cannot actually detect+ # losing it: that test reads the output file only AFTER+ # EVAL.main() has unwound through its `finally` block, which+ # closes out_f (and Python flushes a file on close) regardless+ # of whether any PER-ROW flush ever ran. It defends the ARTIFACT+ # after a clean-ish exit, not the PROPERTY of durability DURING+ # the run.+ #+ # This test instead opens a SECOND, independent file handle on+ # the same path while main() is still running (has not+ # returned) and reads through it -- a second handle can only+ # see bytes actually flushed to the OS by the writer, never+ # bytes still sitting only in the writer's own buffer. The+ # probe runs from inside the fake stdout generator, resumed+ # only once the consumer (main()'s per-line loop body, including+ # write_result_row + out_f.flush() for that line) has fully+ # finished with the PREVIOUS line and is asking for the next one+ # -- so a snapshot taken there reflects exactly what has been+ # made durable so far, mid-run.+ class Encoded:+ ids = [1, 2]++ class FakeTokenizer:+ @staticmethod+ def from_file(path):+ return FakeTokenizer()++ @staticmethod+ def encode(text):+ return Encoded()++ class ProbingStdout:+ def __init__(self, lines, probe_path):+ self._lines = list(lines)+ self._probe_path = probe_path+ self.snapshots = []++ def __iter__(self):+ for line in self._lines:+ yield line+ try:+ with open(self._probe_path) as f:+ self.snapshots.append(f.read())+ except FileNotFoundError:+ self.snapshots.append("")++ with tempfile.TemporaryDirectory() as tmp:+ output = pathlib.Path(tmp) / "results.csv"+ (pathlib.Path(tmp) / "config.json").write_text(+ '{"vocab_size":3}\n')+ stdout = ProbingStdout((+ self.BANNER + "\n",+ self.loaded("absent", 2) + "\n",+ "-1 2 1\n",+ "-2 2 0\n",+ ), str(output))+ process = types.SimpleNamespace(+ returncode=0, stderr=(), stdout=stdout,+ wait=lambda: 0, poll=lambda: 0, terminate=lambda: None)+ argv = [+ "eval_glm.py", "--snap", tmp, "--tasks", "smoke",+ "--limit", "1", "--glm", "/fake/glm", "--out",+ str(output),+ ]+ tokenizers = types.SimpleNamespace(Tokenizer=FakeTokenizer)+ with mock.patch.object(sys, "argv", argv), \+ mock.patch.dict(sys.modules, {"tokenizers": tokenizers}), \+ mock.patch.object(EVAL.subprocess, "Popen",+ return_value=process):+ rc = EVAL.main()+ self.assertEqual(rc, 0)+ # snapshots[0]/[1]: after the banner/load preamble lines, before+ # any SCORE result -- no row yet.+ self.assertNotIn(",-1,1\n", stdout.snapshots[0].replace(".000000", ""))+ self.assertNotIn(",-1,1\n", stdout.snapshots[1].replace(".000000", ""))+ # snapshots[2]: taken right after the FIRST SCORE line was fully+ # processed but BEFORE the second one is even requested --+ # main() has not returned. The first row must already be+ # readable through the independent handle; the second must not.+ first_row_snapshot = stdout.snapshots[2].replace(".000000", "")+ self.assertIn(",-1,1\n", first_row_snapshot,+ "first row not durable before the run finished -- "+ "the per-row flush is not doing its job")+ self.assertNotIn(",-2,0\n", first_row_snapshot)+def test_child_is_terminated_on_mid_run_interrupt_or_exception(self):# SIGINT/SIGTERM/any exception mid-run must not leave the# engine child running. The fake engine here never exits on itsdiff --git a/c/tests/test_pack_python.py b/c/tests/test_pack_python.pyindex fee5a4fd..d17f8130 100644--- a/c/tests/test_pack_python.py+++ b/c/tests/test_pack_python.py@@ -59,6 +59,16 @@ _spec.loader.exec_module(PACK)class PackPythonNeededTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ # test_the_real_tree_carries_the_case_that_started_this and+ # test_engine_evidence_is_needed_by_the_real_tree both assert+ # against the SAME PACK.needed(HERE.parent) result (a real,+ # non-trivial AST-parsing walk of this checkout's own c/ tree,+ # ~0.3s each) -- computed once here and shared, rather than+ # paying for it twice on every run of this suite forever.+ cls.real_tree_paths = PACK.needed(HERE.parent)+def make_tree(self, root):"""A minimal coli-shaped tree: coli imports `foo` and invokestools/bar.py as a subprocess; bar.py itself imports tools/baz.py,@@ -160,7 +170,7 @@ class PackPythonNeededTests(unittest.TestCase):iq3_pack opens iq3xxs_grid.json next to itself. Both were absent fromevery published archive. Assert the real pair and the test dies withthe real bug if either edge is ever dropped again."""- paths = PACK.needed(HERE.parent)+ paths = self.real_tree_pathsself.assertIn(TOOLS / "iq3_pack.py", paths,"reached only through a subprocess-launched script's import")self.assertIn(TOOLS / "iq3xxs_grid.json", paths,@@ -173,7 +183,7 @@ class PackPythonNeededTests(unittest.TestCase):this suite exists to defend. It is a second real-tree case rather thana replacement for the one above -- that one pins the historical bug,this one pins the edge the branch adds."""- paths = PACK.needed(HERE.parent)+ paths = self.real_tree_pathsself.assertIn(TOOLS / "engine_evidence.py", paths)diff --git a/c/tools/engine_evidence.py b/c/tools/engine_evidence.pyindex 9e37d02c..c0f4fa72 100644--- a/c/tools/engine_evidence.py+++ b/c/tools/engine_evidence.py@@ -108,26 +108,28 @@ def parse_engine_loaded(line):def parse_engine_preamble(line):"""Dispatch to the banner/loaded parser by prefix, or return None.- "Starts like one of them" is a literal, mechanical prefix test- (``line.startswith("== GLM C engine")`` / ``line.startswith("loaded- in")``), not a semantic resemblance check: any line -- owned by this- engine or not -- that happens to share that literal prefix is routed- to the matching parser and, if it does not go on to match that- parser's exact grammar, raises PreambleError rather than being- treated as an ordinary unowned log line. This is deliberately- fail-loud (an unexpected line reaching this position is itself- worth surfacing), but it means the dispatch is broader than the two- records it is named for: "loaded index ..." also starts with- "loaded in" purely because "index" itself starts with "in", and- would be refused here even though it has nothing to do with the- engine's load-timing record. No engine anywhere in this tree emits- such a line today (confirmed against every "loaded"-prefixed printf- in the C sources) -- this note exists so a future line that- genuinely collides with the prefix is a documented, expected- refusal rather than a surprise.+ Accepts only the two exact lines the engine actually prints at+ startup -- the "== GLM C engine ..." banner and the "loaded in ..."+ record that follows it -- each matched and range-checked field for+ field. Every other line is refused: an ordinary line that shares+ neither literal prefix returns None (see below); a line that DOES+ share one of the two prefixes but does not go on to match that+ parser's exact grammar raises PreambleError rather than being+ treated as unowned.- None means the line did not even share one of the two literal- prefixes above.+ The prefix test itself is mechanical, not semantic, which makes the+ dispatch slightly broader than the two records it is named for:+ "loaded index ..." also starts with "loaded in" purely because+ "index" itself starts with "in", and would be routed to+ parse_engine_loaded and refused there -- fail-loud, deliberately,+ the same as any other line sharing the prefix without matching the+ grammar. This is a documented characteristic, not a live concern:+ no engine anywhere in this tree emits "loaded index" or any other+ line that collides with either prefix today (confirmed against+ every "loaded"-prefixed printf in the C sources), so there is+ nothing to actually tolerate -- if a future engine change ever adds+ one, this note is why the refusal is expected rather than a+ surprise."""if not isinstance(line, str):raise PreambleError(f"engine preamble is not text: {line!r}")diff --git a/c/tools/eval_glm.py b/c/tools/eval_glm.pyindex cf02db1d..efc7a96e 100644--- a/c/tools/eval_glm.py+++ b/c/tools/eval_glm.py@@ -101,6 +101,22 @@ def parse_c17g(text):survive: neither spelling is finite-preserving for them) -- isrefused."""+ # fullmatch (not match/search) here is UNREACHABLE via the real+ # production path: this function's only caller, parse_score_result,+ # only ever passes the substring _SCORE_RE captured for this exact+ # sub-pattern (_SCORE_RE embeds _C17G_TEXT verbatim as its first+ # group), and a regex capture group's matched text always already+ # satisfies the sub-pattern it was captured with -- fullmatch,+ # match and search are identical for that input by construction,+ # not merely by absence of a counterexample. For a DIRECT caller+ # (this function is called directly elsewhere in this module's own+ # tests) fullmatch vs. match/search is still equivalent in+ # practice: RAN mutation testing (both variants, full suite) found+ # every constructible counterexample (trailing garbage, a bare+ # trailing ".", a single-digit exponent) independently rejected by+ # the round-trip format comparison a few lines below regardless,+ # since format(value, ...) can never reproduce a non-canonical+ # tail. See test_parse_c17g_rejects_* for the direct-caller pins.if not isinstance(text, str) or not re.fullmatch(_C17G_TEXT, text):raise EvidenceError(f"not a canonical %.6f/%.17g token: {text!r}")try:@@ -127,7 +143,25 @@ def is_score_preamble(line):def parse_score_result(line):- """Return (exact_text, value, contlen, greedy) for one complete SCORE line."""+ """Return (exact_text, value, contlen, greedy) for one complete SCORE line.++ fullmatch (not match/search) is UNREACHABLE-via-the-classifier for+ the one input shape that could distinguish them: a `$` anchor (built+ into _SCORE_RE's own pattern text) is zero-width and matches just+ before a trailing "\\n" as well as at true end-of-string, so+ match()/search() would accept a newline-terminated record that+ fullmatch correctly rejects (this is exactly the M11-class gap+ engine_evidence.py's own fullmatch calls had). classify_score_stdout+ and ScoreStdoutClassifier.classify -- the only production callers --+ both strip exactly one trailing newline before calling this function+ and both refuse any OTHER embedded "\\n" first (`raw_line.count("\\n")+ != 1`), so `line` here is guaranteed newline-free through that path:+ the exploit cannot be entered. For a caller reaching this function+ directly (as this module's own tests do), the newline-terminated+ input is still refused today -- test_direct_call_rejects_trailing_+ newline_record pins it so a future match()/search() weakening does+ not go unnoticed on the direct-call path either.+ """match = _SCORE_RE.fullmatch(line)if not match:raise EvidenceError(f"not an exact SCORE record: {line!r}")@@ -238,12 +272,32 @@ def completion_error(returncode, completed, expected, continuation_tokens,positive token count by construction.``stream_error`` is the one condition dev's own contract has no- analog for: a genuinely corrupted or self-inconsistent SCORE stream- (mixed identity-bound/legacy records, a replayed digest, an- out-of-vocabulary token, ...), which this module's evidence layer can- detect and dev's plain per-line filter cannot. That failure stays- fatal regardless of how many requests completed, because the parsed- numbers themselves are not trustworthy.+ analog for: a genuinely corrupted or self-inconsistent SCORE stream,+ which this module's evidence layer can detect and dev's plain+ per-line filter cannot. Concretely, as of this module's current+ stdout classifier: a foreign, malformed, or duplicated/out-of-order+ banner-or-load preamble line; a SCORE line whose numeric token is+ not an exact finite %.6f/%.17g spelling (a bare "nan"/"inf" included+ -- neither survives either spelling); a completed request's contlen+ not matching what that request actually asked for; more SCORE+ result lines than requests were sent; or the stream ending before+ both preamble records were ever seen. That failure stays fatal+ regardless of how many requests completed, because once any one+ line fails to parse as a complete, well-formed record, nothing+ guarantees the corruption did not already touch earlier-looking-fine+ rows too -- unlike the DATA/logprobs serving channel elsewhere in+ this project, where a non-finite value on a masked row is expected+ and reported, not fatal, this SCORE/benchmark channel has no such+ legitimate non-finite case: a nan/inf SCORE value cannot be compared+ against a benchmark's gold answer, and reporting an accuracy table+ built partly from corrupted numbers is a wrong PASS, which this+ module's whole design treats as worse than refusing to report at+ all. (This docstring previously cited identity-bound-evidence+ conditions -- mixed identity-bound/legacy records, a replayed+ digest, an out-of-vocabulary token -- that no longer exist: the+ identity-binding mode itself was removed as unsatisfiable by any+ current engine build. The reasoning above is unchanged; only the+ concrete list of what can still reach this path is corrected.)"""if stream_error:return str(stream_error)@@ -334,8 +388,16 @@ def score_snapshot_vocab(snap):_checked_engine_text_size(len(raw), "SCORE config.json")config = json.loads(raw.decode("utf-8"))vocab = config["vocab_size"]- except (OSError, UnicodeDecodeError, json.JSONDecodeError,+ except (OSError, UnicodeDecodeError, ValueError,KeyError, TypeError) as exc:+ # ValueError (not just its json.JSONDecodeError subclass): a+ # numeric literal in the JSON beyond Python's 4300-digit+ # int-string conversion limit makes json.loads itself raise a+ # bare ValueError, not JSONDecodeError -- same error-contract+ # class as F3's engine_evidence fix. main()'s only caller+ # catches EvidenceError to mark the run INCOMPLETE before ever+ # launching the engine; a bare ValueError escaping here instead+ # crashes main() outright with no INCOMPLETE marker written.raise EvidenceError(f"cannot derive SCORE vocabulary from {path}: {exc}") from excif type(vocab) is not int or not 1 <= vocab <= 1 << 24:raise EvidenceError(f"invalid SCORE vocabulary in {path}: {vocab!r}")