Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
start and serve never acquire: one guard, a typed error, a test that fails on egress
Niko12212e3085a55522
diff --git a/setup.py b/setup.pyindex e90d33d6d..71ee66274 100644--- a/setup.py+++ b/setup.py@@ -58,6 +58,8 @@ import urllib.requestimport zipfilefrom pathlib import Path+from strata_control import acquisition+ROOT = Path(__file__).resolve().parentWIN = os.name == "nt"# #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of@@ -111,7 +113,7 @@ def ms_endpoint() -> str:def reachable(url: str, timeout: float = 5.0) -> bool:"""Whether `url` answers a HEAD request with success (2xx, after redirects) within `timeout` seconds."""try:- urllib.request.urlopen(urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"}),+ _urlopen(urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"}),timeout=timeout).close()return Trueexcept OSError: # HTTPError too: an error page is not the file@@ -154,7 +156,7 @@ def ms_meta(repo: str, path: str):if repo not in _ms_files:try:api = f"{ms_endpoint()}/api/v1/models/{repo}/repo/files?Recursive=true"- with urllib.request.urlopen(urllib.request.Request(api, headers={"User-Agent": "strata-setup"}),+ with _urlopen(urllib.request.Request(api, headers={"User-Agent": "strata-setup"}),timeout=60) as r:files = json.loads(r.read())["Data"]["Files"]_ms_files[repo] = {f["Path"]: (int(f.get("Size") or 0), (f.get("Sha256") or "").lower()) for f in files}@@ -536,7 +538,16 @@ def ask(question, choices, default, yes):say(f" please answer one of: {', '.join(choices)}")+def _urlopen(req, timeout=None):+ """Every network request of this file goes through here: starting and serving never reach the network+ (strata_control/acquisition.py), only an explicit setup, update or install does."""+ acquisition.require("a download")+ return urllib.request.urlopen(req, timeout=timeout)++def run(cmd, cwd=None, env=None, check=True, quiet=False):+ """An install, build or preparation step (pip, cmake, a package manager, tools/*.py): never part of a start."""+ acquisition.require("an install or build step (" + Path(str(cmd[0])).name + ")")say(" > " + " ".join(str(c) for c in cmd))r = subprocess.run([str(c) for c in cmd], cwd=cwd, env=env,stdout=subprocess.PIPE if quiet else None, stderr=subprocess.STDOUT if quiet else None,@@ -1629,6 +1640,7 @@ def download(url, dst: Path, what=None):if dst.exists() and done(dst):ok(f"{what or dst.name} already downloaded")return+ acquisition.require(what or dst.name)if not url.startswith(("http://", "https://")):src = Path(url[7:] if url.startswith("file://") else url)if not src.exists():@@ -1649,7 +1661,7 @@ def download(url, dst: Path, what=None):for attempt in range(5):try:req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"})- total = int(urllib.request.urlopen(req, timeout=60).headers.get("Content-Length", 0))+ total = int(_urlopen(req, timeout=60).headers.get("Content-Length", 0))breakexcept urllib.error.HTTPError as e:if e.code == 404 and hf_unpinned(url) != url: # #214: the pinned revision is gone from the repository@@ -1676,7 +1688,7 @@ def download(url, dst: Path, what=None):break # ask for (a range past the end is a 416, retried 30 times)try:req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={have}-"})- with urllib.request.urlopen(req, timeout=60) as r, open(part, "ab" if have else "wb") as f:+ with _urlopen(req, timeout=60) as r, open(part, "ab" if have else "wb") as f:if have and r.status != 206: # the server ignored the range: start overf.seek(0)f.truncate()@@ -2081,6 +2093,7 @@ def pip_install(packages, what):if not need:ok(f"{what} already installed")return+ acquisition.require(what)say(f" Installing {what} ...")run([sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", *need])stamp.write_text(json.dumps(sorted(set(have) | set(need)), indent=0))@@ -2200,7 +2213,7 @@ def rocm_wanted(index, listing=None):if listing is None:try:req = urllib.request.Request(index.rstrip("/") + "/rocm/", headers={"User-Agent": "strata-setup"})- with urllib.request.urlopen(req, timeout=30) as r:+ with _urlopen(req, timeout=30) as r:listing = r.read().decode("utf-8", "replace")except (OSError, ValueError):listing = ""@@ -2843,6 +2856,7 @@ def hip_card(eng: Path, gpu: dict, listed: list[dict]) -> dict:def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None:"""The ready-made Windows HIP engine (WIN_HIP_ASSET) in engine/, kept between runs; None when it cannot be had(not published for this version, no internet) or has no code for the card."""+ acquisition.require("the ready-made AMD engine")eng = ROOT / "engine"info = eng / "BUILD.json"if info.exists() and (eng / EXE).exists():@@ -2865,7 +2879,7 @@ def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None:breaktry:req = urllib.request.Request(base + WIN_HIP_ASSET, method="HEAD", headers={"User-Agent": "strata-setup"})- urllib.request.urlopen(req, timeout=60).close()+ _urlopen(req, timeout=60).close()breakexcept OSError as e:if i + 1 < len(bases):@@ -3028,6 +3042,7 @@ def build_engine_hip(gpu, llama, vision="none") -> Path:"""Compile the HIP engine for this AMD GPU into engine/ (again only when its source changed: a `git pull`).gpu["archs"]: every architecture it needs code for (the cards of a layer split), else gpu["arch"]. vision "cpu"(#304): the image encoder too, for the CPU (there is no HIP encoder build yet)."""+ acquisition.require("an engine build")eng = ROOT / "engine"eng.mkdir(exist_ok=True)stamp = eng / "BUILD.json"@@ -3359,7 +3374,7 @@ def engine_digest(asset: str, base: str) -> tuple[int, str] | None:try:req = urllib.request.Request(url, headers={"User-Agent": "strata-setup","Accept": "application/vnd.github+json"})- with urllib.request.urlopen(req, timeout=60) as r:+ with _urlopen(req, timeout=60) as r:rel = json.loads(r.read().decode("utf-8"))except Exception:return None # offline, rate-limited, or the release is not there@@ -3546,6 +3561,7 @@ def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | No"""The ready-made engine in engine/ (kept between runs), or None when there is none for this PC.updating: called to replace an installed engine, which starts instead when this fails (no compile).toolkit 12: the experimental CUDA 12 engine (CUDA12_ASSET) in engine-cuda12/."""+ acquisition.require("the ready-made engine")eng = engine_dir(toolkit)asset = CUDA12_ASSET if int(toolkit) == 12 else PREBUILT_ASSETinfo = eng / "BUILD.json"@@ -3576,7 +3592,7 @@ def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | Nobreaktry: # not published (yet), or no internet: compile insteadreq = urllib.request.Request(base + asset, method="HEAD", headers={"User-Agent": "strata-setup"})- urllib.request.urlopen(req, timeout=60).close()+ _urlopen(req, timeout=60).close()breakexcept OSError as e:if i + 1 < len(bases): # #214: this checkout's release is not published (yet)@@ -3658,6 +3674,33 @@ def update_engine_gpu(toolkit=13):return {**g, "count": len(found)}+def engine_update_note() -> None:+ """A start looks at the installed engine(s) and says when UPDATE would replace one; it changes nothing and reaches+ no network (the engine that is installed starts as it is). update_installed_engine, below, is what UPDATE.bat /+ update.sh and a setup run do."""+ for toolkit in (13, 12):+ eng = engine_dir(toolkit)+ info = eng / "BUILD.json"+ if not info.exists() or not (eng / EXE).exists():+ continue+ try:+ meta = json.loads(info.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ continue+ ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit())+ need = WIN_HIP_MIN_ENGINE if (meta.get("backend") == "hip" and WIN) else MIN_ENGINE+ if meta.get("source") == "local":+ old = meta.get("src") != source_hash(ENGINE_SOURCES) or stale_binary(eng / EXE)+ elif meta.get("backend") == "hip" and not WIN:+ old = meta.get("src") != source_hash(ENGINE_SOURCES) or stale_binary(eng / EXE)+ else:+ old = ver < need+ if old:+ warn(f"the installed engine ({meta.get('version') or 'unknown version'}) is older than this Strata expects: "+ "starting it as it is. Starting never updates anything; run "+ + ("UPDATE.bat" if WIN else "./update.sh") + " (or `strata install --update`) to update it")++def update_installed_engine(url_base, toolkit=None) -> None:"""An installed ready-made engine older than MIN_ENGINE is replaced before the model starts, so a plainSTART-HERE.bat on an existing install picks up a new release. If that cannot happen (no internet, the model@@ -3751,6 +3794,7 @@ def update_installed_engine(url_base, toolkit=None) -> None:def pip_cuda_libs(toolkit=13) -> None:"""NVIDIA's cuBLAS and CUDA runtime for a ready-made engine, from pip: CUDA 13's, or the CUDA 12 engine's."""+ acquisition.require("NVIDIA's CUDA libraries (pip)")if int(toolkit) == 12:pip_install(CUDA12_WHEELS, "NVIDIA CUDA 12 libraries for the experimental engine (cuBLAS, CUDA runtime; ~0.7 GB)")else:@@ -3800,6 +3844,7 @@ def cuda_apt_repo(osr):def install_build_tools(gpu, yes):"""The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars)."""+ acquisition.require("the compiler and CUDA toolkit")archs = [int(x) for x in gpu.get("archs", [gpu["arch"]])]# #295: Pascal / Volta need a CUDA 12.x toolkit - CUDA 13 cannot build sm_60/sm_70; gpu["toolkit"] = 12: the# experimental CUDA 12 engine for any cards (--cuda 12, docs/OLDER_GPUS.md)@@ -3886,6 +3931,7 @@ def install_build_tools(gpu, yes):def cmake_build(src, bdir, target, defs, vcvars, bat_name):+ acquisition.require("a compile (cmake)")# The ready-made engine path never calls this function. Keep build helpers out of# the normal serving environment, and use already installed tools offline.build_packages = requirement_lines(BUILD_REQUIREMENTS) if BUILD_REQUIREMENTS.exists() else BUILD_PACKAGES@@ -3988,6 +4034,7 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path:engine whose source files changed since (a `git pull`) is compiled again: only the changed files, a few minutes.toolkit 12 (default: 12 for a card older than CUDA 13 supports): the experimental CUDA 12 engine, inengine-cuda12/ with its own build folders."""+ acquisition.require("an engine build")if toolkit is None:toolkit = 12 if min(int(x) for x in gpu.get("archs", [gpu["arch"]])) < CUDA13_MIN_ARCH else 13t12 = int(toolkit) == 12@@ -4470,6 +4517,15 @@ def data_folder(requested: str | None) -> tuple:return dest, elsewhere+def data_folder_in_place() -> tuple:+ """(the data folder, []) for a start: where settings.json says the model files are, or the default place. Reads+ the settings and nothing else: no folder is created, nothing is moved or copied, no setting is saved. The run+ configs name their model files, so an install made by an earlier Strata starts from where it is."""+ settings = load_settings()+ dest = Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "Strata-data"+ return dest, []++def write_config(path: Path, cfg: dict):"""A run config, written whole or not at all (#459): to a temporary file first, then moved over the old one, soa setup stopped half-way (a closed window, a full disk) never leaves an empty strata-*.json behind."""@@ -4946,6 +5002,14 @@ def settings_summary(cfg: dict, port=None) -> str:def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False,layer_split=None, keep=None) -> int:+ """Start the model. Nothing is installed, downloaded or compiled while it starts (strata_control/acquisition.py):+ what is missing is named with the command that installs it (SETUP / UPDATE / strata install)."""+ with acquisition.forbidden():+ return _start(cfg_path, port, gpu, open_browser, yes, layer_split, keep)+++def _start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False,+ layer_split=None, keep=None) -> int:"""keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab,--vram-reserve-mib)."""cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig")))@@ -5400,6 +5464,8 @@ def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict:missing = [g for g in cards if not (engine_runs_on(g) if tk == 13 else engine_runs_on(g, tk))]if not missing:return cfg+ acquisition.require("an engine with code for " + ", ".join(f"{g['name']} (sm_{g['arch']})" for g in missing),+ ("START-HERE.bat --setup" if WIN else "./setup.sh --setup") + " (it compiles the engine for these cards)")eng = engine_dir(tk)info = eng / "BUILD.json"meta = json.loads(info.read_text(encoding="utf-8"))@@ -5436,7 +5502,10 @@ def engine_lib_dirs(eng: Path, toolkit=13) -> list:def use_cuda12(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict:"""A model on the CUDA 13 engine now has a Pascal / Volta card (a --gpus at start): the model's config moves tothe experimental CUDA 12 engine (one engine per model; its other models keep theirs)."""+ acquisition.require("the experimental CUDA 12 engine")old = min(int(g["arch"]) for g in cards)+ acquisition.require("the experimental CUDA 12 engine for sm_%d" % old,+ ("START-HERE.bat --setup --cuda 12" if WIN else "./setup.sh --setup --cuda 12"))say()warn(f"sm_{old} is older than CUDA 13 supports (it dropped Pascal and Volta): this model moves to the experimental ""CUDA 12 engine (docs/OLDER_GPUS.md; START-HERE.bat --setup --cuda 13 and newer cards only moves it back)")@@ -6076,7 +6145,14 @@ def main() -> int:else:ap.error(f"--gpu takes a GPU number as nvidia-smi numbers them, e.g. --gpu 1 (or --gpus 0,2), not {a.gpu!r}")say("Strata - Qwen3.8-Flash-Next on a normal PC (a GPU + system RAM + CPU)")- data, elsewhere = data_folder(a.data_dir) # the model files: in the data folder, found from any copy+ have = installed_configs()+ # A plain start of an installed model finds everything where it already is: it creates, moves and copies nothing+ # (the model paths are in the run config; the data folder is the one settings.json remembers). Setting up, checking,+ # tuning and updating look for and gather the model files (data_folder).+ plain_start = bool(have) and not (a.setup or a.model or a.family or a.check or a.no_start or a.update+ or a.calibrate or a.rollback_engine or a.data_dir)+ models_dir_given = a.models_dir is not None+ data, elsewhere = data_folder_in_place() if plain_start else data_folder(a.data_dir) # the model filesroots = [data, *elsewhere]if a.models_dir is None:a.models_dir = str(data / "models")@@ -6085,7 +6161,6 @@ def main() -> int:return rollback_engine(12 if a.cuda == "12" else 13)# ---- 0. already installed: just start it- have = installed_configs()if a.update: # #475: UPDATE.bat / update.sh - never starts the modelreturn update_install(have, a)explicit = a.setup or a.model or a.family or a.check or a.no_start@@ -6131,8 +6206,7 @@ def main() -> int:fail(f"--calibrate: {a.model or a.family} is not installed (installed: {names})","calibrate an installed model, or set this one up first without --calibrate")have = targets- if not a.build:- update_installed_engine(a.prebuilt)+ engine_update_note()pick_cfg = have[0]if len(have) > 1:say()@@ -6147,8 +6221,7 @@ def main() -> int:keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab,"vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser})if have and not (a.setup or a.model or a.family or a.check or a.no_start):- if not a.build:- update_installed_engine(a.prebuilt)+ engine_update_note()if len(have) == 1:return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split,keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab,@@ -6162,6 +6235,10 @@ def main() -> int:return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split,keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab,"vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser})+ data, elsewhere = data_folder(a.data_dir) # "install another model": now the model files are gathered+ roots = [data, *elsewhere]+ if not models_dir_given:+ a.models_dir = str(data / "models")# ---- 1. the PCstep(1, "checking your PC")@@ -7094,6 +7171,9 @@ def main() -> int:if __name__ == "__main__":try:sys.exit(main())+ except acquisition.AcquisitionRefused as e: # a start that would have installed something: said, not done+ say(f"\n [X] {e}")+ sys.exit(e.exit_code)except KeyboardInterrupt:say("\nstopped.")sys.exit(1)diff --git a/strata_cli/cli.py b/strata_cli/cli.pyindex 5894e6e90..23a0580a2 100644--- a/strata_cli/cli.py+++ b/strata_cli/cli.py@@ -16,6 +16,8 @@ from pathlib import Pathfrom strata_control import profiles+ROOT = Path(__file__).resolve().parents[1]+#: Backend families, as the engine package manifest records them. Kept here so the argument parsers#: stay declarative without importing the tuning module on every CLI start.BACKENDS = ("metal", "cuda", "hip", "sycl", "cpu")@@ -146,6 +148,13 @@ def parser() -> argparse.ArgumentParser:calibrate.add_argument("--out", metavar="REPORT.json", help="new report path for --measure")calibrate.add_argument("--exclusive", action="store_true", help="assert all model instances using these devices are stopped")calibrate.add_argument("--output", choices=("human", "json"), default="human")+ install = sp.add_parser(+ "install",+ help="the explicit installer: engine, models, Python packages (starting and serving never do this)")+ install.add_argument("--update", action="store_true",+ help="update an existing install (what UPDATE.bat / update.sh run) instead of setting one up")+ install.add_argument("setup_args", nargs=argparse.REMAINDER,+ help="options passed to setup.py, e.g. --family qwen --model Q2_0 --yes")runtime = sp.add_parser("runtime", help="manage an owned local Strata server instance")runtime_sp = runtime.add_subparsers(dest="runtime_command", required=True)runtime_start = runtime_sp.add_parser("start", help="start a saved profile under the local owner host")@@ -1644,10 +1653,26 @@ def _components_backends(a: argparse.Namespace) -> int:return 0+def _install(a: argparse.Namespace) -> int:+ """The one place the terminal acquires anything: it hands over to the installer (setup.py) of a full Strata+ folder, which is where pip, the engine and the models are fetched. A folder without it (the terminal archive)+ says so and names what to do instead."""+ installer = Path(os.environ.get("STRATA_INSTALL_DIR") or ROOT) / "setup.py"+ if not installer.is_file():+ return _error("this folder has no installer (setup.py). Engines, models and updates are installed from a "+ "full Strata folder with SETUP.bat / ./setup.sh and UPDATE.bat / ./update.sh; "+ "set STRATA_INSTALL_DIR to that folder to run it from here", 5)+ extra = [x for x in a.setup_args if x != "--"]+ return subprocess.call([sys.executable, str(installer), "--update" if a.update else "--setup", *extra],+ cwd=str(installer.parent))++def _run(a: argparse.Namespace) -> int:try:if a.command == "serve":return _serve(a)+ if a.command == "install":+ return _install(a)if a.command == "profile":return _profile_command(a)if a.command == "components" and a.components_command == "plan":diff --git a/strata_control/acquisition.py b/strata_control/acquisition.pynew file mode 100644index 000000000..a61e6b4ad--- /dev/null+++ b/strata_control/acquisition.py@@ -0,0 +1,84 @@+"""The line between serving and acquiring.++Starting a model and serving an API never install, download or compile anything. Everything that+reaches the network or runs pip, git, cmake or a package manager lives behind an explicit command:+SETUP, UPDATE or `strata install`. This module is that line, in one place:++* `forbidden()` marks a stretch of code (a start, a serve) in which acquiring is not allowed;+* `require(what, command)` is called by every acquiring primitive (a download, a pip install, a+ network probe, a compile) and raises `AcquisitionRefused` inside such a stretch;+* `AcquisitionRefused` is the typed error: it says what is missing and names the explicit command.++The environment variable `STRATA_NO_ACQUIRE=1` forbids acquiring for a whole process. A process+that serves (`strata serve`, `strata runtime start`, the API server) never imports the installer, so+for it this is a second line of defence, not the first.++Nothing here imports anything outside the standard library.+"""++from __future__ import annotations++import contextlib+import os+import sys+import threading++ENV = "STRATA_NO_ACQUIRE"++_lock = threading.Lock()+_depth = 0+++class AcquisitionRefused(RuntimeError):+ """Something would have been downloaded or installed during a start or a serve."""++ code = "acquisition_refused"+ exit_code = 5++ def __init__(self, what: str, command: str | None = None):+ self.what = what+ self.command = command or explicit_commands()+ super().__init__(+ f"{what} is missing or out of date. Starting and serving never install or download "+ f"anything. Run: {self.command}")+++def explicit_commands() -> str:+ """The commands that acquire, named for this platform."""+ if os.name == "nt":+ return "SETUP.bat (first-time setup), UPDATE.bat (update) or `strata install`"+ return "./setup.sh (first-time setup), ./update.sh (update) or `strata install`"+++def is_forbidden() -> bool:+ return _depth > 0 or os.environ.get(ENV, "").strip().lower() in ("1", "true", "yes", "on")+++def forbidden():+ """No acquisition inside this block. Nests."""+ global _depth+ with _lock:+ _depth += 1+ try:+ yield+ finally:+ with _lock:+ _depth -= 1+++def require(what: str, command: str | None = None) -> None:+ """Call before acquiring `what`; raises AcquisitionRefused where acquiring is forbidden."""+ if is_forbidden():+ raise AcquisitionRefused(what, command)+++def main_guard(fn, *, fail=None):+ """Run `fn()`; a refused acquisition becomes `fail(message, hint)` (or an exit-5 message)."""+ try:+ return fn()+ except AcquisitionRefused as exc:+ if fail is not None:+ return fail(str(exc), None)+ print(f"strata: {exc}", file=sys.stderr)+ return exc.exit_codediff --git a/tests/terminal/test_no_acquisition.py b/tests/terminal/test_no_acquisition.pynew file mode 100644index 000000000..1adca1a97--- /dev/null+++ b/tests/terminal/test_no_acquisition.py@@ -0,0 +1,326 @@+"""Starting and serving never acquire anything.++The owner's rule: a user must never download random packages from the internet while starting or serving. Everything+that installs, downloads or compiles lives behind an explicit command (SETUP, UPDATE, `strata install`). Three layers+are checked here:++* the import graph of the start/serve entry points does not reach installer code;+* no module on the start/serve side runs pip, git, cmake, npm or a package manager, or opens a URL, outside a short+ list of request-time and loopback uses, each with its reason;+* a real start (setup.main with an installed model) with the network and every subprocess mocked makes no request and+ runs no installer, and a start that WOULD need one stops with a typed error that names the explicit command.+"""++import ast+import contextlib+import io+import json+import os+import subprocess+import sys+import tempfile+import unittest+import urllib.request+from pathlib import Path+from unittest import mock++import setup+from strata_cli import cli+from strata_control import acquisition++ROOT = Path(__file__).resolve().parents[2]++#: Modules the start/serve entry points must never load.+INSTALLER_MODULES = {"setup", "pip", "ensurepip", "venv", "huggingface_hub", "modelscope", "metal.setup_mac",+ "sycl.setup_intel"}+#: Files that may be loaded on the start/serve side besides the control, cli and serve packages.+ALLOWED_TOOLS = {"tools.strata_tokenizer", "tools.gguf_reader"} # read-only: a tokenizer and a GGUF header reader++#: argv words that mean "acquire": a subprocess whose literal argv contains one of these is an installer.+INSTALL_WORDS = {"pip", "pip3", "git", "cmake", "ninja", "npm", "npx", "pnpm", "yarn", "winget", "apt-get", "apt",+ "dnf", "pacman", "brew", "curl", "wget", "choco"}++#: (file, call) -> why a network call there is not an acquisition. Request-time and loopback only.+NETWORK_ALLOWED = {+ ("serve/server.py", "urlopen"): "an image_url a client sends in a chat request is fetched at request time",+ ("serve/mcp.py", "urlopen"): "the MCP servers the user configured, at request time",+ ("strata_control/tune_api.py", "urlopen"): "the loopback engine/server of a tuning job the user started",+ ("strata_control/components.py", "urlopen"): "the component fetcher: only `strata install`/UPDATE call it",+}+#: Modules that import the installer on purpose, with the explicit command that reaches them.+INSTALLER_IMPORT_ALLOWED = {+ "strata_control/calibration.py": "`strata engine calibrate`: an explicit tuning command, imports setup lazily",+}++SERVING_DIRS = ("serve", "strata_cli", "strata_control")+++def _sources():+ for d in SERVING_DIRS:+ for p in sorted((ROOT / d).glob("*.py")):+ if p.name.startswith("test_") or p.name == "__init__.py":+ continue+ yield p+ yield ROOT / "strata.py"+++class ImportGraphTests(unittest.TestCase):+ def test_start_and_serve_modules_do_not_load_installer_code(self):+ script = (+ "import sys, os, json\n"+ "sys.path.insert(0, os.getcwd())\n"+ "import strata_cli.cli as c\n"+ "import serve.server\n"+ "from strata_control import runtime\n"+ "c.parser()\n"+ "root = os.getcwd()\n"+ "mods = {n: os.path.relpath(m.__file__, root).replace(os.sep, '/') for n, m in list(sys.modules.items())\n"+ " if getattr(m, '__file__', None) and os.path.abspath(m.__file__).startswith(root)}\n"+ "print(json.dumps({'mods': mods, 'names': sorted(sys.modules)}))\n")+ r = subprocess.run([sys.executable, "-c", script], cwd=ROOT, capture_output=True, text=True, timeout=120)+ self.assertEqual(r.returncode, 0, r.stderr[-1000:])+ got = json.loads(r.stdout.strip().splitlines()[-1])+ loaded = set(got["names"])+ self.assertEqual(sorted(loaded & INSTALLER_MODULES), [])+ for name, rel in got["mods"].items():+ top = rel.split("/")[0]+ self.assertIn(top, ("serve", "strata_cli", "strata_control"),+ f"{name} ({rel}) is loaded by starting/serving but is not part of it")+ self.assertNotIn("strata_control.calibration", got["mods"])+ self.assertNotIn("strata_control.components", got["mods"])++ def test_static_imports_of_the_installer_are_explicit_commands_only(self):+ found = {}+ for p in _sources():+ rel = p.relative_to(ROOT).as_posix()+ tree = ast.parse(p.read_text(encoding="utf-8"))+ for node in ast.walk(tree):+ names = []+ if isinstance(node, ast.Import):+ names = [a.name for a in node.names]+ elif isinstance(node, ast.ImportFrom) and node.module:+ names = [node.module]+ for n in names:+ top = n.split(".")[0]+ if top == "setup" or n.startswith(("tools.", "metal.", "sycl.")) and n not in ALLOWED_TOOLS:+ found.setdefault(rel, []).append(n)+ for rel in found:+ self.assertIn(rel, INSTALLER_IMPORT_ALLOWED, f"{rel} imports installer code: {found[rel]}")++ def test_no_installer_subprocess_or_network_call_on_the_serving_side(self):+ bad = []+ for p in _sources():+ rel = p.relative_to(ROOT).as_posix()+ tree = ast.parse(p.read_text(encoding="utf-8"))+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ fn = node.func+ name = fn.attr if isinstance(fn, ast.Attribute) else fn.id if isinstance(fn, ast.Name) else ""+ if name in ("urlopen", "urlretrieve") and (rel, name) not in NETWORK_ALLOWED \+ and (rel, "urlopen") not in NETWORK_ALLOWED:+ bad.append(f"{rel}:{node.lineno} {name}")+ if name in ("run", "call", "Popen", "check_call", "check_output") and node.args:+ argv = node.args[0]+ words = []+ if isinstance(argv, (ast.List, ast.Tuple)):+ words = [e.value for e in argv.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)]+ elif isinstance(argv, ast.Constant) and isinstance(argv.value, str):+ words = argv.value.split()+ hit = INSTALL_WORDS & {Path(w).stem if w.endswith(".exe") else w for w in words}+ if hit:+ bad.append(f"{rel}:{node.lineno} subprocess {sorted(hit)}")+ self.assertEqual(bad, [])+ for key, why in NETWORK_ALLOWED.items():+ self.assertTrue(why)+++class _Recorder:+ """Stands in for the network and for every way of starting a program; records what a start tries."""++ def __init__(self):+ self.network = []+ self.programs = []++ def urlopen(self, req, *a, **k):+ self.network.append(getattr(req, "full_url", str(req)))+ raise AssertionError("a start reached the network: " + self.network[-1])++ def program(self, argv, *a, **k):+ argv = [str(x) for x in (argv if isinstance(argv, (list, tuple)) else str(argv).split())]+ self.programs.append(argv)+ return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")++ def installers(self):+ return [a for a in self.programs+ if INSTALL_WORDS & {Path(w).stem.lower() if w.lower().endswith(".exe") else w for w in a}+ or "pip" in a or "-m" in a and "pip" in a]+++class StartNeverAcquiresTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name) / "Strata"+ self.root.mkdir()+ self.data = Path(self.tmp.name) / "Strata-data"+ (self.data / "models").mkdir(parents=True)+ self.gguf = self.data / "models" / "m.gguf"+ self.gguf.write_bytes(b"GGUF")+ eng = self.root / "engine"+ eng.mkdir()+ (eng / setup.EXE).write_bytes(b"engine")+ # an engine older than this Strata expects: a start used to download the new one+ (eng / "BUILD.json").write_text(json.dumps({"version": "0.1.1", "source": "prebuilt", "backend": "cuda",+ "archs": [86]}))+ self.cfg = self.root / "strata-q2_0.json"+ self.cfg.write_text(json.dumps({+ "exe": str(eng / setup.EXE), "args": ["--native", str(self.gguf), "--max-context", "8192"],+ "tokenizer": str(self.data / "tok.json"), "model_name": "Q2_0", "port": 8080}))+ self.settings_home = Path(self.tmp.name) / "appdata"+ self.settings_home.mkdir()+ env = {"APPDATA": str(self.settings_home), "XDG_CONFIG_HOME": str(self.settings_home)}+ patcher = mock.patch.dict(os.environ, env)+ patcher.start()+ self.addCleanup(patcher.stop)+ setup.settings_path().parent.mkdir(parents=True, exist_ok=True)+ setup.settings_path().write_text(json.dumps({"data_dir": str(self.data), "installs": [str(self.root)]}))+ self.settings_before = setup.settings_path().read_bytes()+ # pip_install keeps its stamp in sys.prefix: never in the interpreter running the tests+ prefix = mock.patch.object(sys, "prefix", str(self.root))+ prefix.start()+ self.addCleanup(prefix.stop)++ def run_setup(self, rec, *argv, gpus=None):+ out = io.StringIO()+ started = []+ with contextlib.ExitStack() as st:+ st.enter_context(mock.patch.object(setup, "ROOT", self.root))+ st.enter_context(mock.patch.object(sys, "argv", ["setup.py", *argv]))+ st.enter_context(mock.patch.object(urllib.request, "urlopen", rec.urlopen))+ for n in ("run", "call", "Popen", "check_call", "check_output"):+ st.enter_context(mock.patch.object(subprocess, n, rec.program))+ st.enter_context(mock.patch.object(setup, "gpus", lambda: gpus or []))+ st.enter_context(mock.patch.object(setup, "call_server", create=True))+ st.enter_context(mock.patch.object(setup.subprocess, "call", lambda cmd, *a, **k: started.append(cmd) or 0))+ st.enter_context(contextlib.redirect_stdout(out))+ try:+ code = setup.main()+ except SystemExit as e:+ code = e.code+ except acquisition.AcquisitionRefused as e:+ code = e+ return code, out.getvalue(), started++ def test_a_start_with_an_old_engine_makes_no_request_and_runs_no_installer(self):+ rec = _Recorder()+ code, text, started = self.run_setup(rec, "--yes", "--no-browser")+ self.assertEqual(code, 0, text)+ self.assertEqual(rec.network, [])+ self.assertEqual(rec.installers(), [])+ self.assertEqual(len(started), 1, text) # the server was started+ self.assertIn("server.py", " ".join(started[0]))+ self.assertIn("is older than this Strata expects", text)+ self.assertIn("UPDATE", text)++ def test_a_start_moves_copies_and_creates_nothing(self):+ before = sorted(p.relative_to(self.tmp.name).as_posix() for p in Path(self.tmp.name).rglob("*"))+ stamps = {p: p.stat().st_mtime_ns for p in Path(self.tmp.name).rglob("*") if p.is_file()}+ rec = _Recorder()+ code, text, _ = self.run_setup(rec, "--yes", "--no-browser")+ self.assertEqual(code, 0, text)+ after = sorted(p.relative_to(self.tmp.name).as_posix() for p in Path(self.tmp.name).rglob("*"))+ self.assertEqual(before, after)+ self.assertEqual(setup.settings_path().read_bytes(), self.settings_before)+ for p, ns in stamps.items():+ if p != self.cfg: # a start touches the config (most recently used)+ self.assertEqual(p.stat().st_mtime_ns, ns, p)++ def test_a_card_the_engine_has_no_code_for_is_a_typed_error_naming_the_command(self):+ rec = _Recorder()+ card = {"index": 0, "name": "RTX 5090", "arch": "120", "vram_gb": 32.0, "driver": "580.0"}+ with mock.patch.object(setup, "engine_runs_on", lambda g, tk=13: False), \+ mock.patch.object(setup, "old_gpus_opt_in", lambda *a, **k: []):+ code, text, started = self.run_setup(rec, "--yes", "--no-browser", gpus=[card])+ self.assertIsInstance(code, acquisition.AcquisitionRefused)+ self.assertIn("RTX 5090", str(code))+ self.assertIn("setup", str(code).lower())+ self.assertEqual((rec.network, rec.installers(), started), ([], [], []))++ def test_main_script_reports_the_refusal_and_exits_5(self):+ e = acquisition.AcquisitionRefused("an engine for sm_120")+ self.assertEqual(e.exit_code, 5)+ self.assertEqual(e.code, "acquisition_refused")+ self.assertIn("never install or download", str(e))++ def test_every_acquiring_primitive_refuses_while_a_model_starts(self):+ rec = _Recorder()+ calls = [+ lambda: setup.download("https://example.invalid/x.bin", self.root / "x.bin"),+ lambda: setup.download("file:///nonexistent", self.root / "y.bin"),+ lambda: setup.pip_install(["definitely-not-installed==1.0"], "a test package"),+ lambda: setup.run([sys.executable, "-m", "pip", "install", "x"]),+ lambda: setup._urlopen(urllib.request.Request("https://example.invalid/")),+ lambda: setup.reachable("https://example.invalid/"),+ lambda: setup.get_prebuilt("https://example.invalid/", {"arch": "86"}, "none"),+ lambda: setup.cmake_build(self.root, self.root / "b", "strata", [], None, ""),+ lambda: setup.pip_cuda_libs(13),+ ]+ with mock.patch.object(urllib.request, "urlopen", rec.urlopen), \+ mock.patch.object(subprocess, "run", rec.program), mock.patch.object(subprocess, "Popen", rec.program):+ with acquisition.forbidden():+ for i, call in enumerate(calls):+ with self.subTest(i=i):+ with self.assertRaises(acquisition.AcquisitionRefused) as cm:+ call()+ self.assertIn("Run:", str(cm.exception))+ self.assertEqual((rec.network, rec.programs), ([], []))++ def test_the_environment_switch_forbids_a_whole_process(self):+ with mock.patch.dict(os.environ, {acquisition.ENV: "1"}):+ with self.assertRaises(acquisition.AcquisitionRefused):+ setup.pip_install(["definitely-not-installed==1.0"], "a test package")++ def test_update_still_installs(self):+ """The explicit commands keep working: outside a start, the install step runs."""+ installed = []+ with tempfile.TemporaryDirectory() as prefix, mock.patch.object(sys, "prefix", prefix), mock.patch.object(setup, "run", lambda cmd, **k: installed.append([str(c) for c in cmd])):+ setup.pip_install(["somepkg==1.0"], "a test package")+ self.assertEqual(len(installed), 1)+ self.assertIn("pip", installed[0])+++class CliServeIsOfflineTests(unittest.TestCase):+ def test_serve_plan_reaches_no_network_and_runs_no_program(self):+ rec = _Recorder()+ with tempfile.TemporaryDirectory() as d:+ cfg = Path(d) / "strata-x.json"+ gguf = Path(d) / "m.gguf"+ gguf.write_bytes(b"GGUF")+ tok = Path(d) / "t.json"+ tok.write_text("{}")+ exe = Path(d) / "strata.exe"+ exe.write_bytes(b"x")+ cfg.write_text(json.dumps({"exe": str(exe), "args": ["--native", str(gguf)], "tokenizer": str(tok)}))+ out = io.StringIO()+ with mock.patch.object(urllib.request, "urlopen", rec.urlopen), \+ mock.patch.object(subprocess, "run", rec.program), mock.patch.object(subprocess, "Popen", rec.program), \+ mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(Path(d) / "profiles")}), \+ contextlib.redirect_stdout(out):+ code = cli.main(["serve", "--profile", str(cfg), "--plan", "--output", "json"])+ self.assertEqual(code, 0, out.getvalue())+ self.assertEqual((rec.network, rec.programs), ([], []))+ self.assertNotIn("setup", sys.modules.get("strata_cli.cli").__dict__.get("__name__", ""))++ def test_strata_install_without_the_installer_is_a_typed_error(self):+ err = io.StringIO()+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.dict(os.environ, {"STRATA_INSTALL_DIR": d}), \+ mock.patch.object(cli, "ROOT", Path(d)), contextlib.redirect_stderr(err):+ code = cli.main(["install"])+ self.assertEqual(code, 5)+ self.assertIn("installer", err.getvalue())+++if __name__ == "__main__":+ unittest.main()