okami.mom/strata

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

Niko1221Merge f-ci-green-0215: the four red GitHub checks (cmake-cpu on MSVC, py-tools on a CRLF checkout and on macOS, the Windows snapshot time)b749503db

main
24.4 KiB479 linesraw
1#!/usr/bin/env python3
2"""Release gate: install a model of the signed feed from REAL FILES, through setup.py, the way a person's Terminal or the app does.
3
4Why: the feed-model install path had only mock tests until the Qwen4 release-day rehearsal (RESULTS-Q4-P8.md, 2026-11-08), which then found three bugs
5(F2 `KeyError: 'mmproj'` for a model with no picture reader, F3 the Flash-Next draft layer fetched for a model whose entry says `drafter: none`, F5 no RAM
6budget so a 64 GB PC began writing a second 77 GB copy of the experts) and a fourth one for a model of another shape (F4, the shipped expert profile).
7Each of them only shows with a real file of the model's kind, not with the few bytes of the mock tests.
8
9What it does, in a scratch folder (nothing of the real install, %APPDATA% or the data folder is touched, no network beyond 127.0.0.1):
10  1. writes a small synthetic qwen4exp GGUF with tools/q4geo_synth.py (random weights; `--tokenizer-from` gives it a real tokenizer);
11  2. builds a models-only feed signed with a THROW-AWAY key (packaging/feed_tool.py's own build_feed) whose entry says `drafter: none`, has no picture reader
12     and a shape that is not the shipped Flash-Next one;
13  3. serves the file from a tiny Hugging Face stand-in on 127.0.0.1 and runs `setup.py` in the app's mode (STRATA_CONTROL_INSTALL=1: no engine, no pip, no build)
14     with the feed as the model list: download, SHA-256 check, preparation (the pack), run config;
15  4. checks: setup exits 0 and prints neither a Traceback nor `KeyError`; the Flash-Next draft layer was not asked for (the stand-in saw only the model file);
16     the owner's two lines are there; the run config reads the file in place with a RAM budget and no second copy of the experts was written; a neutral expert
17     profile for the file's own layers x experts is in the pack folder and the config names it; a second run changes nothing and downloads nothing.
18  5. with --engine <folder of an engine built for the file's shape>: starts that engine from the run config, sends ONE chat request and checks the answer
19     is finite (the file has random weights: the text is empty or noise, the usage numbers and `finish_reason` are what counts).
20
21    python tools/feed_model_install_gate.py
22    python tools/feed_model_install_gate.py --tokenizer-from <a real Flash-Next shard 1> --engine <engine folder> --full
23
24`tools/test_feed_model_install_realfile.py` runs step 1 to 4 as a test in `python tools/check` (py-tools). The preparation tools read GGUF files with the vendored
25their own GGUF code (tools/strata_gguf.py), so no gguf-py, no llama.cpp checkout, no STRATA_TEST_LLAMA_CPP and no network are needed; the check also fails if setup says it
26fetched llama.cpp. Without numpy it is SKIPPED with that reason (never a pass).
27Exit codes: 0 pass, 1 a check failed, 2 not run (no numpy, no NVIDIA card on a Windows box), 3 the engine phase failed.
28"""
29from __future__ import annotations
30
31import argparse
32import hashlib
33import http.server
34import json
35import os
36import re
37import shutil
38import signal
39import socket
40import subprocess
41import sys
42import tempfile
43import threading
44import time
45import urllib.request
46from pathlib import Path
47
48ROOT = Path(__file__).resolve().parents[1]
49sys.path.insert(0, str(ROOT))
50sys.path.insert(0, str(ROOT / "packaging"))
51
52REV = "0123456789abcdef0123456789abcdef01234567"
53REPO = "gate-test/Qwen4-Gate-GGUF"
54MODEL_ID = "qwen4-gate"
55QUANT = "GATE-Q4"
56FILE_NAME = "Qwen4-Gate-GATE-Q4.gguf"
57SETUP_TIMEOUT = int(os.environ.get("STRATA_GATE_SETUP_TIMEOUT", "300"))   # seconds for one setup run (the 0.2 GB file takes about 6)
58NEUTRAL_LINE = "This model's shape differs from Flash-Next, so a neutral expert profile is used."
59NO_DRAFT_LINE = "The model list says this model has no draft layer (MTP), so none is fetched or used."
60
61# the shape of the small file: a q4_lite model cut down to 1 layer of 8 experts, so a run takes seconds and the file is 0.2 GB. --full: the case-B stand-in of the rehearsal
62# (4 layers of q4_lite, the shape a `-DSTRATA_GEOMETRY_FILE` engine of that rehearsal was built for)
63TINY = dict(layers=1, vocab=2048, set="n_expert=8,n_expert_used=2,n_ff=64")
64FULL = dict(layers=4, vocab=None, set="")
65
66
67class NotRun(Exception):
68    pass
69
70
71def check_gguf_tools() -> None:
72    """The preparation tools read and write GGUF files with their own code (tools/strata_gguf.py, tools/strata_quants.py): nothing to find, nothing to
73    fetch, and no gguf-py needed (this gate also runs on a copy of the tree without third_party/strata-gguf-py)."""
74    for f in ("strata_gguf.py", "strata_quants.py", "strata_quant_tables.py"):
75        if not (ROOT / "tools" / f).is_file():
76            raise NotRun("tools/%s is missing from this checkout" % f)
77
78
79def free_port() -> int:
80    with socket.socket() as s:
81        s.bind(("127.0.0.1", 0))
82        return s.getsockname()[1]
83
84
85class Mirror:
86    """GET/HEAD/Range for /<repo>/resolve/<rev>/<path> out of one folder, on 127.0.0.1; keeps the list of what was asked for."""
87
88    def __init__(self, root: Path):
89        self.root, self.seen = Path(root).resolve(), []
90        outer = self
91
92        class H(http.server.BaseHTTPRequestHandler):
93            protocol_version = "HTTP/1.1"
94
95            def log_message(self, *a):
96                pass
97
98            def _serve(self, head):
99                outer.seen.append(self.path)
100                m = re.match(r"^/([^/]+/[^/]+)/resolve/[^/]+/(.+?)(\?.*)?$", self.path)
101                p = (outer.root / m.group(1) / m.group(2)).resolve() if m else None
102                if p is None or outer.root not in p.parents or not p.is_file():
103                    self.send_response(404)
104                    self.send_header("Content-Length", "0")
105                    self.end_headers()
106                    return
107                size = p.stat().st_size
108                start, end, code = 0, size - 1, 200
109                rng = re.match(r"bytes=(\d*)-(\d*)", self.headers.get("Range") or "")
110                if rng:
111                    a, b = rng.groups()
112                    start = max(0, size - int(b)) if (a == "" and b != "") else int(a or 0)
113                    end = min(int(b), size - 1) if (b and a != "") else size - 1
114                    code = 206
115                n = end - start + 1
116                self.send_response(code)
117                self.send_header("Content-Type", "application/octet-stream")
118                self.send_header("Accept-Ranges", "bytes")
119                self.send_header("Content-Length", str(n))
120                self.send_header("X-Linked-Size", str(size))
121                if code == 206:
122                    self.send_header("Content-Range", "bytes %d-%d/%d" % (start, end, size))
123                self.end_headers()
124                if head:
125                    return
126                with p.open("rb") as f:
127                    f.seek(start)
128                    left = n
129                    while left > 0:
130                        chunk = f.read(min(1 << 20, left))
131                        if not chunk:
132                            break
133                        try:
134                            self.wfile.write(chunk)
135                        except OSError:
136                            return
137                        left -= len(chunk)
138
139            def do_GET(self):
140                self._serve(False)
141
142            def do_HEAD(self):
143                self._serve(True)
144
145        self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
146        self.port = self.server.server_address[1]
147        self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
148
149    def __enter__(self):
150        self.thread.start()
151        return self
152
153    def __exit__(self, *exc):
154        self.server.shutdown()
155        self.server.server_close()
156
157
158def sha256_of(path: Path) -> str:
159    h = hashlib.sha256()
160    with path.open("rb") as f:
161        for chunk in iter(lambda: f.read(1 << 20), b""):
162            h.update(chunk)
163    return h.hexdigest()
164
165
166def make_synthetic(out: Path, shape: dict, tokenizer_from: str | None) -> None:
167    cmd = [sys.executable, "-I", str(ROOT / "tools" / "q4geo_synth.py"), "--shape", "q4_lite", "--layers", str(shape["layers"]), "--recipe", "ud-q4k",
168           "--exact-bf16", "--small-ple", "--out", str(out)]
169    if shape["vocab"] and not tokenizer_from:
170        cmd += ["--vocab", str(shape["vocab"])]
171    if shape["set"]:
172        cmd += ["--set", shape["set"]]
173    if tokenizer_from:
174        cmd += ["--tokenizer-from", tokenizer_from]
175    r = subprocess.run(cmd, capture_output=True, text=True)
176    if r.returncode != 0:
177        if "numpy" in (r.stderr or ""):
178            raise NotRun("tools/q4geo_synth.py needs numpy")
179        raise RuntimeError("q4geo_synth failed: " + (r.stderr or r.stdout)[-600:])
180
181
182def build_feed(feed: Path, entry: dict, work: Path) -> Path:
183    """A models-only feed signed with a throw-away key; returns the file of trusted keys for STRATA_UPDATE_TRUSTED_KEYS."""
184    import feed_tool
185    from strata_control import signing
186    key = signing.generate_key()
187    models = work / "models"
188    models.mkdir()
189    (models / (MODEL_ID + ".entry.json")).write_text(json.dumps(entry, indent=1), encoding="utf-8")
190    feed_tool.build_feed(feed, key=key, sequence=1, models_dir=models)
191    trust = work / "trust.json"
192    trust.write_text(json.dumps({"keys": [signing.public_part(key)]}), encoding="utf-8")
193    return trust
194
195
196def make_entry(model: Path) -> dict:
197    return {"id": MODEL_ID, "title": "Qwen4 Gate", "by": "the release gate", "about": "a synthetic model with random weights, for the install gate",
198            "licence": "Apache 2.0", "licence_url": "https://example.org/licence", "family": "qwen4exp", "repo": REPO, "revision": REV,
199            "pictures": False, "drafter": "none", "context": 32768, "min_engine": "0.1.46",
200            # ram_gb and arena_gb are far above any test machine's RAM on purpose: setup must pick the RAM-budget mode (the GGUF read in place) and not the low-RAM mode that
201            # writes a second copy of the experts (F5); the 0.2 GB file is all there is to read
202            "quants": [{"name": QUANT, "about": "random weights", "ram_gb": 2048, "arena_gb": 2000,
203                        "files": [{"name": FILE_NAME, "size": model.stat().st_size, "sha256": sha256_of(model)}]}]}
204
205
206STUB_SMI = """#!/bin/sh
207# the gate's stand-in for nvidia-smi on a box with no NVIDIA card (setup stops at step 1 without one): one 24 GB Ada card, every other question unanswered
208case "$*" in
209  *memory.total*) echo "0, NVIDIA GeForce RTX 4090, 24564, 8.9, 570.86.16" ;;
210esac
211exit 0
212"""
213
214
215def nvidia_stub_if_needed(env: dict, work: Path, log) -> None:
216    """Setup's step 1 needs an NVIDIA card: nvidia-smi answers on the real boxes (used as it is); on a box without one a POSIX stand-in is put first on PATH."""
217    try:
218        ok = subprocess.run(["nvidia-smi", "-L"], env=env, capture_output=True, timeout=30).returncode == 0
219    except (OSError, subprocess.TimeoutExpired):
220        ok = False
221    if ok:
222        return
223    if os.name == "nt":
224        raise NotRun("no NVIDIA card (nvidia-smi does not answer) and the stand-in is POSIX only: setup stops at its step 1")
225    d = work / "bin"
226    d.mkdir(exist_ok=True)
227    f = d / "nvidia-smi"
228    f.write_bytes(STUB_SMI.encode("utf-8"))
229    f.chmod(0o755)
230    env["PATH"] = str(d) + os.pathsep + env.get("PATH", "")
231    log("no NVIDIA card here: a stand-in nvidia-smi (one 24 GB card) is used for setup's step 1")
232
233
234def sandbox_env(work: Path, install: Path, feed: Path, trust: Path, port: int) -> dict:
235    env = {k: v for k, v in os.environ.items() if not k.startswith(("STRATA_", "HF_")) and k not in ("PYTHONPATH", "PYTHONHOME")}
236    home = work / "home"
237    home.mkdir(exist_ok=True)
238    env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home / "AppData" / "Roaming"), "LOCALAPPDATA": str(home / "AppData" / "Local"),
239                "XDG_DATA_HOME": str(home / ".local" / "share"), "XDG_CONFIG_HOME": str(home / ".config"), "XDG_STATE_HOME": str(home / ".local" / "state"),
240                "XDG_CACHE_HOME": str(home / ".cache"), "STRATA_CONTROL_INSTALL": "1", "STRATA_INSTALL_DIR": str(install), "STRATA_COMPONENTS_DIR": str(work / "comp"),
241                "STRATA_UPDATE_FEED": str(feed), "STRATA_UPDATE_TRUSTED_KEYS": str(trust), "STRATA_NO_PATH": "1", "HF_ENDPOINT": f"http://127.0.0.1:{port}",
242                "PYTHONUTF8": "1", "PYTHONNOUSERSITE": "1", "STRATA_ALLOW_UNPINNED": "1"})
243    return env
244
245
246def kill_tree(proc: subprocess.Popen) -> None:
247    """Only the process this script started and its children."""
248    if os.name == "nt":
249        subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True)
250    else:
251        try:
252            os.killpg(proc.pid, signal.SIGKILL)
253        except OSError:
254            proc.kill()
255
256
257def run_setup(env: dict, data: Path, extra: list[str], timeout: int = SETUP_TIMEOUT) -> tuple[int, str]:
258    """setup.py in the app's mode. A run that does not end in `timeout` seconds (a fetch of something the model list did not name keeps retrying) is killed and reported."""
259    cmd = [sys.executable, str(ROOT / "setup.py"), "--family", MODEL_ID, "--model", QUANT, "--data-dir", str(data), "--feed", env["STRATA_UPDATE_FEED"],
260           "--yes", "--no-start", "--vision", "no", "--context", "32768", "--no-browser", *extra]
261    proc = subprocess.Popen(cmd, cwd=str(ROOT), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace",
262                            start_new_session=(os.name != "nt"))
263    try:
264        out, _ = proc.communicate(timeout=timeout)
265        return proc.returncode, out or ""
266    except subprocess.TimeoutExpired:
267        kill_tree(proc)
268        out, _ = proc.communicate()
269        return 124, (out or "") + f"\n[the gate stopped setup after {timeout} s]\n"
270
271
272def newest(path: Path, pattern: str) -> list[Path]:
273    return sorted(path.rglob(pattern), key=lambda p: p.stat().st_mtime) if path.is_dir() else []
274
275
276def check(work: Path, tokenizer_from: str | None, shape: dict, log) -> dict:
277    """Steps 1 to 4. Returns {"problems": [...], "config": path or None, "out": setup's text}."""
278    problems: list[str] = []
279    model_dir = work / "mirror" / REPO
280    model_dir.mkdir(parents=True)
281    model = model_dir / FILE_NAME
282    t = time.time()
283    make_synthetic(model, shape, tokenizer_from)
284    log(f"synthetic file {model.stat().st_size / 1e9:.2f} GB in {time.time() - t:.1f} s")
285    feed = work / "feed"
286    trust = build_feed(feed, make_entry(model), work)
287    install, data = work / "install", work / "data"
288    install.mkdir()
289    with Mirror(work / "mirror") as mirror:
290        env = sandbox_env(work, install, feed, trust, mirror.port)
291        nvidia_stub_if_needed(env, work, log)
292        t = time.time()
293        code, out = run_setup(env, data, [])
294        log(f"setup run 1: exit {code} in {time.time() - t:.0f} s")
295        asked = [p for p in mirror.seen if "/resolve/" in p]
296        if code != 0:
297            problems.append(f"setup exited {code}")
298        for bad in ("Traceback", "KeyError"):
299            if bad in out:
300                problems.append(f"setup printed {bad!r}")
301        if "llama.cpp source" in out or any("llama.cpp" in p or "ggml-org" in p for p in mirror.seen):
302            problems.append("setup fetched llama.cpp (the preparation tools have their own GGUF code: tools/strata_gguf.py)")
303        if (install / "third_party" / "llama.cpp").exists():
304            problems.append("setup wrote third_party/llama.cpp into the install folder")
305        wrong = sorted({p for p in asked if FILE_NAME not in p})
306        if wrong:                                       # F3: the Flash-Next draft layer (or anything else of another repository) was asked for
307            problems.append("setup asked the model host for more than the model's file: " + ", ".join(wrong[:4]))
308        if NO_DRAFT_LINE not in out:
309            problems.append("setup did not say that the model list has no draft layer")
310        if "Downloading the draft layer" in out:
311            problems.append("setup announced a draft layer download for a model with `drafter: none`")
312        if shape is TINY or shape["layers"] != 48:
313            if NEUTRAL_LINE not in out:
314                problems.append("setup did not say it made a neutral expert profile (F4)")
315        cfgs = [p for p in newest(install, "*.json") if "run" in p.name.lower() or p.parent.name in ("configs", "run")] or newest(install, "config*.json")
316        configs = [p for p in newest(install, "*.json") if _is_run_config(p)]
317        config = configs[-1] if configs else None
318        if config is None:
319            problems.append("no run config was written")
320        else:
321            problems += config_problems(config, data, install, out)
322        extra = sorted(str(p.relative_to(work)) for p in work.rglob("experts.bin*"))
323        if extra:                                         # F5: the low-RAM mode copies the experts into a second file
324            problems.append("a second copy of the experts was written: " + ", ".join(extra[:3]))
325        # run 2: a finished install is left alone and downloads nothing
326        before = len(mirror.seen)
327        mtime = config.stat().st_mtime if config else None
328        t = time.time()
329        code2, out2 = run_setup(env, data, [])
330        log(f"setup run 2: exit {code2} in {time.time() - t:.0f} s")
331        if code2 != 0:
332            problems.append(f"the second setup run exited {code2}")
333        if len([p for p in mirror.seen[before:] if "/resolve/" in p and "Range" not in p]) and ("Downloading" in out2):
334            problems.append("the second run downloaded the model again")
335        for bad in ("Traceback", "KeyError"):
336            if bad in out2:
337                problems.append(f"the second run printed {bad!r}")
338    return {"problems": problems, "config": config, "out": out, "work": work, "data": data}
339
340
341def _is_run_config(p: Path) -> bool:
342    try:
343        d = json.loads(p.read_text(encoding="utf-8-sig"))
344    except (OSError, ValueError):
345        return False
346    return isinstance(d, dict) and "args" in d and ("exe" in d or "model_name" in d)
347
348
349def config_problems(config: Path, data: Path, install: Path, out: str) -> list[str]:
350    problems = []
351    d = json.loads(config.read_text(encoding="utf-8-sig"))
352    args = [str(a) for a in d.get("args", [])]
353    text = " ".join(args)
354    if not any(a.endswith(".gguf") or ".gguf" in a for a in args) and "--model" not in args:
355        problems.append("the run config names no model file")
356    if d.get("backend") == "metal":                       # a Mac (setup's mac_control_setup): the Metal engine maps the GGUF in place, its arena is its RAM budget
357        if "--mmap-experts" not in args:
358            problems.append("the Mac run config has no --mmap-experts (the experts read in place from the GGUF)")
359    elif "--resident-budget-gib" not in args:             # F5: a feed qwen4exp size is read in place with a RAM budget of its experts
360        problems.append("the run config has no --resident-budget-gib (the RAM budget of the experts)")
361    profiles = [a for a in args if "expert-profile" in a]
362    if not profiles:
363        problems.append("the run config names no expert profile")
364    else:
365        for pr in profiles:
366            if pr.startswith("--"):
367                continue
368            if not Path(pr).is_file():
369                problems.append(f"the expert profile {pr} is not a file")
370    return problems
371
372
373def start_engine(config: Path, engine: Path, work: Path, log) -> list[str]:
374    """Step 5: the engine of the run config, one request. The engine folder replaces the config's `component:` engine."""
375    problems: list[str] = []
376    d = json.loads(config.read_text(encoding="utf-8-sig"))
377    exe = next((p for p in (engine / "strata", engine / "strata.exe", engine / "bin" / "strata", engine / "bin" / "strata.exe") if p.is_file()), None)
378    if exe is None:
379        return [f"no strata engine program in {engine}"]
380    port = free_port()
381    cfg = dict(d, exe=str(exe), port=port, host="127.0.0.1")            # the config's `component:strata-engine` is this engine folder
382    cfg_file = work / "engine-run.json"
383    cfg_file.write_text(json.dumps(cfg), encoding="utf-8")
384    env = dict(os.environ, PYTHONUTF8="1")
385    env.update({k: str(v) for k, v in (d.get("env") or {}).items()})
386    libs = [str(engine)] + [str(x) for x in d.get("lib_dirs", [])]
387    env["LD_LIBRARY_PATH"] = os.pathsep.join(libs + [env.get("LD_LIBRARY_PATH", "")])
388    args = [sys.executable, "-m", "serve.server", "--engine", "strata", "--config", str(cfg_file), "--port", str(port), "--host", "127.0.0.1"]
389    logfile = work / "engine.log"
390    with logfile.open("wb") as lf:
391        proc = subprocess.Popen(args, cwd=str(ROOT), env=env, stdout=lf, stderr=subprocess.STDOUT)
392    try:
393        deadline, ready = time.time() + 600, False
394        while time.time() < deadline and proc.poll() is None:
395            try:
396                urllib.request.urlopen(f"http://127.0.0.1:{port}/v1/models", timeout=3).read()
397                ready = True
398                break
399            except OSError:
400                time.sleep(2)
401        if not ready:
402            return ["the engine did not come up: " + logfile.read_text(errors="replace")[-500:]]
403        models = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{port}/v1/models", timeout=10).read())
404        body = json.dumps({"model": models["data"][0]["id"], "messages": [{"role": "user", "content": "What is the capital of France?"}], "max_tokens": 24,
405                           "temperature": 0}).encode()
406        req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", body, {"Content-Type": "application/json"})
407        reply = json.loads(urllib.request.urlopen(req, timeout=600).read())
408        usage = reply.get("usage") or {}
409        log(f"one request: finish {reply['choices'][0].get('finish_reason')}, usage {usage}")
410        if not usage.get("completion_tokens"):
411            problems.append("the request returned no completion tokens")
412        if reply["choices"][0].get("finish_reason") not in ("length", "stop"):
413            problems.append("the request did not finish normally")
414    except Exception as e:                                # noqa: BLE001
415        problems.append(f"the request failed: {e}")
416    finally:
417        if proc.poll() is None:
418            proc.terminate()
419            try:
420                proc.wait(30)
421            except subprocess.TimeoutExpired:
422                proc.kill()
423    return problems
424
425
426def main(argv=None) -> int:
427    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
428    ap.add_argument("--tokenizer-from", help="a real qwen4exp GGUF (shard 1): the synthetic file gets its tokenizer (needed by --engine)")
429    ap.add_argument("--engine", type=Path, help="an engine folder built for the file's shape: step 5 starts it and sends one request (needs --full)")
430    ap.add_argument("--full", action="store_true", help="the 4-layer q4_lite stand-in of the rehearsal instead of the small file (3.5 GB with a real tokenizer)")
431    ap.add_argument("--work", type=Path, help="scratch folder (default: a new temp folder, removed at the end unless --keep)")
432    ap.add_argument("--keep", action="store_true")
433    a = ap.parse_args(argv)
434    if a.engine and not a.full:
435        print("--engine needs --full: the engine is built for one shape, the small file is another", file=sys.stderr)
436        return 2
437    log = lambda s: print(time.strftime("%H:%M:%S"), s, flush=True)   # noqa: E731
438    try:
439        check_gguf_tools()
440    except NotRun as e:
441        print("NOT RUN:", e)
442        return 2
443    work = a.work or Path(tempfile.mkdtemp(prefix="strata-feed-install-gate-"))
444    if a.work:
445        if work.exists() and any(work.iterdir()):
446            print("--work needs a new or empty folder", file=sys.stderr)
447            return 2
448        work.mkdir(parents=True, exist_ok=True)
449    code = 1
450    try:
451        res = check(work, a.tokenizer_from, FULL if a.full else TINY, log)
452        problems = res["problems"]
453        if not problems and a.engine:
454            ep = start_engine(res["config"], a.engine, work, log)
455            if ep:
456                problems, code = ep, 3
457        if problems:
458            print("FAIL:")
459            for p in problems:
460                print("  -", p)
461            print("---- setup output (tail) ----")
462            print("\n".join(res["out"].splitlines()[-40:]))
463            code = code if code == 3 else 1
464        else:
465            print("PASS: feed model installed from a real file" + (" and answered one request" if a.engine else ""))
466            code = 0
467    except NotRun as e:
468        print("NOT RUN:", e)
469        code = 2
470    finally:
471        if a.keep:
472            print("kept", work)
473        else:
474            shutil.rmtree(work, ignore_errors=True)
475    return code
476
477
478if __name__ == "__main__":
479    sys.exit(main())