Merge f-0250-tui into f-0243-rel

This commit is contained in:
Niko1221 committed 2026-10-24 15:44:30 +02:00
commit 0c53372a0e
33 files changed
+696 -68

No files matched your search

+5 -2
View File
@@ -185,8 +185,11 @@ def main() -> int:
check("profile list", r["rc"] == 0, rc=r["rc"], output=r["stdout"].strip()[:300])
r = run([*strata, "install"], env, root)
check("install refuses without an installer", r["rc"] == 5 and "no installer" in r["stderr"],
rc=r["rc"], stderr=r["stderr"].strip()[:300])
# since 0.2.4 the Terminal carries setup.py: with no keyboard it stops at the first question, in plain words and with a non-zero code
# (an older Terminal without the installer answers rc 5 "no installer")
stopped = r["rc"] not in (0, None) and ("no installer" in r["stderr"] or "setup stopped" in (r["stdout"] + r["stderr"]).lower())
check("install stops without a keyboard (or without an installer)", stopped, rc=r["rc"], stderr=r["stderr"].strip()[:300],
output=r["stdout"].strip()[-300:])
# serve on the mock engine: a fake run config (the mock never loads it), a free port, a chat answer
cfg_dir = sandbox / "cfg"
+134 -29
View File
@@ -1580,7 +1580,7 @@ def named_gpus(gpu, gpus) -> list:
return []
def cuda_choice(archs, cuda=None):
def cuda_choice(archs, cuda=None, driver=None):
"""The CUDA toolkit of one model's engine: (12 or 13, why). 13 (the ready-made engine) unless a card is older
than CUDA 13 supports (Pascal / Volta: CUDA 13 cannot compile for them) - one engine runs per model, so its oldest
card decides. `cuda` (--cuda 12|13) overrides it; setup recommends, it does not refuse (the caller warns)."""
@@ -1595,6 +1595,9 @@ def cuda_choice(archs, cuda=None):
if old:
return 12, (f"sm_{old[0]} is older than CUDA 13 supports (it dropped Pascal and Volta): this model runs the "
"experimental CUDA 12 engine")
if driver and CUDA12_MIN_DRIVER <= int(driver) < MIN_DRIVER: # #3843: a driver too old for CUDA 13 still runs the CUDA 12 engine
return 12, (f"the NVIDIA driver {driver} is older than CUDA 13 needs ({MIN_DRIVER}): this model runs the CUDA 12 engine "
f"(it works with driver {CUDA12_MIN_DRIVER} or newer; a newer driver from https://www.nvidia.com/drivers gives the CUDA 13 engine)")
return 13, None
@@ -2090,29 +2093,50 @@ def find_vcvars(cuda_v=None):
args = [str(vswhere), "-latest", "-products", "*"]
if cuda_v is not None:
upper = "19.0" if tuple(cuda_v) >= (13, 3) else "18.0"
args += ["-version", f"[16.0,{upper})"]
args += ["-version", f"[17.0,{upper})"] # 17 = Visual Studio 2022: the sources are C++20, and nvcc silently drops -std=c++20 under 2019 (#3566)
args += ["-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"]
p = out(args).strip()
v = Path(p) / "VC/Auxiliary/Build/vcvars64.bat" if p else None
return v if v and v.exists() else None
CMAKE_MIN = (3, 24) # CMakeLists.txt: cmake_minimum_required(VERSION 3.24)
def _tool_version(path, name):
"""(ok, version tuple) of `path --version`: ok False when it does not run (a pip launcher whose Python is gone)."""
try:
done = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=30)
except (OSError, subprocess.SubprocessError):
return False, ()
if done.returncode != 0:
return False, ()
found = re.search(r"(\d+)\.(\d+)(?:\.(\d+))?", done.stdout or "")
return True, tuple(int(x) for x in found.groups() if x) if found else ()
def find_tool(name):
"""A tool on PATH, or the one pip installed next to this Python (cmake, ninja). A PATH copy that does not run
(a pip launcher whose Python is gone) is skipped for the one next to this Python."""
p = shutil.which(name)
if p:
try:
if subprocess.run([p, "--version"], capture_output=True, timeout=30).returncode == 0:
return p
except (OSError, subprocess.SubprocessError):
pass
for d in (Path(sys.executable).parent / "Scripts", Path(sys.executable).parent,
Path.home() / ".local" / "bin"):
c = d / (name + (".exe" if WIN else ""))
if c.exists():
return str(c)
return None
"""The tool the build uses (cmake, ninja): the one pip installed next to THIS Python first (the virtualenv's own, #3822), then PATH,
then ~/.local/bin. One that does not run (a pip launcher whose Python is gone) is skipped, and so is a cmake older than the
one CMakeLists.txt needs while another is found; with only an older one it is returned and the build says so."""
exe = name + (".exe" if WIN else "")
candidates = [str(d / exe) for d in (Path(sys.executable).parent / "Scripts", Path(sys.executable).parent) if (d / exe).exists()]
on_path = shutil.which(name)
if on_path and on_path not in candidates:
candidates.append(on_path)
local = Path.home() / ".local" / "bin" / exe
if local.exists() and str(local) not in candidates:
candidates.append(str(local))
older = None
for c in candidates:
runs, version = _tool_version(c, name)
if not runs:
continue
if name == "cmake" and version and version[:2] < CMAKE_MIN:
older = older or c
continue
return c
return older
def free_gb(path):
@@ -2519,6 +2543,27 @@ def _piece_worker(src: _Source, st: _Pieces, todo: list, part: Path):
st.stop.set()
class StallNote:
"""A download that gets no byte for a while says so (#3567): "stalled at 69%" instead of a silent line that never moves. `check` is called
often with the bytes so far; it answers a sentence at most once a minute while nothing arrives, and None otherwise."""
AFTER = 120.0
def __init__(self, now: float = 0.0):
self.have, self.since, self.said = -1, now, 0.0
def check(self, have: int, total: int, now: float) -> str | None:
if have != self.have:
self.have, self.since, self.said = have, now, 0.0
return None
idle = now - self.since
if idle < self.AFTER or now - self.said < 60:
return None
self.said = now
return (f"no data for {int(idle // 60)} min at {100 * have // max(1, total)}%: the connection is stuck. It keeps trying; to stop, press Ctrl+C, "
"and run the same command again: the download continues where it stopped")
def parallel_download(url: str, part: Path, total: int, label: str, conns: int, name: str) -> bool:
"""Fill `part` (total bytes) over `conns` ranged connections. True when every byte is there; False when the server
does not do ranges (the caller reads the file in one stream)."""
@@ -2538,6 +2583,7 @@ def parallel_download(url: str, part: Path, total: int, label: str, conns: int,
if not part.with_name(part.name + ".chunks").is_file() and not _save_pieces(part, total, done):
return False # no piece list can be kept here: the pieces would not be told from holes
last_print = last_save = 0.0
stall = StallNote(time.time())
def report(force=False):
nonlocal last_print, last_save
@@ -2546,6 +2592,10 @@ def parallel_download(url: str, part: Path, total: int, label: str, conns: int,
last_print = now
have = st.have()
print(f"\r {label}: {have / 1e9:6.2f} / {total / 1e9:.2f} GB ({100 * have / total:.0f}%) ", end="", flush=True)
note = stall.check(have, total, now)
if note:
print()
warn(note)
if now - last_save > DL_SAVE_EVERY:
last_save = now
_save_pieces(part, total, st.snapshot())
@@ -2975,6 +3025,16 @@ def _hash_file(s: Path, size: int) -> str:
return h.hexdigest()
def own_gguf_is_whole(path: Path) -> bool:
"""The person's own GGUF reads as a whole file: its header parses and every tensor lies inside the file (a cut-short copy fails this)."""
try:
from strata_control import gguf_preflight
gguf_preflight.inspect_metadata(Path(path))
return True
except Exception: # noqa: BLE001 - anything unreadable is "not whole"
return False
def verify_sha256(s: Path, size: int, sha: str, own: bool = False, repair=None) -> None:
"""A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark,
so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again.
@@ -2984,6 +3044,11 @@ def verify_sha256(s: Path, size: int, sha: str, own: bool = False, repair=None)
if m.exists() and f"sha256 {sha}" in m.read_text(encoding="utf-8", errors="replace"):
return
have = s.stat().st_size if s.exists() else -1
if own and have > 0 and have != size and own_gguf_is_whole(s):
# a fine-tune or another build with the layout of the published file (#3777: 96 bytes apart): recommend, never refuse
warn(f"{s.name} is {have:,} bytes; the published file is {size:,}. It is a complete GGUF file, so Strata uses it as it is; "
"it may be another version or a fine-tune, so check a few answers before you rely on it")
return
if have != size:
if own: # --gguf-dir: the person's own file is never deleted by setup
fail(f"{s.name} is {have:,} bytes; the published file is {size:,}",
@@ -3000,6 +3065,10 @@ def verify_sha256(s: Path, size: int, sha: str, own: bool = False, repair=None)
else:
say(" The damaged parts could not be found this way.")
if digest != sha:
if own and own_gguf_is_whole(s):
warn(f"{s.name} is not the published file (SHA-256 {digest[:12]}..., expected {sha[:12]}...) but it is a complete GGUF file, so "
"Strata uses it as it is; it may be another version or a fine-tune, so check a few answers before you rely on it")
return
if own:
fail(f"{s.name} does not match the published file (SHA-256 {digest}, expected {sha})",
"it may be damaged or another version; your file was left as it is. Copy the whole published file into the folder")
@@ -3292,6 +3361,20 @@ def control_missing_packages() -> list:
if importlib.util.find_spec(m) is None]
def pip_stamp_is_ours(stamp: Path) -> bool:
"""The list of installed packages was written for THIS system (#3634). A .venv on a disk that Windows and Linux both start from keeps
the stamp of the other one, which then says "already installed" about packages this Python does not have. A marker beside the stamp
names the system that wrote it; an older stamp without a marker is believed only while the packages every run needs can be imported."""
marker = stamp.with_name(stamp.name + ".os")
try:
if marker.exists():
return marker.read_text(encoding="utf-8").strip() == sys.platform
except OSError:
return False
import importlib.util
return all(importlib.util.find_spec(m) is not None for m in ("numpy", "jinja2", "regex", "yaml"))
def pip_install(packages, what, extra=()):
"""pip install into .venv, skipped when the same list was installed before. An install from before the pinned
requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the
@@ -3303,7 +3386,7 @@ def pip_install(packages, what, extra=()):
ok(f"{what}: bundled with the app")
return
stamp = Path(sys.prefix) / ".strata-pip.json"
have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else []
have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() and pip_stamp_is_ours(stamp) else []
bare = {p.lower() for p in have if req_name(p) == p.lower()}
need = [p for p in packages if p not in have and req_name(p) not in bare
and not (bare and "==" in p and _installed(req_name(p)))]
@@ -3314,6 +3397,7 @@ def pip_install(packages, what, extra=()):
say(f" Installing {what} ...")
run([sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", *extra, *need])
stamp.write_text(json.dumps(sorted(set(have) | set(need)), indent=0))
stamp.with_name(stamp.name + ".os").write_text(sys.platform, encoding="utf-8")
ok(f"{what} installed")
@@ -5461,13 +5545,24 @@ def install_build_tools(gpu, yes):
return nvcc, find_vcvars(cuda_v) if WIN else None
def tool_usable(name):
"""find_tool found one that runs and (cmake) is new enough: an older system cmake counts as missing, so pip puts the right one in the venv."""
found = find_tool(name)
if found is None:
return False
if name == "cmake":
runs, version = _tool_version(found, name)
return runs and (not version or version[:2] >= CMAKE_MIN)
return True
def ensure_build_tools():
"""cmake and ninja for a local compile, installed from requirements-build.txt when missing (#3403: the Mac setup
compiles without cmake_build(), so it calls this too). Returns (cmake, ninja)."""
# 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
missing = [package for package in build_packages if find_tool(req_name(package)) is None]
missing = [package for package in build_packages if not tool_usable(req_name(package))]
if missing:
pip_install(missing, "CMake and Ninja build tools")
cmake, ninja = find_tool("cmake"), find_tool("ninja")
@@ -5486,8 +5581,9 @@ def cmake_build(src, bdir, target, defs, vcvars, bat_name):
# the same command then gets past it (issue #45); a second attempt only compiles what is still missing.
if WIN:
if vcvars is None: # #881: the build needs MSVC's environment
fail("the Visual Studio C++ build tools were not found",
"install them (Visual Studio 2019 or 2022, workload 'Desktop development with C++') and run setup again")
fail("the Visual Studio 2022 C++ build tools were not found (Visual Studio 2019 is too old: the sources are C++20)",
"install Visual Studio 2022 Build Tools (workload 'Desktop development with C++'), then run setup again; a ready-made engine "
"needs no compiler: `strata update` fetches it")
bat = ROOT / bat_name
q = lambda c: " ".join(f'"{x}"' if " " in str(x) else str(x) for x in c) # noqa: E731
bat.write_text(f'@echo off\r\ncall "{vcvars}" >nul\r\n{q(conf)} || exit /b 1\r\n{q(build)} && exit /b 0\r\n'
@@ -6704,8 +6800,15 @@ def update_install(have: list, a) -> int:
ok(f"{cfg.get('model_name', cfg_path.stem)}: up to date")
ver = engine_version(Path(json.loads(have[0].read_text(encoding="utf-8-sig"))["exe"]))
say()
start = "START-HERE.bat" if WIN else "./setup.sh"
if any(ver) and tuple(ver) < MIN_ENGINE: # #3653: the engine step failed above; "updated" would be untrue
warn(f"Strata's files are updated, but the engine was NOT: it is still {'.'.join(map(str, ver))} and this Strata wants "
f"{'.'.join(map(str, MIN_ENGINE))} or newer. The model still starts with the old engine.")
say(f" Next step: check the internet connection (and that the model window is closed), then run {'UPDATE.bat' if WIN else './update.sh'} again; "
"the line above this one says why the engine was not fetched.")
return 0
ok("Strata is updated" + (f" (engine {'.'.join(map(str, ver))})" if any(ver) else "") +
". Start the model with " + ("START-HERE.bat" if WIN else "./setup.sh") + " when you want it.")
f". Start the model with {start} when you want it.")
return 0
@@ -6975,6 +7078,7 @@ UD_FIT_MIN_SLACK_MIB = 64 # at least a few cache slots beside the estima
UD_FIT_CARD_GB = 9.5 # the check is for cards up to here
UD_FIT_RUNTIME_MIB = 250 # CUDA / HIP: the runtime's own context (the SYCL measurement above has none of it)
UD_FIT_ENGINE_RESERVE_MIB = 300 # the reserve the engine settles on when none is given and the card is tight
KV_WORDS = {"int8": "8-bit", "q4_0": "4-bit (Hadamard-rotated)", "k8v4": "8-bit keys, 4-bit values", "fp16": "16-bit"}
UD_FIT_KV_BYTES = {"fp16": 2112, "int8": 1056, "q4_0": 576, "k8v4": 816} # per token per attention layer (13)
UD_FIT_CTX_STEPS = (8192, 6144, 4608)
@@ -8245,6 +8349,9 @@ def mac_control_setup(a) -> int:
info = MF.mac_info()
ram = float(info["ram_gb"] or ram_gb())
ok(f"{info['chip']}, {ram:.0f} GB unified memory, macOS {info['macos'] or '?'}")
if info.get("rosetta_python"):
say(" (the Python that runs this is an Intel build running through Rosetta: Strata works, and the Apple Silicon Python "
"from python.org or Homebrew in /opt/homebrew is a little faster to start)")
problems = MF.mac_problems(info, need_compiler=False) # the app compiles nothing: no Command Line Tools needed
for p in problems:
warn(p)
@@ -8433,9 +8540,9 @@ def main() -> int:
ap.add_argument("--rope-scale", type=float,
help="the extension factor (default: the final context over the trained 262144, at least 1 - "
"1.5 for 384K, 2 for 512K, 1 inside the trained range)")
ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"],
ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4", "fp16"],
help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less "
"precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)")
"precise) k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell) or fp16 (16-bit, twice the memory of int8)")
ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"],
help="let the model read images (on by default where the model can; yes = the best reader for this card: the CPU "
"under 24 GB of VRAM, the GPU from 24 GB, any make; gpu / cpu = that reader; no = text only)")
@@ -8801,15 +8908,13 @@ def main() -> int:
if multi:
ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)")
ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, compute capability {cc(gpu)}, driver {gpu['driver']}")
cuda_tk, why = cuda_choice(gpu["archs"], a.cuda) # one engine per model: its oldest card decides
cuda_tk, why = cuda_choice(gpu["archs"], a.cuda, driver_major(gpu)) # one engine per model: its oldest card decides
if why:
(warn if cuda_tk == 13 or str(a.cuda) == "12" else ok)(f"CUDA {cuda_tk}: {why}")
min_driver = CUDA12_MIN_DRIVER if cuda_tk == 12 else MIN_DRIVER
if driver_major(gpu) < min_driver:
fail(f"the NVIDIA driver is too old ({gpu['driver']}; {min_driver} or newer is needed)",
"update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again" +
("" if cuda_tk == 12 else f" (or --cuda 12: the experimental CUDA 12 engine runs with driver "
f"{CUDA12_MIN_DRIVER} or newer, docs/OLDER_GPUS.md)"))
"update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again")
if gpu["vram_gb"] < 11:
warn("less than 12 GB of " + ("GPU memory (this APU's carve-out + shared memory)" if gpu.get("uma") else "VRAM")
+ ": Strata will run, but most experts stay on the CPU and it will be slow")
@@ -9104,7 +9209,7 @@ def main() -> int:
say(" documents; long-context lookups (needle tests) still pass")
kv = ["int8", "q4_0"][int(ask("KV cache?", ["1", "2"], "1", a.yes)) - 1]
if ctx > 8192:
ok(f"KV cache: {'8-bit' if kv == 'int8' else '4-bit (Hadamard-rotated)'}")
ok(f"KV cache: {KV_WORDS.get(kv, kv)}")
if MODELS[model].get("vision", fam.get("vision")) is False: # UD-IQ4_XS: images, unlike UD-Q4_K_XL
vision = "none"
if a.vision not in (None, "no", "none"):
+12
View File
@@ -413,6 +413,15 @@ def gpu_notices(s: S.LaunchSettings, comp) -> list[S.Notice]:
# ------------------------------------------------------------------------------------------------ plain-text run
def _engine_log_of(config) -> str:
"""Where this launch writes the engine's log (#3656): the config's own "log", printed so a failure can be read without a search."""
try:
from strata_cli.launch.runner import read_config
return str(read_config(Path(config)).get("log") or "")
except (OSError, ValueError, TypeError):
return ""
def _say(line: str = "") -> None:
sys.stdout.write(line + "\n")
sys.stdout.flush()
@@ -815,6 +824,9 @@ def run_launch(a: argparse.Namespace) -> int:
from strata_cli.launch import access
_say(f" {'API key':<14} {access.mask_key(result.key)} (show it: strata launch --show-key"
+ (f" --preset \"{s.name}\")" if (a.preset or a.save_preset) else ")"))
engine_log = _engine_log_of(result.config)
if engine_log:
_say(f" {'Engine log':<14} {engine_log} (follow it: strata logs --follow)")
for n in result.notices:
_say(f"[!] {n}")
local = next((u for u in result.urls if "127.0.0.1" in u), result.urls[0] if result.urls else "")
+21 -8
View File
@@ -21,7 +21,8 @@ from typing import Callable
PLACEHOLDER_KEY = "strata-local" # the tested configs' placeholder when the server has no key (not a secret)
OUTPUT_CAP = 4096 # the output cap every tested config used
COMPACT_AT = 15000 # where the tested configs make the app compact its conversation
TESTED_CONTEXT = 32768 # the window every config below was tested on
COMPACT_AT = 15000 # and where those tested configs make the app compact its conversation
@dataclass
@@ -42,6 +43,17 @@ class Target:
return max(1024, self.context - OUTPUT_CAP)
def compact_at(t: Target) -> int:
"""Where the app should compact its conversation: the share of the input limit the tested configs used, so that the
summarising request (which carries the whole conversation) still fits the window.
A flat 15,000 summarises a wider server every 15,000 tokens - 6% of a 256K window - while the tested configs compact
a 32K server at 52% of its input limit. The share is what carries over, not the number: a 32K server keeps exactly
the value it was tested at."""
tested_limit = TESTED_CONTEXT - OUTPUT_CAP
return max(COMPACT_AT, int(t.input_limit * COMPACT_AT / tested_limit))
@dataclass
class FileSpec:
path: str # may start with ~
@@ -80,7 +92,7 @@ def _j(obj) -> str:
def opencode_file(t: Target) -> str:
return _j({"$schema": "https://opencode.ai/config.json", "model": f"strata/{t.model}", "small_model": f"strata/{t.model}",
"autoupdate": False,
"compaction": {"auto": True, "buffer": max(1024, t.input_limit - COMPACT_AT)},
"compaction": {"auto": True, "buffer": max(1024, t.input_limit - compact_at(t))},
"share": "disabled",
"provider": {"strata": {"npm": "@ai-sdk/openai-compatible", "name": "Strata (local)",
"options": {"baseURL": t.base, "apiKey": t.key},
@@ -90,7 +102,7 @@ def opencode_file(t: Target) -> str:
def codex_file(t: Target) -> str:
return (f'model = "{t.model}"\nmodel_provider = "strata"\nmodel_context_window = {t.context}\n'
f"model_auto_compact_token_limit = {COMPACT_AT}\nmodel_reasoning_summary = \"auto\"\napproval_policy = \"never\"\n"
f"model_auto_compact_token_limit = {compact_at(t)}\nmodel_reasoning_summary = \"auto\"\napproval_policy = \"never\"\n"
'sandbox_mode = "workspace-write"\ncheck_for_update_on_startup = false\n\n[model_providers.strata]\n'
f'name = "Strata (local)"\nbase_url = "{t.base}"\nwire_api = "responses"\nenv_key = "STRATA_API_KEY"\n'
"stream_idle_timeout_ms = 600000\n")
@@ -118,7 +130,7 @@ def omp_models(t: Target) -> str:
def omp_config(t: Target) -> str:
return ("modelRoles:\n default: strata/" + t.model + "\ndefaultThinkingLevel: medium\ncompaction:\n enabled: true\n thresholdTokens: "
+ str(COMPACT_AT) + "\n keepRecentTokens: 4000\n methodOrder:\n - soft\n idleEnabled: false\nsetupVersion: 2\n")
+ str(compact_at(t)) + "\n keepRecentTokens: 4000\n methodOrder:\n - soft\n idleEnabled: false\nsetupVersion: 2\n")
def pi_models(t: Target) -> str:
@@ -131,12 +143,12 @@ def pi_models(t: Target) -> str:
def pi_settings(t: Target) -> str:
return _j({"defaultProvider": "strata", "defaultModel": t.model, "defaultThinkingLevel": "medium",
"compaction": {"enabled": True, "reserveTokens": max(1024, t.context - COMPACT_AT), "keepRecentTokens": 4000}})
"compaction": {"enabled": True, "reserveTokens": max(1024, t.context - compact_at(t)), "keepRecentTokens": 4000}})
def hermes_file(t: Target) -> str:
return ("model:\n default: " + t.model + "\n provider: lmstudio\n base_url: " + t.base + "\n context_length: " + str(t.context) +
"\ncompression:\n enabled: true\n threshold_tokens: " + str(COMPACT_AT) + "\nauxiliary:\n compression:\n context_length: 65536\n")
"\ncompression:\n enabled: true\n threshold_tokens: " + str(compact_at(t)) + "\nauxiliary:\n compression:\n context_length: 65536\n")
def openclaw_file(t: Target) -> str:
@@ -181,14 +193,15 @@ def _limits_omp(t: Target) -> list[str]:
def _limits_pi(t: Target) -> list[str]:
return ["pi has the smallest prompt of the eight (1.5K tokens): the most room for the conversation.",
"It compacts after the turn that crosses the line, so one turn can reach about 15K tokens before it summarises."]
"It compacts after the turn that crosses the line, so one turn can reach about %dK tokens before it summarises."
% round(compact_at(t) / 1000)]
def _limits_hermes(t: Target) -> list[str]:
out = ["Hermes refuses a window under 64,000 tokens unless the provider is lmstudio with an explicit context_length: the config uses "
"that, and auxiliary.compression.context_length 65536 for its summariser (the same floor).",
"Its system prompt and 20 tools take about 12.9K tokens (40% of a 32K window): about 19K is left for the conversation.",
"Its compaction threshold is floored at its own 64K minimum, so it compacts later than 15K (around 20K); it still fits 32K."]
"Its own 64K minimum floors the compaction threshold, so it compacts later than the value above (around 20K on a 32K window); it still fits 32K."]
if t.context < 65536:
out.insert(0, "WARNING: Hermes is built for 64K or more. At %dK it works only through the workaround above." % (t.context // 1024))
return out
+54 -3
View File
@@ -77,6 +77,30 @@ def python_failure(lines: list[str]) -> str | None:
return None
DEEPSEEK_ENGINE_LINE = re.compile(r"(A newer DeepSeek engine (?:is available|may be available)[^\r\n]*|DeepSeek engine updated from [^\r\n]*)")
def deepseek_engine_note(line: str) -> tuple[str, str] | None:
"""setup's line about the DeepSeek engine upgrade ("A newer DeepSeek engine is available but could not be installed: ...; still using X",
or "DeepSeek engine updated from X to Y"): ("warn" | "info", the sentence), None for any other line. The failure line must reach the
person: the model starts with the engine they have, and they should know there is a newer one."""
found = DEEPSEEK_ENGINE_LINE.search(line)
if not found:
return None
text = found.group(1).strip()
return ("info" if text.startswith("DeepSeek engine updated") else "warn", text)
def argparse_failure(lines: list[str]) -> str:
"""setup.py's own refusal of an option ("setup.py: error: argument --kv: invalid choice: ..."), which is neither an [X] line nor a
traceback (#3785): the words after "error:" are the cause."""
for line in reversed(lines):
found = re.match(r"\s*(?:setup|strata)(?:\.py)?: error: (.+)", line)
if found:
return found.group(1).strip()[:300]
return ""
def missing_file(failure: str) -> bool:
"""An import or file error: the install itself is short of a file, which an update of Strata brings back."""
return failure.startswith(("ModuleNotFoundError", "ImportError", "FileNotFoundError"))
@@ -99,6 +123,7 @@ def setup_failure(lines: list[str], err: str, hint: str, details: str | None, ow
"""The error for a setup.py run that exited non-zero. setup.py's own `[X]` line (err) is the message when there is one; when it
stopped with a Python error instead, that error's last line is (#3613, #3467: a file missing from the Terminal's tools/ ended every
launch after a tune with only "The model could not be installed"). `details` is the file that holds the rest of its output."""
err = err or argparse_failure(lines)
crashed = python_failure(lines) if not err else None
if crashed:
where = f" The whole setup output is in {details}." if details else ""
@@ -216,6 +241,11 @@ def tune_words(result: dict | None, code: int | None = None) -> tuple[str, str]:
# ----------------------------------------------------------------------------------------------- run config
def runtime_max_wait() -> int:
from strata_control import runtime
return int(runtime.MAX_START_WAIT)
def read_config(path: Path) -> dict:
return json.loads(Path(path).read_text(encoding="utf-8-sig"))
@@ -482,6 +512,7 @@ class Runner:
self.hardware_override = hardware
self.children: list[subprocess.Popen] = []
self.notices: list[str] = []
self._engine_notes: set[str] = set()
self.identity_notes: list[str] = []
self.tune_result: dict | None = None
self.config_path: Path | None = None
@@ -872,6 +903,17 @@ class Runner:
except Exception: # noqa: BLE001
return 0.0
def start_wait(self) -> int:
"""How long the start waits for the model to be ready (#3949 #3459): 10 minutes, more for a big model, which a slow disk needs
longer to read (about 8 more seconds per GB above 40 GB, at most 30 minutes). Automatic: nobody sets a variable for it."""
gb = 0.0
try:
row = next((r for r in self.catalog.rows() if r.family == self.s.family and r.model == self.s.model), None)
gb = float(getattr(row, "download_gb", 0) or 0)
except Exception: # noqa: BLE001
gb = 0.0
return int(min(runtime_max_wait(), max(600, 600 + (gb - 40.0) * 8.0)))
def download_question(self) -> tuple[str, str]:
"""(title, text) of the question before a download starts, naming exactly what is fetched."""
return self.model_state().question()
@@ -976,6 +1018,12 @@ class Runner:
continue
lines.append(line)
lines[:] = lines[-1500:]
note = deepseek_engine_note(line)
if note and note[1] not in self._engine_notes: # setup's DeepSeek engine lines are shown, not condensed away (0.2.5 list)
self._engine_notes.add(note[1])
if note[0] == "warn":
self.notices.append(note[1])
self.emit("model", note[1], None, level=note[0], step=step_seen)
prog = cat.mcp.install_progress(lines)
prog = cat.mcp.combined_progress(prog, job)
dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label")
@@ -1238,6 +1286,9 @@ class Runner:
cfg = derive_config(base, self.s, bool_flags=tune_knobs.BOOL_FLAGS,
log=str(launch_dir() / f"{self.name}.engine.log"), gpus=cards_for_launch(self.s, self.catalog, base=base))
self.use_own_dsv41_engine(cfg)
wait = self.start_wait()
if wait > 600 and not cfg.get("engine_ready_s"): # the server's own wait for the engine (900 s) must not end before the start's
cfg["engine_ready_s"] = wait + 60
out = launch_dir() / f"{self.name}.json"
write_private(out, cfg)
self.config_path = out
@@ -1334,12 +1385,12 @@ class Runner:
if s.tuned_preset:
try:
presets.find(s.tuned_preset)
self.emit("tune", "This preset is already tuned for this computer.", 100)
self.emit("tune", "This preset is already tuned for this computer. Add --retune to measure again.", 100)
return
except presets.PresetError:
pass
elif s.tuned_at: # measured before: the standard settings were already the fastest, nothing was saved
self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do.", 100)
self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do; add --retune to measure again.", 100)
return
stored = self.stored_tuning()
if stored: # the same model and choices were tuned on this computer before (a run by flags, no preset)
@@ -1577,7 +1628,7 @@ class Runner:
def go() -> None:
try:
box["r"] = runtime.start(name, wait=600)
box["r"] = runtime.start(name, wait=self.start_wait())
except Exception as e: # noqa: BLE001
box["e"] = e
finally:
+8 -3
View File
@@ -387,7 +387,7 @@ class ModelScreen(Base):
w = self.width()
if w >= 100:
return [("Model", 42), ("Download", 10), ("Needs (RAM + VRAM)", 20), ("On this computer", 0)]
return [("Model", 41), ("Download", 9), ("Needs (RAM+VRAM)", 17), ("On this computer", 0)]
return [("Model", 41), ("Size", 8), ("Needs", 7), ("Fits?", 0)] # 80 columns: the verdict column keeps room (the long words are below the list)
def build_menu(self, initial: bool = False) -> None:
s = self.ctx.settings
@@ -402,7 +402,11 @@ class ModelScreen(Base):
tag = (" (recommended)" if r.recommended else "") + (" (installed)" if r.installed else "") + (" [experimental]" if r.experimental else "")
need = f"{r.memory_gb:.0f} GB" if r.memory_gb else "-"
ssd = f" · SSD {r.spill_gb:.0f} GB" if r.spill_gb >= 1 else ""
items.append(Item([r.title, f"{r.download_gb:.0f} GB", need, Cell((r.words.split(",")[0].split(":")[0] if ssd and "SSD" in r.words else r.words) + ssd + tag, col)], key=(r.family, r.model)))
verdict = (r.words.split(",")[0].split(":")[0] if ssd and "SSD" in r.words else r.words) + ssd + tag
if self.width() < 100: # a short verdict that fits the column; the full sentence is shown under the list
extra = " (recommended)" if r.recommended else " (installed)" if r.installed else " [experimental]" if r.experimental else ""
verdict = {"fits": "fits", "tight": "tight", "no": "too big"}[r.verdict] + extra
items.append(Item([r.title, f"{r.download_gb:.0f} GB", need, Cell(verdict, col)], key=(r.family, r.model)))
if (s.family, s.model) == (r.family, r.model):
sel = i
m = self.query_one(Menu)
@@ -1328,7 +1332,8 @@ class AccessScreen(Base):
step_id = "access"
hints = "↑↓ choose Enter next p port k new key t key on/off Esc back ? help"
help_text = ("Who can use the model. 'This computer only' is the safe default and never needs a key. Beyond it Strata makes an API key "
"for you (recommended); press t if you would rather have no key: it still starts, but anyone who can reach it can use it.")
"for you (recommended); press t if you would rather have no key: it still starts, but anyone who can reach it can use it. "
"To see the key later: strata launch --show-key. To use a key of your own: strata launch --api-key YOUR-KEY (or --api-key-env NAME).")
BINDINGS = Base.BINDINGS + [Binding("p", "port", show=False), Binding("k", "newkey", show=False), Binding("t", "keytoggle", show=False)]
+9 -1
View File
@@ -627,7 +627,15 @@ def windows_display_adapters() -> list[dict]:
"""The display adapters Windows has a driver for: the display-class registry key (readable without admin and without running
anything), then Win32_VideoController when the key lists nothing: {"vendor": "10de"|"1002"|"8086"|..., "device": int, "name",
"vram_gb"}. Empty off Windows or when neither can be read."""
return _windows_display_adapters_registry() or _windows_adapters_cim()
found = _windows_display_adapters_registry()
if len({a.get("vendor") for a in found} & {"10de", "1002"}) > 1:
# The registry keeps the driver entry of a card that was taken out (an NVIDIA card swapped for a Radeon, #3892): when two makes are
# listed, only the adapters Windows reports as present now count.
present = {(a["vendor"], a["device"]) for a in _windows_adapters_cim()}
now = [a for a in found if (a["vendor"], a["device"]) in present]
if now:
return now
return found or _windows_adapters_cim()
def _windows_display_adapters_registry() -> list[dict]:
+8
View File
@@ -413,6 +413,14 @@ def select_engine(packages, hardware: dict) -> tuple[EnginePackage | None, list[
return None, reasons
best = max(fitting, key=lambda p: (version_key(p.version), ec._version_key(p.min_driver.get("nvidia", "0")),
ec.hip_preference(p.archs) if p.backend == "hip" else 1))
kept = str(hardware.get("installed_variant") or "")
if best.backend == "cuda" and kept and best.variant != kept:
# An update never switches the CUDA build (#3835): a model on the CUDA 12 engine (its card is one CUDA 13 has no code for) must not
# be given CUDA 13 because ANOTHER card in the PC fits it. The same version of the build that runs here is kept when the feed has it.
same = [p for p in fitting if p.backend == "cuda" and p.variant == kept and version_key(p.version) == version_key(best.version)]
if same:
reasons.append(f"the installed {kept} build is kept; {best.variant} would also fit another card in this PC")
best = same[0]
return best, reasons
+5 -1
View File
@@ -94,7 +94,11 @@ def mac_info(run=subprocess.run) -> dict:
clt_path = clt.stdout.strip() if clt.returncode == 0 else ""
except (OSError, subprocess.SubprocessError):
clt_path = ""
return {"chip": chip, "ram_gb": ram, "macos": ver, "arm64": platform.machine() == "arm64",
# platform.machine() is the PYTHON's build: an Intel Python running through Rosetta says x86_64 on an M1 Max (#3894). The chip name
# (Rosetta passes "Apple M1 Max" through) and hw.optional.arm64 say what the Mac is.
python_arm = platform.machine() == "arm64"
mac_arm = python_arm or _sysctl("hw.optional.arm64", run) == "1" or chip.startswith("Apple")
return {"chip": chip, "ram_gb": ram, "macos": ver, "arm64": mac_arm, "rosetta_python": mac_arm and not python_arm,
"clt": clt_path, "perf_cores": int(_sysctl("hw.perflevel0.physicalcpu", run) or 0)}
+32
View File
@@ -294,6 +294,33 @@ def _candidate_by_header(shards: list[Path], tensors: int, payload: int, experts
return None
def _candidate_by_layout(shards: list[Path], tensors: int, payload: int, experts: set[str]) -> dict | None:
"""A qwen4exp file set that is no build Strata has tested (a fine-tune, a K-quant mix from another maker) but has the layout of one
(#3651 #3777): the closest row by expert formats, then by size. Strata uses the files as that model and says so; it never refuses a
working file for not being on the list (recommend, never force)."""
try:
catalog = json.loads((ROOT / "data" / "gguf_fingerprints.json").read_text(encoding="utf-8"))
except (OSError, UnicodeError, ValueError):
return None
best = None
for selection in sorted(SUPPORTED_SELECTIONS):
row = catalog.get(selection) if isinstance(catalog, dict) else None
if not isinstance(row, dict) or row.get("tensors") != tensors or not isinstance(row.get("expert_bytes"), dict):
continue
have = set(row["expert_bytes"])
union = have | experts
score = (len(have & experts) / len(union)) if union else 0.0
key = (-score, abs(int(row.get("bytes") or 0) - payload), selection)
if score > 0 and (best is None or key < best[0]):
best = (key, selection, have)
if best is None:
return None
family, model = best[1].split("/", 1)
return {"family": family, "model": model, "basis": "same_layout_other_build",
"expected_expert_types": sorted(best[2] | experts), "expected_tensor_count": tensors,
"setup_args_hint": ["--family", family, "--model", model, "--gguf-dir", str(shards[0].parent)]}
def _already_set_up(shards: list[Path], candidate: dict | None) -> dict | None:
"""Is this model already installed (a run config of any known install names the file) and what was prepared beside it (pack, draft
layer, picture reader)? Read-only; None when the file set is not one Strata knows."""
@@ -709,6 +736,11 @@ def plan_import(raw_path: str) -> dict:
candidate = _candidate_selection(shards)
if candidate is None and metadata is not None and not issues:
candidate = _candidate_by_header(shards, observed_tensor_count, observed_payload, observed_experts)
if candidate is None:
candidate = _candidate_by_layout(shards, observed_tensor_count, observed_payload, observed_experts)
if candidate is not None:
messages.append(f"These files are not exactly a build Strata has tested; they have the layout of {candidate['family']} "
f"{candidate['model']}, so Strata uses them as that model. Check a few answers before you rely on them.")
if "multiple_model_groups" in issues:
candidate = None # nothing is chosen for the person
if candidate is None and not {"multiple_model_groups", "incomplete_or_invalid_shard_set"} & set(issues):
+9 -6
View File
@@ -515,6 +515,9 @@ def _check_start_candidate(name: str, expected_profile_revision: str | None,
return plan, digest
MAX_START_WAIT = 1800 # seconds a start may wait for the model: a 250 GB DeepSeek set on a slow disk needs more than 10 minutes (#3949)
def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30,
expected_profile_revision: str | None = None,
expected_source_sha256: str | None = None,
@@ -535,8 +538,8 @@ def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30,
if token is None:
raise ProfileError("the process to follow with --die-with-pid is not running")
die_with = (die_with_pid, token)
if not 0 <= wait <= 600 or not 0 <= shutdown_timeout <= 300:
raise ProfileError("start wait must be 0..600 and shutdown timeout 0..300 seconds")
if not 0 <= wait <= MAX_START_WAIT or not 0 <= shutdown_timeout <= 300:
raise ProfileError(f"start wait must be 0..{MAX_START_WAIT} and shutdown timeout 0..300 seconds")
if expected_profile_revision is not None and (not isinstance(expected_profile_revision, str) or
not re.fullmatch(r"[0-9a-f]{16}", expected_profile_revision)):
raise ProfileError("expected profile revision must be 16 lowercase hex characters")
@@ -706,9 +709,9 @@ def restart(name: str, *, timeout: float = 1000, startup_wait: float = 300,
allow_source_switch: bool = False,
allow_source_migration: bool = False,
expected_source_sha256: str | None = None) -> dict:
if (not 1 <= timeout <= 1800 or not 1 <= startup_wait <= 600 or
if (not 1 <= timeout <= 1800 or not 1 <= startup_wait <= MAX_START_WAIT or
type(allow_source_switch) is not bool or type(allow_source_migration) is not bool):
raise ProfileError("restart wait must be 1..1800 and startup wait 1..600 seconds")
raise ProfileError(f"restart wait must be 1..1800 and startup wait 1..{MAX_START_WAIT} seconds")
if expected_source_sha256 is not None and (not isinstance(expected_source_sha256, str) or
not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)):
raise ProfileError("expected source SHA-256 must be 64 lowercase hex characters")
@@ -1224,7 +1227,7 @@ class Host:
return {**result, "profile": self.name}
if command == "restart":
startup_wait = request.get("startup_wait", 300)
if type(startup_wait) not in (int, float) or not 1 <= startup_wait <= 600:
if type(startup_wait) not in (int, float) or not 1 <= startup_wait <= MAX_START_WAIT:
return {"ok": False, "error": "invalid_startup_wait", "exit_code": 2}
revision = request.get("expected_profile_revision")
if revision is not None and (not isinstance(revision, str) or
@@ -1368,7 +1371,7 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--die-with-pid", type=int)
parser.add_argument("--die-with-token")
args = parser.parse_args(argv)
if not 0 <= args.shutdown_timeout <= 300 or not 1 <= args.startup_wait <= 600:
if not 0 <= args.shutdown_timeout <= 300 or not 1 <= args.startup_wait <= MAX_START_WAIT:
parser.error("shutdown timeout must be 0..300")
if args.expected_profile_revision is not None and not re.fullmatch(r"[0-9a-f]{16}", args.expected_profile_revision):
parser.error("expected profile revision must be 16 lowercase hex characters")
+33 -1
View File
@@ -571,7 +571,7 @@ def _choose_engine(feed: feedmod.Feed, ctx: Context, state: State) -> tuple[dict
"download_bytes": 0, "previous": state.section("engine").get("previous"), "pinned": state.section("engine").get("pinned"),
"problem": None}, None
installed, missing_reason = installed_engine(ctx.components, ctx.hardware)
sticky = {**ctx.hardware, "installed_variant": installed.variant if installed is not None and installed.backend == "hip" else ""}
sticky = {**ctx.hardware, "installed_variant": installed.variant if installed is not None and installed.backend in ("hip", "cuda") else ""}
offered, reasons = feedmod.select_engine([p for p in feed.engine], sticky)
section = state.section("engine")
report = {"installed": _engine_view(installed), "offered": offered.to_dict() if offered else None,
@@ -839,6 +839,36 @@ def _test_start_failure(component: ec.EngineComponent, started: dict, ctx: Conte
return TestStartFailed(component.version, f"it did not answer a one-token probe ({error or started.get('state')}){tail}")
TEST_CONTEXT = 4096
_TEST_DROP_WITH_VALUE = ("--kv-resident", "--vision-tokens")
_TEST_DROP_FLAGS = ("--vision",)
def light_test_args(args: list) -> list:
"""The saved model's engine options made light for the test start (#3842): a short context, no KV kept in VRAM and no picture reader. The
test asks whether the NEW engine loads and answers one token, not whether this card holds the model's 262,144-token settings next to the
desktop and the running model; a 16 GB card refused good engines with 'out of memory' at the first weight upload."""
out, i = [], 0
values = [str(x) for x in args]
while i < len(values):
item = values[i]
nxt = values[i + 1] if i + 1 < len(values) else None
if item == "--max-context" and nxt is not None:
try:
out += [item, str(min(int(nxt), TEST_CONTEXT))]
except ValueError:
out += [item, nxt]
i += 2
elif item in _TEST_DROP_WITH_VALUE and nxt is not None:
i += 2
elif item in _TEST_DROP_FLAGS:
i += 2 if nxt is not None and not nxt.startswith("--") else 1
else:
out.append(item)
i += 1
return out
def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Context) -> dict:
"""Start the staged engine through the real start path (owner runtime, `component:strata-engine`, a saved model), wait for
the one-token generation probe, and stop it. Everything runs in an isolated runtime, profile and component folder, so a
@@ -855,6 +885,8 @@ def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Con
cfg["exe"] = ec.REFERENCE_PREFIX + ec.COMPONENT_ID
cfg["backend"] = component.backend
cfg.pop("lib_dirs", None)
if isinstance(cfg.get("args"), list):
cfg["args"] = light_test_args(cfg["args"])
cfg["host"] = "127.0.0.1"
cfg["port"] = _free_port()
cfg["log"] = str(sandbox / "engine.log")
+19
View File
@@ -229,6 +229,25 @@ class GuiLayout(unittest.TestCase):
self.assertEqual(plan["candidate_selection"]["model"], "Gyro-S")
self.assertEqual(payload, 124)
def test_a_fine_tune_with_the_layout_of_a_known_build_is_used_not_refused(self): # #3651 #3777
folder = self.base / "finetune"
folder.mkdir()
(folder / "Qwen3.8-Flash-Next-Gyro-S-abliterated-TQ1_0.gguf").write_bytes(gyro_s_bytes())
fake_root = self.base / "fake-root2"
(fake_root / "data").mkdir(parents=True)
table = {"gyro/Gyro-S": {"arch": "qwen4exp", "tensors": 2, "bytes": 999_999, "expert_bytes": {"TQK6": 52, "TQK7": 60},
"files": [GYRO_S], "repo": "x"},
"gyro/Gyro-M": {"arch": "qwen4exp", "tensors": 2, "bytes": 888_888, "expert_bytes": {"TQ2_T": 40},
"files": [GYRO_S], "repo": "x"}}
(fake_root / "data" / "gguf_fingerprints.json").write_text(json.dumps(table))
with mock.patch.object(models, "ROOT", fake_root):
plan = models.plan_import(str(folder))
self.assertEqual(plan["issues"], [])
self.assertEqual(plan["candidate_selection"]["basis"], "same_layout_other_build")
self.assertEqual(plan["candidate_selection"]["model"], "Gyro-S") # the closest by expert formats
self.assertTrue(any("not exactly a build Strata has tested" in m for m in plan["messages"]))
self.assertIn("unrecognized_or_unsupported_model_variant", models.plan_import(str(folder))["issues"]) # the real table has 1224 tensors
# ---- T05: where it is, what is missing
def test_the_folder_defaults_to_where_the_model_is(self):
cat = self.catalog()
+14
View File
@@ -159,5 +159,19 @@ class LaunchChoice(unittest.TestCase):
self.assertEqual(self.runner().upgrade_dsv41_engine(found), new)
class SetupPathLines(unittest.TestCase):
"""The upgrade lines setup prints are shown by strata launch, the failure one especially (0.2.5 list)."""
def test_the_failure_line_is_a_warning_and_the_success_line_is_news(self):
from strata_cli.launch.runner import deepseek_engine_note
bad = deepseek_engine_note(" A newer DeepSeek engine is available but could not be installed: no space left; still using 0.1.49.")
self.assertEqual(bad[0], "warn")
self.assertTrue(bad[1].endswith("still using 0.1.49."))
self.assertEqual(deepseek_engine_note("[!] A newer DeepSeek engine may be available but could not be checked (OSError); still using 0.1.49.")[0], "warn")
good = deepseek_engine_note(" DeepSeek engine updated from 0.1.49 to 0.1.49.2.")
self.assertEqual(good, ("info", "DeepSeek engine updated from 0.1.49 to 0.1.49.2."))
self.assertIsNone(deepseek_engine_note(" checking model.gguf (SHA-256, 5 GB) ..."))
if __name__ == "__main__":
unittest.main()
+10
View File
@@ -258,6 +258,16 @@ class WindowsAmd(unittest.TestCase):
{"vendor": "1002", "device": 0x744C, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 24.0}]
IGPU_ONLY = [{"vendor": "1002", "device": 0x15BF, "name": "AMD Radeon 780M Graphics", "vram_gb": 0.5}]
def test_a_removed_nvidia_card_left_in_the_registry_does_not_win(self): # #3892
old = {"vendor": "10de", "device": 0x2684, "name": "NVIDIA GeForce RTX 4090", "vram_gb": 24.0}
new = self.TESTER_A[0]
with mock.patch.object(ec, "_windows_display_adapters_registry", return_value=[old, new]), mock.patch.object(ec, "_windows_adapters_cim", return_value=[dict(new)]):
self.assertEqual(ec._windows_vendor_backend(), "hip")
with mock.patch.object(ec, "_windows_display_adapters_registry", return_value=[old, new]), mock.patch.object(ec, "_windows_adapters_cim", return_value=[dict(old), dict(new)]):
self.assertEqual(ec._windows_vendor_backend(), "cuda") # both really there: NVIDIA first, as before
with mock.patch.object(ec, "_windows_display_adapters_registry", return_value=[old, new]), mock.patch.object(ec, "_windows_adapters_cim", return_value=[]):
self.assertEqual(ec._windows_vendor_backend(), "cuda") # Windows could not say: nothing is dropped
def test_nvidia_wins_and_an_integrated_radeon_is_not_a_card(self):
self.assertEqual(ec._windows_vendor_backend(self.OWNER_PC), "cuda")
self.assertEqual(ec.windows_amd_cards(self.OWNER_PC), [])
+13
View File
@@ -357,6 +357,18 @@ class StoredTuning(Base):
seen, started = self.run_tune(self.runner_for_tune())
self.assertTrue(started)
def test_a_big_model_gets_a_longer_start_wait_by_itself(self): # #3949 #3459
r = self.runner_for_tune()
row = type("Row", (), {"family": r.s.family, "model": r.s.model, "download_gb": 20.0})
with mock.patch.object(r.catalog, "rows", return_value=[row]):
self.assertEqual(r.start_wait(), 600) # a small model keeps ten minutes
row.download_gb = 250.0
with mock.patch.object(r.catalog, "rows", return_value=[row]):
self.assertEqual(r.start_wait(), 1800) # 600 + 210 x 8, capped at 30 minutes
row.download_gb = 83.0
with mock.patch.object(r.catalog, "rows", return_value=[row]):
self.assertEqual(r.start_wait(), 944)
def test_a_stored_result_is_used_and_said(self):
saved = self.store()
r = self.runner_for_tune()
@@ -364,6 +376,7 @@ class StoredTuning(Base):
self.assertFalse(started)
text = seen[-1]
self.assertIn("already tuned for this computer", text)
self.assertIn("Add --retune to measure again", text)
self.assertIn("Q2 32K - Full speed", text)
self.assertIn("--retune", text)
self.assertEqual(r.s.tuned_preset, saved["id"])
+1 -1
View File
@@ -84,7 +84,7 @@ class Issue3403MacBuildTools(unittest.TestCase):
for p in packages:
installed[p.split("==")[0]] = "/venv/bin/" + p.split("==")[0]
with mock.patch.object(setup, "find_tool", side_effect=find), mock.patch.object(setup, "pip_install", side_effect=pip) as pi:
with mock.patch.object(setup, "find_tool", side_effect=find), mock.patch.object(setup, "pip_install", side_effect=pip) as pi, mock.patch.object(setup, "_tool_version", return_value=(True, (3, 31, 0))):
self.assertEqual(setup.ensure_build_tools(), ("/venv/bin/cmake", "/venv/bin/ninja"))
self.assertEqual(pi.call_count, 1)
setup.ensure_build_tools() # present now: nothing more is installed
+31 -1
View File
@@ -952,6 +952,24 @@ class FlagsCommand(unittest.TestCase):
self.assertIn("Nothing was changed.", out)
self.assertEqual(store.list_presets(), [])
def test_the_access_help_names_the_flags_for_showing_and_setting_a_key(self): # #3713 #3951
from strata_cli.launch import screens
self.assertIn("strata launch --show-key", screens.AccessScreen.help_text)
self.assertIn("--api-key YOUR-KEY", screens.AccessScreen.help_text)
def test_the_summary_says_where_the_engine_log_is(self): # #3656
import tempfile
with tempfile.TemporaryDirectory() as d:
cfg = Path(d) / "x.json"
cfg.write_text(json.dumps({"log": str(Path(d) / "office.engine.log"), "args": []}), encoding="utf-8")
fake = Result(profile="launch-office", urls=["http://127.0.0.1:8080"], key=None, tune_word=None, notices=[], config=str(cfg))
with mock.patch.object(Runner, "run", return_value=fake):
code, out, err = run_cli(["launch", "--no-tui", "--model", "q2_0"])
self.assertEqual(code, 0, err)
self.assertIn("Engine log", out)
self.assertIn("office.engine.log", out)
self.assertIn("strata logs --follow", out)
def test_run_without_screens_prints_the_address_and_saves_the_preset(self):
fake = Result(profile="launch-office", urls=["http://127.0.0.1:8080", "http://192.168.1.5:8080"], key="sk-strata-abcdefghijkl",
tune_word=None, notices=[], config="/x")
@@ -1236,7 +1254,19 @@ class ConnectCommand(unittest.TestCase):
def test_context_flag_reaches_the_config(self):
code, out, _ = run_cli(["connect", "pi", "--url", "http://127.0.0.1:8080", "--context", "64k", "--show-key"])
self.assertIn('"contextWindow": 65536', out)
self.assertIn('"reserveTokens": 50536', out)
self.assertIn('"reserveTokens": 33394', out) # 65536 - 32142: the tested 52.3% share, not a flat 15K
def test_the_compaction_point_scales_with_the_window(self):
"""A wider server must not be summarised every 15,000 tokens: the share the tested 32K configs used carries over."""
wide = harness.target("http://127.0.0.1:18900", None, "qwen3.8-flash-next-q2_0", 262144)
self.assertEqual(harness.compact_at(wide), 135000) # 52.3% of the 258048 input limit
cfg = json.loads(self.render("opencode", context=262144)["files"][0]["text"])
self.assertEqual(wide.input_limit - cfg["compaction"]["buffer"], 135000)
self.assertIn("model_auto_compact_token_limit = 135000", self.render("codex", context=262144)["files"][0]["text"])
self.assertIn("thresholdTokens: 135000", self.render("omp", context=262144)["files"][1]["text"])
# the window every config was tested on keeps exactly the value it was tested at
tested = harness.target("http://127.0.0.1:18900", None, "qwen3.8-flash-next-q2_0", 32768)
self.assertEqual(harness.compact_at(tested), 15000)
class GpuRolesFlag(unittest.TestCase):
+10 -2
View File
@@ -24,6 +24,14 @@ UNUSABLE = {"usable": False, "engine": None, "notice": "No engine for this PC wa
"The app never downloads an engine while it starts or serves."}
def qwen_catalog():
"""A catalog stand-in for a Qwen model: since 0.2.4 the runner asks it whether the family is DeepSeek (which has its own engine and skips this step);
a bare Mock answers yes to everything."""
cat = mock.Mock()
cat.strata.multi_family.return_value = False
return cat
class FakeProc:
def __init__(self, events: list[dict], code: int = 0):
self.stdout = iter(json.dumps(e) + "\n" for e in events)
@@ -42,7 +50,7 @@ def update_events(status: str, note: str = "", code: int = 0) -> list[dict]:
def runner(spawned: list) -> Runner:
r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=mock.Mock(), emit=lambda e: None)
r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=qwen_catalog(), emit=lambda e: None)
r.check_cancel = lambda: None
return r
@@ -58,7 +66,7 @@ class EngineBeforeModel(unittest.TestCase):
"""ensure_engine() like run_ensure, returning (spawns, error or None, the runner with .events)."""
spawns: list = []
seen: list = []
r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=mock.Mock(), emit=seen.append,
r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=qwen_catalog(), emit=seen.append,
confirm=confirm, assume_yes=assume_yes)
r.events = seen
r.check_cancel = lambda: None
+18
View File
@@ -236,6 +236,24 @@ class ModelStep(Base):
self.assertIn("The n-gram table stays on your SSD", t)
self.run_app(case)
def test_the_verdict_column_is_not_cut_off_at_80_columns(self): # 0.2.5 list
ctx = make_ctx()
app = LaunchApp(ctx)
async def go():
async with app.run_test(size=(80, 34)) as pilot:
await pilot.pause(0.2)
await press(pilot, "enter")
t = text_of(app)
self.assertIn("Fits?", t)
rec = next(l for l in t.splitlines() if "Qwen3.8-Flash-Next IQ3_S " in l)
self.assertIn("fits (recommended)", rec)
for model in ("Q2_0", "NVFP4 ", "UD-Q5_K_XL"):
row = next(l for l in t.splitlines() if model in l and "GB" in l)
self.assertTrue(any(w in row for w in ("fits", "tight", "too big")), row)
self.assertTrue(all(len(l) <= 80 for l in t.splitlines()))
asyncio.run(go())
def test_choosing_a_model_and_going_on(self):
async def case(app, pilot, ctx):
await press(pilot, "enter", "up", "up", "up", "enter")
+31 -1
View File
@@ -48,6 +48,8 @@ NETWORK_ALLOWED = {
("strata_control/tune_session.py", "urlopen"): "the loopback engine (127.0.0.1) the auto-tuner a user started measures",
("strata_control/loopback.py", "urlopen"): "the one opener for this computer's own servers (no proxy); any other address is passed on unchanged",
("strata_control/components.py", "urlopen"): "the component fetcher: only `strata install`/UPDATE call it",
("strata_control/dsv41_engine.py", "urlopen"): "the DeepSeek engine's one 10-second 'is the feed reachable' check, called only by strata launch and "
"setup (test_the_deepseek_engine_check_is_reached_only_from_launch_and_setup); never while serving",
}
#: Modules that import the installer on purpose, with the explicit command that reaches them.
INSTALLER_IMPORT_ALLOWED = {
@@ -109,6 +111,26 @@ class ImportGraphTests(unittest.TestCase):
for rel in found:
self.assertIn(rel, INSTALLER_IMPORT_ALLOWED, f"{rel} imports installer code: {found[rel]}")
def test_the_deepseek_engine_check_is_reached_only_from_launch_and_setup(self):
"""strata_control/dsv41_engine.py (the engine's self-upgrade, 0.2.4.2) reaches the network; serving must never import it."""
importers = set()
for d in SERVING_DIRS:
for p in sorted((ROOT / d).glob("*.py")):
if p.name.startswith("test_") or p.name == "dsv41_engine.py":
continue
tree = ast.parse(p.read_text(encoding="utf-8"))
for node in ast.walk(tree):
names = [a.name for a in node.names] if isinstance(node, ast.Import) else [node.module] + [f"{node.module}.{a.name}" for a in node.names] if isinstance(node, ast.ImportFrom) and node.module else []
if any(n.endswith("dsv41_engine") for n in names):
importers.add(p.relative_to(ROOT).as_posix())
importers.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "strata_cli" / "launch").glob("*.py")
if "dsv41_engine" in p.read_text(encoding="utf-8") and not p.name.startswith("test_"))
importers.discard("strata_cli/launch/runner.py")
if "dsv41_engine" in (ROOT / "setup.py").read_text(encoding="utf-8"):
importers.add("setup.py")
importers.discard("setup.py")
self.assertEqual(sorted(importers), [], "only strata_cli/launch/runner.py and setup.py may use the DeepSeek engine check")
def test_no_installer_subprocess_or_network_call_on_the_serving_side(self):
bad = []
for p in _sources():
@@ -313,7 +335,15 @@ class CliServeIsOfflineTests(unittest.TestCase):
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), ([], []))
# Reading the hardware is not acquiring anything: nvidia-smi / hipInfo / rocminfo and PowerShell's Get-CimInstance (display adapters) only
# print what is here. Whether a PC runs them depends on the PC (a machine with nvidia-smi on PATH does), so the check is that nothing else runs.
probes = {"nvidia-smi", "hipinfo", "rocminfo", "rocm-smi", "vulkaninfo"}
def read_only(argv):
stem = Path(argv[0]).stem.lower()
return stem in probes or (stem in ("powershell", "pwsh") and any("Get-CimInstance" in a for a in argv))
self.assertEqual(rec.network, [])
self.assertEqual([a for a in rec.programs if not read_only(a)], [])
self.assertNotIn("setup", sys.modules.get("strata_cli.cli").__dict__.get("__name__", ""))
def test_strata_install_without_the_installer_is_a_typed_error(self):
+11
View File
@@ -1308,5 +1308,16 @@ class RuntimeTests(unittest.TestCase):
os.close(exclusive)
class StartWaitLimit(unittest.TestCase):
def test_a_start_may_wait_up_to_thirty_minutes_for_a_big_model(self): # #3949
from strata_control import runtime as rt, profiles as pr
self.assertEqual(rt.MAX_START_WAIT, 1800)
with self.assertRaisesRegex(pr.ProfileError, "start wait must be 0..1800"):
rt.start("x", wait=1801)
with mock.patch.object(rt, "_name", side_effect=pr.ProfileError("reached")):
with self.assertRaisesRegex(pr.ProfileError, "reached"):
rt.start("x", wait=1800)
if __name__ == "__main__":
unittest.main()
@@ -18,6 +18,20 @@ TRACEBACK = [
class SetupFailureWords(unittest.TestCase):
def test_an_option_setup_refuses_is_said_with_its_reason(self): # #3785
lines = ["Preparing unsloth UD-Q6_K_XL from your model files...",
"setup.py: error: argument --kv: invalid choice: 'bf16' (choose from int8, q4_0, k8v4, fp16)"]
error = setup_failure(lines, "", "", "/tmp/a.setup.log", True)
self.assertIn("The model could not be installed. Argument --kv: invalid choice: 'bf16'", error.text)
self.assertIn("/tmp/a.setup.log", error.next)
self.assertEqual(setup_failure(["nothing useful"], "", "", None, True).text, "The model could not be installed.")
def test_setup_accepts_the_kv_format_the_docker_docs_offer(self):
import subprocess, sys
root = Path(__file__).resolve().parents[2]
done = subprocess.run([sys.executable, str(root / "setup.py"), "--kv", "bogus"], capture_output=True, text=True, cwd=str(root), timeout=120)
self.assertIn("fp16", done.stderr.splitlines()[-1]) # the choices line of the argparse error
def test_the_last_line_of_a_traceback_is_found(self):
self.assertEqual(python_failure(TRACEBACK), "ModuleNotFoundError: No module named 'calibrate'")
self.assertIsNone(python_failure(["[X] Not enough disk space", " Free some space"]))
+10
View File
@@ -175,6 +175,16 @@ class Selection(unittest.TestCase):
self.assertTrue(any("580.65" in r for r in old[1]))
self.assertIsNone(self.pick(both, nvidia_driver="500.00")[0])
def test_an_update_keeps_the_cuda_build_that_runs_here(self): # #3835
both = [entry(variant="cuda12", driver="575.51", archs=("sm_60", "sm_61", "sm_86", "compute_89")), entry(variant="cuda13")]
two_cards = {"cuda_archs": ["sm_61", "sm_86"], "nvidia_driver": "615.71"}
self.assertEqual(self.pick(both, **two_cards)[0].variant, "cuda13") # nothing installed: as before
kept, reasons = self.pick(both, installed_variant="cuda12", **two_cards)
self.assertEqual(kept.variant, "cuda12")
self.assertTrue(any("is kept" in r for r in reasons))
only13 = [entry(variant="cuda13")]
self.assertEqual(self.pick(only13, installed_variant="cuda12")[0].variant, "cuda13") # the feed has no 12: the best fit
def test_the_newest_version_wins_and_the_card_must_be_covered(self):
newer = [entry("0.1.45"), entry("0.1.46")]
self.assertEqual(self.pick(newer)[0].version, "0.1.46")
+11
View File
@@ -457,6 +457,17 @@ class StartPathSignature(UpdaterCase):
ec.verify_signature(ec.read_manifest(folder), {ec.ENV_REQUIRE_SIGNED: "1"})
class LightTestStart(unittest.TestCase):
def test_the_test_start_drops_the_big_context_and_the_picture_reader(self): # #3842
args = ["--serve", "--pack", "p", "--max-context", "262144", "--kv", "int8", "--kv-resident", "32768", "--vision",
"--vision-tokens", "768", "--spec", "4"]
self.assertEqual(updater.light_test_args(args), ["--serve", "--pack", "p", "--max-context", "4096", "--kv", "int8", "--spec", "4"])
self.assertEqual(updater.light_test_args(["--max-context", "2048", "--vision", "cpu", "--mtp", "x"]),
["--max-context", "2048", "--mtp", "x"])
self.assertEqual(updater.light_test_args(["--vision"]), [])
self.assertEqual(updater.light_test_args(["--max-context", "abc"]), ["--max-context", "abc"])
class LazyModel(UpdaterCase):
"""A server that is "ready" with its model unloaded has not generated anything yet; the test start forces the load and the probe."""
+4 -4
View File
@@ -236,10 +236,10 @@ class VsRange(unittest.TestCase):
def test_the_range_follows_the_toolkit(self):
self.assertIsNone(self.asked(None)) # #881: without CUDA vswhere gets no version range
self.assertEqual(self.asked((13, 0)), "[16.0,18.0)")
self.assertEqual(self.asked((13, 2)), "[16.0,18.0)")
self.assertEqual(self.asked((13, 3)), "[16.0,19.0)")
self.assertEqual(self.asked((14, 0)), "[16.0,19.0)")
self.assertEqual(self.asked((13, 0)), "[17.0,18.0)")
self.assertEqual(self.asked((13, 2)), "[17.0,18.0)")
self.assertEqual(self.asked((13, 3)), "[17.0,19.0)")
self.assertEqual(self.asked((14, 0)), "[17.0,19.0)")
def test_vcvars_by_hand(self):
+65
View File
@@ -0,0 +1,65 @@
"""setup.find_tool takes the virtualenv's own cmake before a PATH one and skips a cmake older than CMakeLists.txt needs (#3822).
python -m unittest tools.test_setup_find_tool
"""
from __future__ import annotations
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import setup # noqa: E402
class FindTool(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.bin = Path(self.tmp.name) / "venv" / "bin"
self.bin.mkdir(parents=True)
self.venv_python = self.bin / "python"
def versions(self, table):
return lambda path, name: table.get(str(path), (False, ()))
def venv_tool(self, name="cmake"):
return str(self.bin / (name + (".exe" if setup.WIN else "")))
def find(self, table, on_path, name="cmake", venv_copy=True):
if venv_copy:
Path(self.venv_tool(name)).write_text("x")
with mock.patch.object(setup.sys, "executable", str(self.venv_python)), \
mock.patch.object(setup.shutil, "which", return_value=on_path), \
mock.patch.object(setup, "_tool_version", side_effect=self.versions(table)), \
mock.patch.object(setup.Path, "home", return_value=Path(self.tmp.name) / "home"):
return setup.find_tool(name), setup.tool_usable(name)
def test_the_virtualenv_copy_wins_over_an_old_system_cmake(self):
got, usable = self.find({"/usr/bin/cmake": (True, (3, 22, 1)), self.venv_tool(): (True, (4, 1, 0))}, "/usr/bin/cmake")
self.assertEqual(got, self.venv_tool())
self.assertTrue(usable)
def test_an_old_cmake_on_its_own_is_returned_but_not_usable(self):
got, usable = self.find({"/usr/bin/cmake": (True, (3, 22, 1))}, "/usr/bin/cmake", venv_copy=False)
self.assertEqual(got, "/usr/bin/cmake") # the build would say "CMake 3.24 or higher is required"
self.assertFalse(usable) # so setup installs the pip cmake first
def test_a_new_enough_system_cmake_is_fine_without_a_venv_one(self):
got, usable = self.find({"/usr/bin/cmake": (True, (3, 28, 3))}, "/usr/bin/cmake", venv_copy=False)
self.assertEqual((got, usable), ("/usr/bin/cmake", True))
def test_ninja_has_no_version_floor(self):
got, usable = self.find({"/usr/bin/ninja": (True, (1, 10))}, "/usr/bin/ninja", "ninja", venv_copy=False)
self.assertTrue(usable)
def test_a_launcher_that_does_not_run_is_skipped(self):
got, _ = self.find({self.venv_tool(): (False, ()), "/usr/bin/cmake": (True, (3, 30, 0))}, "/usr/bin/cmake")
self.assertEqual(got, "/usr/bin/cmake")
if __name__ == "__main__":
unittest.main()
+7
View File
@@ -49,6 +49,13 @@ class MacCheck(unittest.TestCase):
self.assertTrue(info["clt"])
self.assertEqual(M.mac_problems(info), [])
def test_an_intel_python_on_apple_silicon_is_still_an_apple_silicon_mac(self): # #3894
with mock.patch.object(M.platform, "machine", return_value="x86_64"):
info = M.mac_info(fake_run({**M5, "machdep.cpu.brand_string": "Apple M1 Max"}))
self.assertTrue(info["arm64"])
self.assertTrue(info["rosetta_python"])
self.assertNotIn("Intel", " ".join(M.mac_problems(info)))
def test_intel_old_macos_and_missing_tools_are_named(self):
with mock.patch.object(M.platform, "machine", return_value="x86_64"):
info = M.mac_info(fake_run({**M5, "macos": "14.6", "machdep.cpu.brand_string": "Intel Core i9"}, clt_rc=2))
+18 -5
View File
@@ -39,6 +39,14 @@ class Choice(unittest.TestCase):
self.assertEqual(tk, 12, archs)
self.assertIn(f"sm_{min(archs)} is older than CUDA 13 supports", why)
def test_a_driver_too_old_for_cuda13_gets_the_cuda12_engine(self): # #3843
self.assertEqual(setup.cuda_choice([86], None, 576)[0], 12)
self.assertIn("older than CUDA 13 needs", setup.cuda_choice([86], None, 576)[1])
self.assertEqual(setup.cuda_choice([86], None, 580), (13, None))
self.assertEqual(setup.cuda_choice([86], None, 0), (13, None)) # driver unknown: as before
self.assertEqual(setup.cuda_choice([86], None, 500), (13, None)) # too old for both: setup stops with the driver message
self.assertEqual(setup.cuda_choice([86], "13", 576)[0], 13) # chosen by hand: kept
def test_the_override_is_honored_with_a_warning(self):
tk, why = setup.cuda_choice([70], "13")
self.assertEqual(tk, 13) # recommend, never force: kept, and said
@@ -225,12 +233,17 @@ class Install(unittest.TestCase):
self.assertEqual((calls, cfg["cuda"]), ([12], 12))
self.assertIn("--cuda 12 (as you chose", out)
def test_an_old_driver_is_told_about_cuda12(self):
code, out, _, _, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")],
def test_an_old_driver_gets_cuda12_by_itself(self): # #3843: said in one line, not a stop
code, out, cfg, calls, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")],
argv_for("qwen", "IQ3_XXS"))
self.assertEqual(code, 0, out[-3000:])
self.assertEqual((calls, cfg["cuda"]), ([12], 12))
self.assertIn("older than CUDA 13 needs (580): this model runs the CUDA 12 engine", out)
code, out, _, _, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "470.10")],
argv_for("qwen", "IQ3_XXS"))
self.assertEqual(code, 1)
self.assertIn("580 or newer is needed", out)
self.assertIn("--cuda 12", out)
self.assertEqual(code, 1) # too old for both: the stop stays
self.assertIn("is too old", out)
self.assertNotIn("--cuda 12", out)
code, out, cfg, calls, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")],
argv_for("qwen", "IQ3_XXS") + ["--cuda", "12"])
self.assertEqual(code, 0, out[-3000:])
+17
View File
@@ -59,6 +59,23 @@ class OwnFileChecks(unittest.TestCase):
self.assertEqual(code, 1)
self.assertFalse(self.file.exists())
def test_a_complete_own_gguf_of_another_size_or_hash_is_used_with_a_warning(self): # #3777
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # `discover -s tools` puts only tools/ on the path
from tests.terminal.test_own_files import gguf_bytes
gguf = Path(self.tmp.name) / "fine-tune.gguf"
gguf.write_bytes(gguf_bytes(["Q8_0"]))
for size, sha in ((gguf.stat().st_size + 96, "0" * 64), (gguf.stat().st_size, "0" * 64)):
code, text = run(setup.verify_sha256, gguf, size, sha, own=True)
self.assertEqual(code, 0, text)
self.assertIn("Strata uses it as it is", text)
cut = Path(self.tmp.name) / "cut.gguf"
cut.write_bytes(gguf.read_bytes()[:-40]) # cut short: the tensor payload is not all there
code, text = run(setup.verify_sha256, cut, gguf.stat().st_size, "0" * 64, own=True)
self.assertEqual(code, 1)
self.assertIn("your file was left as it is", text)
code, text = run(setup.verify_sha256, gguf, gguf.stat().st_size + 96, "0" * 64) # a download is still checked
self.assertEqual(code, 1)
def test_a_matching_own_file_passes(self):
code, _text = run(setup.verify_sha256, self.file, 800, self.sha, own=True)
self.assertEqual(code, 0)
+16
View File
@@ -378,6 +378,7 @@ class Requirements(unittest.TestCase):
with mock.patch.object(setup, "WIN", False), \
mock.patch.object(setup, "find_tool", side_effect=find_tool), \
mock.patch.object(setup, "_tool_version", return_value=(True, (3, 28, 1))), \
mock.patch.object(setup, "pip_install", side_effect=pip_install), \
mock.patch.object(setup, "run", side_effect=run):
setup.cmake_build(ROOT, ROOT / "build-test", "strata", [], None, "unused.bat")
@@ -397,6 +398,21 @@ class Requirements(unittest.TestCase):
after = json.loads((Path(d) / ".strata-pip.json").read_text()) if ran else stamp
return [c for cmd in ran for c in cmd if "==" in c or c in setup.PY_PACKAGES], after
def test_a_stamp_written_by_another_system_is_not_believed(self): # #3634
lines = setup.requirement_lines()
with tempfile.TemporaryDirectory() as d:
(Path(d) / ".strata-pip.json").write_text(json.dumps(lines))
(Path(d) / ".strata-pip.json.os").write_text("win32" if setup.sys.platform != "win32" else "linux")
ran = []
with mock.patch.object(setup.sys, "prefix", d), mock.patch.object(setup, "run", lambda cmd, **kw: ran.append(cmd)):
quiet(setup.pip_install, lines, "the packages")
self.assertTrue(ran) # installed again, here
self.assertEqual((Path(d) / ".strata-pip.json.os").read_text(), setup.sys.platform)
ran.clear()
with mock.patch.object(setup.sys, "prefix", d), mock.patch.object(setup, "run", lambda cmd, **kw: ran.append(cmd)):
quiet(setup.pip_install, lines, "the packages")
self.assertFalse(ran) # and then skipped as before
def test_fresh_install_gets_every_pin(self):
lines = setup.requirement_lines()
ran, stamp = self.pip(None, lines)
+34
View File
@@ -0,0 +1,34 @@
"""A download with no data for two minutes says so (#3567).
python -m unittest tools.test_setup_stall_note
"""
import sys
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import setup # noqa: E402
class Stall(unittest.TestCase):
def test_silent_while_bytes_arrive_and_for_the_first_two_minutes(self):
s = setup.StallNote(0.0)
self.assertIsNone(s.check(10, 100, 1.0))
self.assertIsNone(s.check(20, 100, 200.0)) # moving
self.assertIsNone(s.check(20, 100, 300.0)) # 100 s idle
def test_says_it_once_a_minute_and_stops_when_data_comes(self):
s = setup.StallNote(0.0)
s.check(69, 100, 1.0)
said = s.check(69, 100, 130.0)
self.assertIn("no data for 2 min at 69%", said)
self.assertIn("run the same command again", said)
self.assertIsNone(s.check(69, 100, 150.0))
self.assertIn("min at 69%", s.check(69, 100, 200.0))
self.assertIsNone(s.check(70, 100, 201.0))
self.assertIsNone(s.check(70, 100, 250.0))
if __name__ == "__main__":
unittest.main()
+12
View File
@@ -54,6 +54,18 @@ class Update(unittest.TestCase):
call.assert_not_called()
self.assertIn("Strata is updated", out)
def test_an_engine_that_stayed_old_is_not_called_updated(self): # #3653
with tempfile.TemporaryDirectory() as d:
p = self.config(Path(d))
with mock.patch.object(setup, "engine_version", return_value=(0, 1, 44, 1)):
rc, pip, eng, dv, start, call, out = self.run_update([p])
self.assertIn("the engine was NOT", out)
self.assertIn("Next step:", out)
self.assertNotIn("[ok] Strata is updated", out)
with mock.patch.object(setup, "engine_version", return_value=(0, 1, 49, 2)):
rc, pip, eng, dv, start, call, out = self.run_update([p])
self.assertIn("Strata is updated (engine 0.1.49.2)", out)
def test_build_keeps_the_compiled_engine_path(self):
with tempfile.TemporaryDirectory() as d:
p = self.config(Path(d))