graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(eval): tier 1 counts tests off the artifact, and the ratchet stops stalling (#439)
Rach Pradhan44f27a3a9827
diff --git a/AGENTS.md b/AGENTS.mdindex 859aa79c..6721c938 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -34,7 +34,7 @@ Failures name the invariant, say which regression it guards, and print the commaTwo rules the hook enforces that are easy to trip:-- **The suite count is a ratchet.** If it drops, either restore the tests or lower `test_count_baseline` in the manifest in the same commit, with a reason in the message.+- **The suite count is a ratchet.** If it drops, either restore the tests or lower `test_count_baseline` in the manifest in the same commit, with a reason in the message. Nothing raises it for you: bump it at each release cut, and tier 1 warns once the real suite has run more than `test_count_slack` (25) tests ahead of the floor, because a floor that far behind would not notice a whole module falling out of the test root.- **The SDKs are generated, not written.** Run `python3 sdk/generate.py --harness ./zig-out/bin/graff` after any change to the model catalog, tool schemas, or provider list, and commit the result.## Tier 2: model-backed behaviordiff --git a/README.md b/README.mdindex f972deaf..d102012c 100644--- a/README.md+++ b/README.md@@ -1416,6 +1416,14 @@ reports green. `invariants` goes further, rerunning the suite undersource and never run. Both are configured as data in`scripts/eval/tier1-manifest.json`.+Both read the count off the compiled test binary rather than off the build+summary, because a fully cached `zig build test` prints no `N/N tests passed`+line, and they pick that binary by the test names it carries rather than by+mtime, so a `-Dtest-filter` build left in `.zig-cache/o` is never mistaken for+the whole suite. `test_count_baseline` is a floor nothing raises on its own:+bump it at each release cut, and tier 1 warns once the suite runs more than+`test_count_slack` tests ahead of it.+---## Licensediff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 1aea759d..f894b1b2 100644--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -56,13 +56,23 @@ fiwanted() { [[ -z "$only" || "$only" == "$1" ]]; }failed=()+warned=()started=$SECONDS+# scripts/eval/tier1_invariants.py `count` exits with this when the suite has run+# far enough ahead of test_count_baseline that the floor guards nothing. Green,+# but say so out loud - that ratchet stalled 350 tests behind for months (#439).+RATCHET_STALLED=3+announce() { printf '\n\033[1m==> %s\033[0m %s\n' "$1" "$2"; }record_fail() {failed+=("$1")printf '\n \033[31mFAILED\033[0m %s\n rerun just this check: scripts/eval-tier1.sh --only %s\n' "$1" "$1"}+record_warn() {+ warned+=("$1")+ printf ' \033[33mWARN\033[0m %s: %s\n' "$1" "$2"+}# --- fmt ---------------------------------------------------------------if wanted fmt; then@@ -117,10 +127,22 @@ skip_dependent() {# --- tests -------------------------------------------------------------suite_count() {- # `--summary all` prints "N/N tests passed" even on a fully cached run.+ # `--summary all` prints "N/N tests passed" only when the run step actually+ # ran. A fully cached `zig build test` on zig 0.17 prints "Build Summary: 4/4+ # steps succeeded" and nothing else, so this comes back empty and the caller+ # falls back to artifact_count - it does NOT mean the build is red (#439).sed -n 's/.*Build Summary:.*; \([0-9][0-9]*\)\/[0-9][0-9]* tests passed.*/\1/p' <<<"$1" | tail -1}+# The count off the compiled artifact instead of off the build summary: a test+# binary run with no arguments prints "All N tests passed." every time, cached+# build or not, and running it re-proves the suite besides. Pass the same+# -Dtest-filter values the build used so the right artifact is picked out of+# .zig-cache/o (see scripts/eval/tier1_test_binary.py).+artifact_count() {+ python3 scripts/eval/tier1_test_binary.py count "$@"+}+if wanted tests; thenif ((!build_ok)); thenskip_dependent tests@@ -136,10 +158,19 @@ if wanted tests; thenelsecount=$(suite_count "$out")if [[ -z "$count" ]]; then- printf ' FAIL could not read the test count out of the build summary\n'- record_fail tests- elif python3 scripts/eval/tier1_invariants.py count --observed "$count"; then :; else+ printf ' the cached build printed no test summary; counting from the compiled artifact\n'+ count=$(artifact_count)+ fi+ if [[ -z "$count" ]]; then+ printf ' FAIL could not read the test count from the build summary or the test artifact\n'record_fail tests+ else+ python3 scripts/eval/tier1_invariants.py count --observed "$count"+ case $? in+ 0) : ;;+ "$RATCHET_STALLED") record_warn tests "test_count_baseline is stale (see above)" ;;+ *) record_fail tests ;;+ esacfififi@@ -152,15 +183,27 @@ if wanted invariants; thenelseannounce invariants "the named goal/loop/todo tests actually ran"filters=()- while IFS= read -r line; do [[ -n "$line" ]] && filters+=(-Dtest-filter="$line"); done \- < <(python3 scripts/eval/tier1_invariants.py filters)+ counters=()+ while IFS= read -r line; do+ [[ -n "$line" ]] || continue+ filters+=(-Dtest-filter="$line")+ counters+=(--filter "$line")+ done < <(python3 scripts/eval/tier1_invariants.py filters)# Anonymous `test {}` blocks ignore -Dtest-filter and always run, so measure# that floor with a filter that matches nothing and subtract it.- floor_out=$(zig build test --summary all -Dtest-filter="__tier1_matches_nothing__" 2>&1)+ nothing="__tier1_matches_nothing__"+ floor_out=$(zig build test --summary all -Dtest-filter="$nothing" 2>&1)floor=$(suite_count "$floor_out")+ # These two builds cache like any other, and a cached run prints no test+ # summary (#439). Ask the artifacts instead - both are small and finish in+ # under a second.+ [[ -n "$floor" ]] || floor=$(artifact_count --filter "$nothing")named_out=$(zig build test --summary all "${filters[@]}" 2>&1)status=$?named=$(suite_count "$named_out")+ if ((status == 0)) && [[ -z "$named" ]]; then+ named=$(artifact_count "${counters[@]}")+ fiif ((status != 0)); thenprintf '%s\n' "$named_out" | tail -6printf ' one of the named invariants is failing.\n'@@ -217,6 +260,9 @@ fi# --- verdict -----------------------------------------------------------elapsed=$((SECONDS - started))+if ((${#warned[@]} > 0)); then+ printf '\n\033[33m%d warning(s)\033[0m: %s\n' "${#warned[@]}" "${warned[*]}"+fiif ((${#failed[@]} == 0)); thenprintf '\n\033[32mtier 1 green\033[0m in %ss\n' "$elapsed"exit 0diff --git a/scripts/eval/test_reachability.py b/scripts/eval/test_reachability.pyindex 036a7d0b..58eddf03 100644--- a/scripts/eval/test_reachability.py+++ b/scripts/eval/test_reachability.py@@ -15,6 +15,14 @@ test root" and exited 0 while 37 tests were dead. This compares two groundtruths instead - the names declared in src/*.zig, and the names present in thecompiled binary - so it cannot be fooled by an import Zig never follows.+Which binary matters as much as which names. This used to read the NEWEST+artifact under .zig-cache/o, and a `-Dtest-filter` build lands there too: after+one - `zig build test -Dtest-filter=foo` by hand, or the `invariants` check+right before this one in a hook that reordered - the newest artifact holds only+the tests that filter matched, and every other declared test read as "not+compiled in" (#439). tier1_test_binary.select() picks the artifact by the names+it carries instead, so the full build wins even when a filtered one is newer.+Usage: python3 scripts/eval/test_reachability.py [--verbose]Exit 0 when every declared test is compiled in; 1 otherwise."""@@ -22,39 +30,22 @@ Exit 0 when every declared test is compiled in; 1 otherwise.from __future__ import annotationsimport pathlib-import reimport subprocessimport sys-ROOT = pathlib.Path(__file__).resolve().parents[2]-SRC = ROOT / "src"-CACHE = ROOT / ".zig-cache" / "o"--TEST_NAME = re.compile(r'^test "((?:[^"\\]|\\.)*)"', re.M)---def declared_tests() -> dict[str, str]:- """Every `test "name"` in src/*.zig, mapped to its file."""- out: dict[str, str] = {}- for path in sorted(SRC.glob("*.zig")):- for match in TEST_NAME.finditer(path.read_text(encoding="utf-8")):- # The source carries Zig escapes; the binary carries the resolved- # bytes. Unescape so a name containing a quote still matches.- name = match.group(1).replace('\\"', '"').replace("\\\\", "\\")- out[name] = path.name- return out-+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))+import tier1_test_binary # noqa: E402 (sibling module, not an installed package)+from tier1_test_binary import ArtifactError, declared_tests, select # noqa: E402-def newest_test_binary() -> pathlib.Path | None:- candidates = [p for p in CACHE.glob("*/test") if p.is_file()]- return max(candidates, key=lambda p: p.stat().st_mtime) if candidates else None+ROOT = pathlib.Path(__file__).resolve().parents[2]def main() -> int:verbose = "--verbose" in sys.argv# A stale binary would give a false verdict in either direction, so build- # first and let a compile failure surface as a compile failure.+ # first - unfiltered, which is also what makes the artifact we want exist -+ # and let a compile failure surface as a compile failure.build = subprocess.run(["zig", "build", "test"], cwd=ROOT, capture_output=True, text=True)@@ -63,23 +54,27 @@ def main() -> int:sys.stderr.write(build.stderr[-2000:])return 1- binary = newest_test_binary()- if binary is None:- sys.stderr.write("no compiled test binary found under .zig-cache/o\n")+ declared = declared_tests()+ try:+ # No filters: the full build, i.e. the artifact carrying the most+ # declared names. Raw bytes, NOT `strings` - that tool only extracts+ # ASCII runs, so every test name containing an em dash, an arrow or a+ # quote read as missing and the guard cried wolf on six live tests.+ chosen = select([], declared)+ except ArtifactError as exc:+ sys.stderr.write(f"{exc}\n")return 1+ binary = chosen.path- # Raw bytes, NOT `strings`: that tool only extracts ASCII runs, so every- # test name containing an em dash, an arrow or a quote read as missing and- # the guard cried wolf on six perfectly live tests. Searching the bytes for- # the UTF-8 encoding of each name has no such blind spot.- blob = binary.read_bytes()-- declared = declared_tests()missing: dict[str, list[str]] = {}- for name, file in declared.items():- if name.encode("utf-8") not in blob:- missing.setdefault(file, []).append(name)-+ for name in chosen.missing:+ missing.setdefault(declared[name], []).append(name)++ if not chosen.was_newest:+ print(+ " ignored a newer but filtered artifact in .zig-cache/o"+ f" ({tier1_test_binary.candidates()[0].parent.name})"+ )if not missing:print(f" all {len(declared)} declared tests are compiled in ({binary.parent.name})")return 0diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 1fc1a0e1..5bcfabd9 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -4,13 +4,18 @@"Tier 1 of the internal eval set: the deterministic invariants the pre-push hook enforces.","No network, no model calls. Tier 2 (model-backed behavior) lives in evals/ and is opt-in.","test_count_baseline is a ratchet: the suite may grow, it may never shrink. A drop means a",- "module stopped being referenced from the test root and its tests silently vanished."+ "module stopped being referenced from the test root and its tests silently vanished.",+ "It is a FLOOR and nothing raises it automatically - bump it by hand at each release cut.",+ "test_count_slack is how far the real suite may run ahead of that floor before the tests",+ "check starts WARNING that the ratchet has stalled: it sat 350 behind for months (#439),",+ "which is a floor low enough to catch nothing."],"test_roots": ["src/main.zig","src/repl.zig"],- "test_count_baseline": 656,+ "test_count_baseline": 994,+ "test_count_slack": 25,"required_invariants": [{"id": "goal-epochs",diff --git a/scripts/eval/tier1_invariants.py b/scripts/eval/tier1_invariants.pyindex dbd3174f..99b0ac66 100644--- a/scripts/eval/tier1_invariants.py+++ b/scripts/eval/tier1_invariants.py@@ -17,6 +17,11 @@ Subcommands (all offline, all under a second):filters print one -Dtest-filter value per line, for the shellcount --observed N the total suite count may grow, never shrinkinvariants --observed N the filtered run must have run exactly the required set++`count` exits 3, not 1, when the suite has run far enough ahead of the baseline+that the floor no longer guards anything (#439: it sat 350 behind). That is a+warning the caller surfaces, never a failure - the baseline is a floor, and only+a human bumps it, in the commit that earned the tests."""from __future__ import annotations@@ -34,6 +39,12 @@ IMPORT = re.compile(r'@import\("([^"]+\.zig)"\)')TEST_DECL = re.compile(r'(?m)^test[ {]')TEST_NAME = re.compile(r'(?m)^test "((?:[^"\\]|\\.)*)"')+# `count` exit code for "green, but the baseline is far enough behind the real+# suite that it guards nothing". Kept out of 0/1 so the shell can tell a warning+# from a pass and from a failure. scripts/eval-tier1.sh reads it.+RATCHET_STALLED = 3+DEFAULT_SLACK = 25+def load_manifest() -> dict:try:@@ -171,6 +182,7 @@ def main() -> None:if args.cmd == "count":baseline = int(manifest["test_count_baseline"])+ slack = int(manifest.get("test_count_slack", DEFAULT_SLACK))if args.observed < baseline:print(f" FAIL test count dropped: {args.observed} ran, baseline is {baseline}.\n"@@ -182,7 +194,23 @@ def main() -> None:file=sys.stderr,)sys.exit(1)- if args.observed > baseline:+ drift = args.observed - baseline+ if drift > slack:+ # Never raise it here: a floor that moves on its own is not a floor,+ # and the number belongs in the same commit as the tests that earned+ # it. But say it loudly, because the alternative is what #439 found -+ # a baseline 350 behind, guarding nothing, for months.+ print(+ f" WARN the ratchet has stalled: {args.observed} tests ran but"+ f" test_count_baseline is {baseline}, {drift} behind (slack {slack}).\n"+ " A floor that far below the suite would not notice a whole module\n"+ " falling out of the test root.\n"+ f" fix: set test_count_baseline to {args.observed} in\n"+ " scripts/eval/tier1-manifest.json and commit it.",+ file=sys.stderr,+ )+ sys.exit(RATCHET_STALLED)+ if drift:print(f" {args.observed} tests ran (baseline {baseline}) - ""bump test_count_baseline in scripts/eval/tier1-manifest.json to ratchet it up"diff --git a/scripts/eval/tier1_test_binary.py b/scripts/eval/tier1_test_binary.pynew file mode 100644index 00000000..ad8d7a50--- /dev/null+++ b/scripts/eval/tier1_test_binary.py@@ -0,0 +1,204 @@+#!/usr/bin/env python3+"""Resolve the compiled Zig test artifact, and read the suite count off it.++`zig build test` is not a reliable narrator for either question tier 1 asks it+(#439):++ * The count. On zig 0.17 a fully cached run prints "Build Summary: 4/4 steps+ succeeded" and stops - there is no "N/N tests passed" line, because the run+ step never re-ran. The shell's sed came back empty and the tests check+ FAILED a suite that was green. The artifact still knows: a test binary+ invoked with no arguments prints "All N tests passed." as its last line,+ cached build or not, and running it re-proves the suite besides.+ * Which binary. .zig-cache/o/*/test accumulates one artifact per distinct+ build, and every -Dtest-filter build lands there too. Taking the newest, as+ the reachability check used to, reads a FILTERED binary whenever the last+ build was filtered - and then reports the ~950 tests it legitimately does+ not contain as "not compiled in".++So selection is by content, never by mtime. Every `test "name"` in src/*.zig is+a byte string inside the binary that compiled it, and -Dtest-filter drops the+tests it does not match at COMPILE time, names and all. The build we want is the+one whose declared-name set matches what its filters select: no filters means+every declared name, and the tier-1 floor build (a filter matching nothing)+means none of them. mtime only breaks ties.++ resolve [--filter TEXT]... print the artifact path for that build+ count [--filter TEXT]... run that artifact and print how many tests it holds++Both exit non-zero with a reason on stderr rather than guess. Neither builds:+the caller runs `zig build test` (with the same filters) first, so a compile+error surfaces as a compile error.+"""++from __future__ import annotations++import argparse+import pathlib+import re+import subprocess+import sys++ROOT = pathlib.Path(__file__).resolve().parents[2]+SRC = ROOT / "src"+CACHE = ROOT / ".zig-cache" / "o"++TEST_NAME = re.compile(r'^test "((?:[^"\\]|\\.)*)"', re.M)+ALL_PASSED = re.compile(r"^All (\d+) tests passed\.$", re.M)+MIXED = re.compile(r"^(\d+) passed; (\d+) skipped; (\d+) failed\.$", re.M)+++class ArtifactError(Exception):+ """No usable test artifact, or one that would not say how many tests it holds."""+++def declared_tests() -> dict[str, str]:+ """Every `test "name"` in src/*.zig, mapped to the file that declares it."""+ out: dict[str, str] = {}+ for path in sorted(SRC.glob("*.zig")):+ for match in TEST_NAME.finditer(path.read_text(encoding="utf-8")):+ # The source carries Zig escapes; the binary carries the resolved+ # bytes. Unescape so a name containing a quote still matches.+ name = match.group(1).replace('\\"', '"').replace("\\\\", "\\")+ out[name] = path.name+ return out+++class Selection:+ """One candidate artifact, scored against the build we asked for."""++ def __init__(self, path: pathlib.Path, present: set[str], expected: set[str]):+ self.path = path+ self.present = present+ self.expected = expected+ self.considered = 1+ self.was_newest = True++ @property+ def missing(self) -> set[str]:+ """Names this build should carry and does not."""+ return self.expected - self.present++ @property+ def extra(self) -> set[str]:+ """Names it carries that the filters did not ask for."""+ return self.present - self.expected++ def describe(self) -> str:+ return (+ f"{self.path.parent.name} ({len(self.present)} of {len(self.expected)}"+ f" expected test names; {self.considered} artifact(s) in .zig-cache/o)"+ )+++def candidates() -> list[pathlib.Path]:+ """Every compiled test artifact, newest first."""+ found = [p for p in CACHE.glob("*/test") if p.is_file()]+ return sorted(found, key=lambda p: p.stat().st_mtime, reverse=True)+++def select(filters: list[str], declared: dict[str, str] | None = None) -> Selection:+ """The artifact built with exactly these -Dtest-filter values (none = full).++ Zig's filters are substring matches on the test name, so the set of declared+ names a filtered build keeps is computable from the source alone. Rank every+ candidate by how far it is from that set - missing names first, then names it+ should not have - and the full build wins the unfiltered question even when a+ filtered build is newer.+ """+ if declared is None:+ declared = declared_tests()+ expected = {n for n in declared if not filters or any(f in n for f in filters)}++ ranked: list[Selection] = []+ # candidates() is newest first and sort() below is stable, so ties stay in+ # that order and the newest equally-good artifact wins.+ for path in candidates():+ blob = path.read_bytes()+ present = {n for n in declared if n.encode("utf-8") in blob}+ ranked.append(Selection(path, present, expected))+ if not ranked:+ raise ArtifactError(+ "no compiled test binary under .zig-cache/o - run `zig build test` first"+ )++ newest = ranked[0].path+ ranked.sort(key=lambda s: (len(s.missing), len(s.extra)))+ best = ranked[0]+ best.considered = len(ranked)+ best.was_newest = best.path == newest+ return best+++def artifact_count(path: pathlib.Path) -> tuple[int, str]:+ """Run the artifact and read its own tally. Raises if it does not pass."""+ proc = subprocess.run(+ [str(path)], cwd=ROOT, capture_output=True, text=True, errors="replace"+ )+ blob = proc.stdout + proc.stderr+ passed = ALL_PASSED.search(blob)+ if passed and proc.returncode == 0:+ return int(passed.group(1)), blob+ mixed = MIXED.search(blob)+ if mixed:+ ok, skipped, failed = (int(g) for g in mixed.groups())+ if failed == 0 and proc.returncode == 0:+ return ok + skipped, blob+ raise ArtifactError(+ f"{path} reported {failed} failing test(s):\n" + "\n".join(blob.splitlines()[-12:])+ )+ raise ArtifactError(+ f"{path} exited {proc.returncode} without a test tally:\n"+ + "\n".join(blob.splitlines()[-12:])+ )+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest="cmd", required=True)+ for name in ("resolve", "count"):+ cmd = sub.add_parser(name)+ cmd.add_argument(+ "--filter",+ action="append",+ default=[],+ help="a -Dtest-filter value the build used (repeatable; none = the full build)",+ )+ args = parser.parse_args()++ try:+ chosen = select(args.filter)+ except ArtifactError as exc:+ print(f" {exc}", file=sys.stderr)+ return 1++ if chosen.missing and not args.filter:+ # Not fatal here: `reach` is the check that judges missing names. Say it+ # out loud so a thin artifact never passes for the full one in silence.+ print(+ f" note: {chosen.describe()} is missing {len(chosen.missing)} declared"+ " test name(s) - it is still the fullest artifact available",+ file=sys.stderr,+ )+ if not chosen.was_newest:+ print(+ " note: the newest artifact in .zig-cache/o is a different build"+ f" (its -Dtest-filter set differs); using {chosen.path.parent.name}",+ file=sys.stderr,+ )++ if args.cmd == "resolve":+ print(chosen.path)+ return 0++ try:+ count, _ = artifact_count(chosen.path)+ except ArtifactError as exc:+ print(f" {exc}", file=sys.stderr)+ return 1+ print(count)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())