okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
24.1 KiB534 linesraw
1#!/usr/bin/env python3
2"""One command for the fast checks:  python tools/check   (Python 3.8+, standard library only)
3
4Runs, each in its own step with its own timeout, in a scratch folder (build trees, temp files, logs):
5
6  cmake-cpu       CMake preset `cpu-check` (CMakePresets.json): configure, build, CTest. No GPU, no model, no network.
7  py-tests        pytest tests/   (without tests/snapshot, which has its own step)
8  py-serve        pytest serve/
9  py-tools        pytest tools/test_*.py
10  py-optional     tools/dflash2, tools/trellis tests; need torch and are skipped without it
11  host-typecheck  apps/host: npm run typecheck
12  host-test       apps/host: npm test (a per-test timeout, so a hang fails one test instead of the run)
13  host-build      apps/host: npm run build
14  snapshot        pytest tests/snapshot (the config snapshot of the four entry points; needs Node 24)
15  docs            local links in the current pages (tools/check_links.py), the release manifest, the capability table and the bench results index (--check)
16
17Prints one table: passed / failed / skipped / not run, per step, with the reason for every skip and every "not run".
18A step that cannot run because a tool is missing (Node, cmake, a compiler, pytest, torch) is "not run" and says which tool;
19it is never reported as a pass.  The exit code is 1 when anything failed or timed out, and 0 otherwise; --strict makes a
20"not run" step exit 2 too.  Nothing here needs a GPU, a model or the real Strata install.
21
22    python tools/check                      everything above
23    python tools/check --only cmake-cpu,py-tools
24    python tools/check --skip host-build --json result.json
25    python tools/check --list
26Backend, model and browser tests are separate commands (see the CI workflows in .github/workflows); they are not part of this one.
27"""
28import argparse
29import glob
30import json
31import os
32import re
33import shutil
34import signal
35import subprocess
36import sys
37import tempfile
38import time
39import xml.etree.ElementTree as ET
40
41ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
42WIN = os.name == "nt"
43HOST = os.path.join(ROOT, "apps", "host")
44NODE_MIN = (24, 12)
45
46# step name -> default timeout in seconds (explicit, per step; --timeout-scale multiplies them)
47TIMEOUTS = {"cmake-cpu": 1800, "py-tests": 3600, "py-serve": 1800, "py-tools": 1200, "py-optional": 900,
48            "host-typecheck": 600, "host-test": 1800, "host-build": 600, "snapshot": 900, "docs": 300}
49STEPS = list(TIMEOUTS)
50
51
52class Result:
53    def __init__(self, name):
54        self.name, self.status, self.reason = name, "not run", ""
55        self.passed = self.failed = self.skipped = 0
56        self.seconds = 0.0
57        self.failures = []     # test ids or the failing command
58        self.skips = {}        # reason -> count
59        self.log = ""
60
61    def row(self):
62        return {"step": self.name, "status": self.status, "passed": self.passed, "failed": self.failed,
63                "skipped": self.skipped, "seconds": round(self.seconds, 1), "reason": self.reason,
64                "failures": self.failures[:200], "skips": self.skips, "log": self.log}
65
66
67class Scratch:
68    def __init__(self, base, keep):
69        self.keep = keep
70        self.created = base is None
71        self.dir = os.path.abspath(base) if base else tempfile.mkdtemp(prefix="strata-check-")
72        os.makedirs(os.path.join(self.dir, "tmp"), exist_ok=True)
73
74    def path(self, *p):
75        return os.path.join(self.dir, *p)
76
77    def env(self, extra=None):
78        env = dict(os.environ)
79        tmp = self.path("tmp")
80        env.update({"TMP": tmp, "TEMP": tmp, "TMPDIR": tmp, "PYTHONUTF8": "1", "PYTHONDONTWRITEBYTECODE": "1",
81                    "PYTHONUNBUFFERED": "1"})      # CI is left as the caller has it: some code asks whether a person can answer (strata_cli/launch/cmd.py)
82        env.update(extra or {})
83        return env
84
85    def cleanup(self):
86        # only a folder this run created is removed
87        if self.created and not self.keep:
88            shutil.rmtree(self.dir, ignore_errors=True)
89
90
91def run_cmd(cmd, cwd, env, timeout, logfile, shell=False):
92    """Run one command to a log file. Returns (exit code or None on timeout, seconds). On timeout the whole tree of
93    the child is killed (only this child's own tree)."""
94    t0 = time.time()
95    kw = {}
96    if WIN:
97        kw["creationflags"] = 0x00000200  # CREATE_NEW_PROCESS_GROUP
98    else:
99        kw["start_new_session"] = True
100    with open(logfile, "ab") as log:
101        log.write(("\n$ %s\n" % (cmd if isinstance(cmd, str) else " ".join(cmd))).encode())
102        log.flush()
103        try:
104            p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT, shell=shell, **kw)
105        except OSError as e:
106            log.write(("could not start: %s\n" % e).encode())
107            return -1, 0.0
108        try:
109            rc = p.wait(timeout=timeout)
110        except subprocess.TimeoutExpired:
111            if WIN:
112                subprocess.call(["taskkill", "/PID", str(p.pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
113            else:
114                try:
115                    os.killpg(p.pid, signal.SIGTERM)
116                    time.sleep(3)
117                    os.killpg(p.pid, signal.SIGKILL)
118                except (ProcessLookupError, PermissionError):
119                    pass
120            p.wait()
121            log.write(("\n[tools/check: timed out after %d s, killed]\n" % timeout).encode())
122            return None, time.time() - t0
123    return rc, time.time() - t0
124
125
126def tail(logfile, n=25):
127    try:
128        with open(logfile, "rb") as f:
129            return f.read().decode("utf-8", "replace").splitlines()[-n:]
130    except OSError:
131        return []
132
133
134# ---------------------------------------------------------------------------------------------------------- tools
135
136def node_version():
137    node = shutil.which("node")
138    if not node:
139        return None, "Node.js is not installed (needs >= %d.%d)" % NODE_MIN
140    try:
141        out = subprocess.run([node, "--version"], capture_output=True, text=True, timeout=30).stdout.strip()
142        v = tuple(int(x) for x in re.match(r"v(\d+)\.(\d+)", out).groups())
143    except Exception as e:  # noqa: BLE001
144        return None, "node --version failed (%s)" % e
145    if v < NODE_MIN:
146        return None, "Node.js %s is too old (needs >= %d.%d)" % (out, NODE_MIN[0], NODE_MIN[1])
147    return node, ""
148
149
150def have_module(name):
151    r = subprocess.run([sys.executable, "-c", "import importlib.util,sys;sys.exit(0 if importlib.util.find_spec(%r) else 1)" % name],
152                       capture_output=True)
153    return r.returncode == 0
154
155
156_vc_env = {}
157
158
159def msvc_env(base_env):
160    """On Windows the compiler is found through Visual Studio's vcvars64.bat when cl is not already on PATH."""
161    if shutil.which("cl", path=base_env.get("PATH")):
162        return base_env, ""
163    if "env" in _vc_env:
164        return _vc_env["env"], _vc_env["why"]
165    cands = []
166    pf = [os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), os.environ.get("ProgramFiles", r"C:\Program Files")]
167    vswhere = os.path.join(pf[0], "Microsoft Visual Studio", "Installer", "vswhere.exe")
168    if os.path.exists(vswhere):
169        out = subprocess.run([vswhere, "-latest", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
170                              "-property", "installationPath"], capture_output=True, text=True).stdout.strip()
171        if out:
172            cands.append(os.path.join(out.splitlines()[0], "VC", "Auxiliary", "Build", "vcvars64.bat"))
173    for root in pf:
174        for edition in ("BuildTools", "Community", "Professional", "Enterprise"):
175            cands.append(os.path.join(root, "Microsoft Visual Studio", "2022", edition, "VC", "Auxiliary", "Build", "vcvars64.bat"))
176    for bat in cands:
177        if os.path.exists(bat):
178            out = subprocess.run('cmd /c ""%s" >nul && set"' % bat, capture_output=True, text=True, shell=True).stdout
179            env = dict(base_env)
180            for line in out.splitlines():
181                if "=" in line and not line.startswith("="):
182                    k, v = line.split("=", 1)
183                    env[k] = v
184            _vc_env["env"], _vc_env["why"] = env, ""
185            return env, ""
186    _vc_env["env"], _vc_env["why"] = base_env, "no C++ compiler: cl is not on PATH and Visual Studio 2022's vcvars64.bat was not found"
187    return base_env, _vc_env["why"]
188
189
190# ---------------------------------------------------------------------------------------------------------- parsing
191
192def parse_junit(path, res, prefix=""):
193    try:
194        tree = ET.parse(path)
195    except (OSError, ET.ParseError):
196        return False
197    for case in tree.iter("testcase"):
198        name = (case.get("classname") or "") + "::" + (case.get("name") or "")
199        kids = {c.tag for c in case}
200        if "skipped" in kids:
201            sk = case.find("skipped")
202            msg = (sk.get("message") or "").strip()
203            if msg.lower().startswith("collection skipped") and (sk.text or "").strip():   # a module-level skip: the reason is in the text
204                msg = (sk.text or "").strip().splitlines()[-1].replace("Skipped: ", "").strip()
205            reason = (msg or (sk.text or "")).strip().splitlines()
206            reason = reason[0][:140] if reason else "no reason given"
207            if reason.lower() in ("true", "skipped", "skip"):
208                reason = "(skipped in the test file without a reason: " + (case.get("name") or "?")[:80] + ")"
209            res.skipped += 1
210            res.skips[reason] = res.skips.get(reason, 0) + 1
211        elif "failure" in kids or "error" in kids:
212            res.failed += 1
213            res.failures.append(prefix + name)
214        else:
215            res.passed += 1
216    return True
217
218
219def finish(res, rc, timed_out, log):
220    res.log = log
221    if timed_out:
222        res.status = "failed"
223        res.reason = "timed out after %d s" % round(res.seconds)
224        res.failures.append("timeout")
225    elif rc != 0 or res.failed:
226        res.status = "failed"
227        if not res.failures:
228            res.failures.append("exit code %s" % rc)
229            res.reason = " | ".join(l.strip() for l in tail(log, 4))[:300]
230    else:
231        res.status = "passed"
232    return res
233
234
235# ---------------------------------------------------------------------------------------------------------- steps
236
237def step_cmake(ctx):
238    r = Result("cmake-cpu")
239    cmake, ninja = shutil.which("cmake"), shutil.which("ninja")
240    if not cmake:
241        r.reason = "cmake is not installed"
242        return r
243    if not ninja:
244        r.reason = "ninja is not installed (the cpu-check preset uses the Ninja generator)"
245        return r
246    env = ctx.scratch.env()
247    if WIN:
248        env, why = msvc_env(env)
249        if why:
250            r.reason = why
251            return r
252    elif not any(shutil.which(c) for c in ("c++", "g++", "clang++")):
253        r.reason = "no C++ compiler (c++, g++ or clang++) on PATH"
254        return r
255    build = ctx.scratch.path("build-cpu-check")
256    log = ctx.scratch.path("cmake-cpu.log")
257    t = ctx.timeout("cmake-cpu")
258    t0 = time.time()
259    for label, cmd in (("configure", [cmake, "--preset", "cpu-check", "-B", build]),
260                       ("build", [cmake, "--build", build, "--parallel", str(ctx.jobs)])):
261        rc, _ = run_cmd(cmd, ROOT, env, max(30, t - (time.time() - t0)), log)
262        if rc is None or rc != 0:
263            r.seconds = time.time() - t0
264            r.failures.append("cmake " + label + (" (timed out)" if rc is None else ""))
265            r.reason = " | ".join(l.strip() for l in tail(log, 4))[:300]
266            return finish(r, rc if rc is not None else 1, rc is None, log)
267    junit = ctx.scratch.path("ctest.xml")
268    rc, _ = run_cmd([shutil.which("ctest"), "--test-dir", build, "--output-on-failure", "--parallel", str(min(ctx.jobs, 8)),
269                     "--timeout", "120", "--no-tests=error", "--output-junit", junit], ROOT, env, max(30, t - (time.time() - t0)), log)
270    r.seconds = time.time() - t0
271    if rc is None:
272        return finish(r, 1, True, log)
273    if not parse_junit(junit, r):
274        r.failures.append("ctest wrote no result file")
275        return finish(r, 1, False, log)
276    # the one-line summary the CMakeLists prints at configure time (which kinds of test were registered)
277    for line in open(log, "rb").read().decode("utf-8", "replace").splitlines():
278        if "strata tests:" in line:
279            r.reason = line.split("-- ", 1)[-1].strip()
280            break
281    return finish(r, rc, False, log)
282
283
284def step_pytest(name, targets, extra=(), need_node=False, cwd=None):
285    def run(ctx):
286        r = Result(name)
287        if not have_module("pytest"):
288            r.reason = "pytest is not installed for %s" % sys.executable
289            return r
290        if need_node:
291            node, why = node_version()
292            if not node:
293                r.reason = why
294                return r
295        paths = []
296        for t in targets:
297            hit = sorted(glob.glob(os.path.join(ROOT, t))) if any(c in t for c in "*?[") else ([os.path.join(ROOT, t)] if os.path.exists(os.path.join(ROOT, t)) else [])
298            paths.extend(hit)
299        if not paths:
300            r.reason = "no test files found for " + " ".join(targets)
301            return r
302        if ctx.shard:   # --shard I/N: every N-th test file (for a machine that allows only short jobs); the shards together are the whole step
303            i, n = ctx.shard
304            files = []
305            for pth in paths:
306                if os.path.isdir(pth):
307                    for pat in ("test_*.py", "*_test.py"):
308                        files += glob.glob(os.path.join(pth, "**", pat), recursive=True)
309                else:
310                    files.append(pth)
311            skip_dirs = [os.path.normpath(x[len("--ignore="):]) for x in extra if x.startswith("--ignore=")]
312            files = sorted({f for f in files if not any(os.path.normpath(f).startswith(d + os.sep) for d in skip_dirs)})
313            paths = files[i - 1::n]
314            r.reason = "shard %d/%d: %d of %d test files" % (i, n, len(paths), len(files))
315            if not paths:
316                return r
317        junit = ctx.scratch.path(name + ".xml")
318        log = ctx.scratch.path(name + ".log")
319        cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-o", "junit_family=xunit2",
320               "--junitxml=" + junit, "--maxfail=1000000", *extra, *paths]
321        rc, secs = run_cmd(cmd, cwd or ROOT, ctx.scratch.env(), ctx.timeout(name), log)
322        r.seconds = secs
323        ok = parse_junit(junit, r)
324        if rc is None and not ok:
325            return finish(r, 1, True, log)
326        if not ok and rc not in (0, 5):
327            r.failures.append("pytest wrote no result file (exit %s)" % rc)
328            r.reason = " | ".join(l.strip() for l in tail(log, 4))[:300]
329        if rc == 5:  # nothing collected
330            r.reason = "pytest collected no tests"
331            r.status = "not run"
332            return r
333        return finish(r, rc, rc is None, log)
334    return run
335
336
337def step_optional(ctx):
338    r = Result("py-optional")
339    for mod, what in (("torch", "torch"),):
340        if not have_module(mod):
341            r.reason = "%s is not installed for %s (tools/dflash2 tests need torch)" % (what, sys.executable)
342            return r
343    return step_pytest("py-optional", ["tools/dflash2", "tools/trellis"])(ctx)
344
345
346def npm_cmd():
347    return shutil.which("npm.cmd" if WIN else "npm") or shutil.which("npm")
348
349
350def host_ready(ctx, r):
351    """Node, npm and apps/host/node_modules. Installs the packages with `npm ci` when they are missing."""
352    node, why = node_version()
353    if not node:
354        r.reason = why
355        return False
356    if not npm_cmd():
357        r.reason = "npm is not installed"
358        return False
359    if os.path.isdir(os.path.join(HOST, "node_modules", ".bin")) or ctx.npm_ready:
360        return True
361    log = ctx.scratch.path("npm-ci.log")
362    rc, _ = run_cmd([npm_cmd(), "ci", "--no-audit", "--no-fund"], HOST, ctx.scratch.env(), 900, log)
363    if rc != 0:
364        r.reason = "npm ci could not install apps/host's packages (no network?); log " + log
365        return False
366    ctx.npm_ready = True
367    return True
368
369
370def step_npm(name, script, args=()):
371    def run(ctx):
372        r = Result(name)
373        if not host_ready(ctx, r):
374            return r
375        log = ctx.scratch.path(name + ".log")
376        junit = ctx.scratch.path(name + ".xml")
377        cmd = [npm_cmd(), "run", script]
378        if name == "host-test":
379            # the junit file gives the counts and the skip reasons; spec goes to the log
380            cmd += ["--", "--test-reporter=spec", "--test-reporter-destination=stdout", "--test-reporter=junit",
381                    "--test-reporter-destination=" + junit]
382        rc, secs = run_cmd(cmd, HOST, ctx.scratch.env({"STRATA_TEST_TIMEOUT_MS": "180000"}), ctx.timeout(name), log)
383        r.seconds = secs
384        if name == "host-test" and os.path.exists(junit):
385            parse_junit(junit, r)
386            # node writes suites and tests as testcases; a suite-level failure has no testcase of its own
387        elif name == "host-test":
388            summary = {m.group(1): int(m.group(2)) for m in re.finditer(r"^\W*(tests|pass|fail|cancelled|skipped)\s+(\d+)\s*$",
389                                                                       open(log, "rb").read().decode("utf-8", "replace"), re.M)}
390            r.passed, r.failed, r.skipped = summary.get("pass", 0), summary.get("fail", 0) + summary.get("cancelled", 0), summary.get("skipped", 0)
391            if r.skipped:
392                r.skips["(node:test gives no reason in this report)"] = r.skipped
393        return finish(r, rc, rc is None, log)
394    return run
395
396
397def step_docs(ctx):
398    """The documentation checks that need no tools but Python: links, release manifest, capability table, bench index, settings register, the vendored ggml manifest."""
399    r = Result("docs")
400    log = ctx.scratch.path("docs.log")
401    r.log = log
402    for label, script, args in (("links", "check_links.py", ()), ("release manifest", "release_manifest.py", ("--check",)),
403                                ("capability table", "capability_table.py", ("--check",)), ("bench results index", "bench_results_index.py", ("--check",)), ("settings register", "settings_register.py", ("--check",)),
404                                ("vendored ggml and gguf-py (third_party/strata-ggml, strata-gguf-py)", "check_vendored.py", ())):
405        path = os.path.join(ROOT, "tools", script)
406        if not os.path.exists(path):
407            r.skipped += 1
408            r.skips["%s: tools/%s is not in this checkout" % (label, script)] = 1
409            continue
410        rc, secs = run_cmd([sys.executable, path, *args], ROOT, ctx.scratch.env(), ctx.timeout("docs"), log)
411        r.seconds += secs
412        if rc == 0:
413            r.passed += 1
414        else:
415            r.failed += 1
416            r.failures.append("%s (exit %s)" % (label, rc))
417    if r.failed:
418        r.status = "failed"
419        r.reason = " | ".join(l.strip() for l in tail(log, 4))[:300]
420    else:
421        r.status = "passed"
422    return r
423
424
425STEP_FUNCS = {
426    "cmake-cpu": step_cmake,
427    "py-tests": step_pytest("py-tests", ["tests"], ["--ignore=" + os.path.join(ROOT, "tests", "snapshot")]),
428    "py-serve": step_pytest("py-serve", ["serve"]),
429    "py-tools": step_pytest("py-tools", ["tools/test_*.py"]),
430    "py-optional": step_optional,
431    "host-typecheck": step_npm("host-typecheck", "typecheck"),
432    "host-test": step_npm("host-test", "test"),
433    "host-build": step_npm("host-build", "build"),
434    "snapshot": step_pytest("snapshot", ["tests/snapshot"], need_node=True),
435    "docs": step_docs,
436}
437
438
439class Ctx:
440    def __init__(self, scratch, scale, jobs, shard=None):
441        self.scratch, self.scale, self.jobs, self.npm_ready, self.shard = scratch, scale, jobs, False, shard
442
443    def timeout(self, name):
444        return int(TIMEOUTS[name] * self.scale)
445
446
447def table(results):
448    head = ("step", "status", "passed", "failed", "skipped", "time", "")
449    rows = [head] + [(r.name, r.status.upper() if r.status != "passed" else "passed", str(r.passed), str(r.failed), str(r.skipped),
450                      "%dm%02ds" % divmod(int(r.seconds), 60), r.reason if r.status != "passed" else "") for r in results]
451    w = [max(len(row[i]) for row in rows) for i in range(6)]
452    out = []
453    for i, row in enumerate(rows):
454        out.append("  ".join(row[j].ljust(w[j]) if j in (0, 1) else row[j].rjust(w[j]) for j in range(6)) + ("  " + row[6] if row[6] else ""))
455        if i == 0:
456            out.append("  ".join("-" * x for x in w))
457    return "\n".join(out)
458
459
460def main(argv=None):
461    ap = argparse.ArgumentParser(description="Strata fast checks (see the top of this file)")
462    ap.add_argument("--only", help="comma list of steps")
463    ap.add_argument("--skip", help="comma list of steps to leave out")
464    ap.add_argument("--list", action="store_true", help="list the steps and their timeouts")
465    ap.add_argument("--scratch", help="scratch folder (default: a new one under the temp folder, removed at the end)")
466    ap.add_argument("--keep", action="store_true", help="keep the scratch folder (logs, build tree)")
467    ap.add_argument("--json", help="also write the result to this file")
468    ap.add_argument("--strict", action="store_true", help="exit 2 when a step could not run")
469    ap.add_argument("--timeout-scale", type=float, default=1.0, help="multiply every step's timeout")
470    ap.add_argument("--shard", help="I/N: run every N-th test file of the Python steps (e.g. 1/4), for a machine with short job limits")
471    ap.add_argument("--jobs", type=int, default=max(2, min(16, (os.cpu_count() or 4) // 2)), help="build/test parallelism")
472    a = ap.parse_args(argv)
473    if a.list:
474        for s in STEPS:
475            print("%-15s timeout %ds" % (s, TIMEOUTS[s]))
476        return 0
477    want = [s.strip() for s in a.only.split(",")] if a.only else list(STEPS)
478    for s in want + [x.strip() for x in (a.skip or "").split(",") if x.strip()]:
479        if s not in STEPS:
480            ap.error("unknown step %r (try --list)" % s)
481    want = [s for s in want if s not in [x.strip() for x in (a.skip or "").split(",")]]
482    scratch = Scratch(a.scratch, a.keep)
483    shard = None
484    if a.shard:
485        m = re.match(r"^(\d+)/(\d+)$", a.shard)
486        if not m or not 1 <= int(m.group(1)) <= int(m.group(2)):
487            ap.error("--shard wants I/N with 1 <= I <= N, for example 2/4")
488        shard = (int(m.group(1)), int(m.group(2)))
489    ctx = Ctx(scratch, a.timeout_scale, a.jobs, shard)
490    results = []
491    print("tools/check: %s, python %s, scratch %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), sys.version.split()[0], scratch.dir), flush=True)
492    try:
493        for s in want:
494            print("... %s" % s, flush=True)
495            try:
496                r = STEP_FUNCS[s](ctx)
497            except Exception as e:  # noqa: BLE001  a bug in this script is a failure, never a pass
498                r = Result(s)
499                r.status, r.reason = "failed", "tools/check itself failed: %r" % (e,)
500                r.failures.append(r.reason)
501            print("    %s %s" % (s, r.status), flush=True)
502            results.append(r)
503        print()
504        print(table(results))
505        for r in results:
506            if r.failures:
507                print("\nFAILED in %s (%d):" % (r.name, len(r.failures)))
508                for f in r.failures[:40]:
509                    print("  " + f)
510                if len(r.failures) > 40:
511                    print("  ... %d more (see %s)" % (len(r.failures) - 40, r.log))
512                if r.log:
513                    print("  log: " + r.log)
514        skips = [(r.name, k, v) for r in results for k, v in sorted(r.skips.items(), key=lambda kv: -kv[1])]
515        if skips:
516            print("\nSKIPPED, with the reason:")
517            for name, reason, n in skips:
518                print("  %-14s %5d  %s" % (name, n, reason))
519        nrun = [r for r in results if r.status == "not run"]
520        failed = [r for r in results if r.status == "failed"]
521        print("\ncheck: %d passed, %d failed, %d not run (of %d steps)" % (
522            len([r for r in results if r.status == "passed"]), len(failed), len(nrun), len(results)))
523        if a.json:
524            with open(a.json, "w", encoding="utf-8") as f:
525                json.dump([r.row() for r in results], f, indent=1)
526        if a.keep or a.scratch:
527            print("scratch kept: " + scratch.dir)
528        return 1 if failed else (2 if (a.strict and nrun) else 0)
529    finally:
530        scratch.cleanup()
531
532
533if __name__ == "__main__":
534    sys.exit(main())