update: no model test load when memory is short; an unproven engine falls back by itself (#5400)

An engine update loaded the model "for testing" while other programs held
the memory, and the PC ran out of memory (RTX 5080 16 GB, 64 GB RAM).

- The test start reads the memory free now against what its test load
  needs, from the run config's own plan: the expert arena in the normal mode
  (setup's arena_gb), N GiB under --resident-budget-gib, nothing under
  --mmap-experts / --resident-experts, the PLE table only when it stays in
  RAM, plus the engine's own 5.3 GB and 4 GB headroom. Not enough: the model
  is not loaded, the engine gets the check an install without a model gets
  (it runs and answers --version), the update goes on and says: "Only <X> GB
  of memory is free right now and <model> needs about <Y> GB, so the new
  engine was checked without loading the model. It loads your model the next
  time it starts." Unknown memory: the full test as before.
- Such an engine is "unproven" (state.json engine.unproven). A start that
  reaches ready proves it. If its first real start fails because of the
  engine (not a refusal: no memory for the model, a busy port), runtime.start
  switches back to engine.previous by itself, once, and starts again within
  the same wait; the result carries engine_fallback and the line "The new
  engine <new> could not start your model, so Strata went back to engine
  <old>. Your settings are unchanged; the update will be offered again."
  (strata launch shows it; the app's `strata runtime start --output json`
  gets it). That version is held back (failed-before, `strata update --force`
  to use it again; then unproven again); with memory still short its next
  offer waits with the reason. An engine the person chose is never unproven.
- The light test arguments read the PLE table from the file (--ple-io
  direct, STRATA_PLE_AUTO_RAM=0 for the engine's own residency choice).

Measured on l620 (IQ3_S, released 0.2.14 engine, the test's light args):
before, engine peak 84.4 GB (the PLE table 28.8 GB locked in RAM); now the
normal mode peaks at 55.7 GB with system memory in use +53.8 GB, estimate
59.6 GB; with setup's own flags for a 46 GiB / 12 GB-card PC (--mmap-experts)
and 12 GB of the card usable, in use +5.7 GB, estimate 9.3 GB.

packaging/UPDATES.md says it. Tests: tests/terminal/test_update_low_memory.py
(enough / short / unknown memory, no model, the fallback once and no loop,
ready proves, a chosen engine, refusals, the second start inside the first
wait, the app's runtime start JSON, the estimate and the light args).
This commit is contained in:
Niko1221 committed 2026-11-16 18:34:22 +01:00
1 parent 3365da4618
commit 888c0db159
6 files changed
+490 -1

No files matched your search

+5
View File
@@ -136,6 +136,11 @@ into `components/engine/` and re-resolve to make sure a start now picks it. Any
Every older engine is kept until the person deletes it (Settings > Engine, `strata components remove`); `state.json` `engine.previous` is the one the last
switch left. A new engine becomes the one in use and clears any pin. With no model installed yet (first run)
the test is `--version` only, and the report says so.
When the memory free at that moment is less than what the test load of the model needs, from the engine's own plan, plus 4 GB, the model is not
loaded: the test is `--version` only, the update goes on and says so, and `state.json` marks the engine `engine.unproven`. Its first real start
proves it (ready clears the mark). If that start fails because of the engine, not a refusal such as no memory or a busy port, the owner runtime
switches back to `engine.previous` by itself, once, and starts again; that version is then held back (`engine.failed_unproven`) until
`strata update --force`.
Not while an engine is serving: the check uses the activity lease `strata serve` and the owner runtime already hold. `--wait SECONDS` waits;
a terminal asks whether to wait; scripts get exit 7. The download itself may run first; the check is repeated right before the test start and
+2
View File
@@ -2316,6 +2316,8 @@ class Runner:
self.end_failed_start()
raise LaunchError(f"The server could not start: {box['e']}", _log_hint(self.config_path, box["e"]), 6)
r = box["r"]
if r.get("engine_fallback"): # #5400: the new engine could not start the model; the previous one was used again
self.emit("start", str(r.get("note") or ""), None, level="warn")
if not r.get("ok"):
text, nxt = explain_engine_exit(r, self.config_path, marks=self._marks, server_log=self.server_log_path(),
shared_memory=self.shares_memory())
+41
View File
@@ -588,10 +588,51 @@ STOP_REAP_WAIT = 10.0 # seconds it then waits for the killed tree to be go
MAX_START_WAIT = 1800 # seconds a start may wait for the model: a 250 GB set on a slow disk needs more than 10 minutes (#3949)
#: #5400: words in a failed start that say the model did not fit (a refusal of this PC, not a broken engine): no fallback to the previous engine.
_NO_ROOM = re.compile(r"out of memory|not enough (?:free |graphics |gpu |video )?memory|cudaErrorMemoryAllocation|CUDA_ERROR_OUT_OF_MEMORY|"
r"hipErrorOutOfMemory|cannot allocate memory|MemoryError|address already in use|port .* (?:in use|busy)", re.I)
def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30,
expected_profile_revision: str | None = None,
expected_source_sha256: str | None = None,
die_with_pid: int | None = None, on_status=None) -> dict:
"""Start the saved profile under a new owner host (see _start_once). #5400: an engine the last update switched to without loading the model
(memory was short then) is proven by this start: ready clears that; a failure of the engine itself goes back to the previous engine and starts
once more, within the same wait. Never a loop: one switch back, and only for that engine."""
began = time.monotonic()
kw = dict(shutdown_timeout=shutdown_timeout, expected_profile_revision=expected_profile_revision,
expected_source_sha256=expected_source_sha256, die_with_pid=die_with_pid, on_status=on_status)
result = _start_once(name, wait=wait, **kw)
try:
from strata_control import updater
except Exception: # noqa: BLE001
return result
if result.get("state") == "ready":
updater.mark_proven()
return result
if result.get("state") != "failed" or wait == 0 or _NO_ROOM.search(f"{result.get('error', '')}\n{result.get('log_tail', '')}"):
return result
if updater.unproven_in_use() is None:
return result
try:
stop(name, timeout=60) # the failed start's host, so nothing serves while the engine is switched
except Exception: # noqa: BLE001 - a host that already left
pass
back = updater.fall_back_from_unproven()
if back is None:
return result
left = max(30.0, wait - (time.monotonic() - began))
again = _start_once(name, wait=min(left, MAX_START_WAIT), **kw)
again["engine_fallback"] = back
again["note"] = back["message"]
return again
def _start_once(name: str, *, wait: float = 300, shutdown_timeout: float = 30,
expected_profile_revision: str | None = None,
expected_source_sha256: str | None = None,
die_with_pid: int | None = None, on_status=None) -> dict:
"""Start the saved profile under a new owner host.
``on_status`` (optional) is called with each status answer while the start waits (about every 0.2 s; the caller throttles), so a
+208
View File
@@ -412,6 +412,7 @@ class Context:
feed_timeout: float = 30.0 # seconds a read of the feed may wait (the quiet daily check uses 5)
automatic: bool = False # a read of the feed nobody asked for by name (netpolicy rule 4b: the refusal note)
gate: object | None = None # strata_control.engine_update.ModelGate: what to do when a model is loaded (None: refuse before anything is downloaded)
memory_check: Callable | None = None # (run config) -> (free GB, needed GB) when memory is short for a test load, else None (#5400; tests)
def say(self, phase: str, message: str, **extra) -> None:
self.emit({"event": "phase", "phase": phase, "message": message, **extra})
@@ -694,6 +695,12 @@ def _choose_engine(feed: feedmod.Feed, ctx: Context, state: State) -> tuple[dict
if report["status"] == "available" and local:
report["installed_locally"] = local
report["download_bytes"] = 0
if offered.version in (section.get("failed_unproven") or {}) and not ctx.force:
# #5400: this engine was used without a test load (memory was short) and could not start the model; switching to it again by itself
# would repeat that. The person can ask for it by name.
report["status"] = "failed-before"
report["note"] = (f"{offered.version} could not start your model after the last update, so the previous engine is in use; "
"run `strata update --force` to use it again")
return report, offered
bad = (section.get("failed") or {}).get(offered.version)
if bad and _failed_mark_is_old(bad, ctx):
@@ -1107,6 +1114,11 @@ def _test_start_failure(component: ec.EngineComponent, started: dict, ctx: Conte
TEST_CONTEXT = 4096
_TEST_DROP_WITH_VALUE = ("--kv-resident", "--vision-tokens")
#: (#5400) "--ple-io ram" locks the n-gram (PLE) table in RAM (28.8 GB for IQ3_S, measured on l620): the test reads its rows from the file
#: ("direct"), which is all a one-token test needs. The engine also picks "ram" by itself when the RAM is free (its residency policy): the test
#: start's environment turns that off (TEST_ENV).
_TEST_PLE_IO = "direct"
TEST_ENV = {"STRATA_PLE_AUTO_RAM": "0"}
_TEST_DROP_FLAGS = ("--vision",)
@@ -1127,6 +1139,9 @@ def light_test_args(args: list) -> list:
i += 2
elif item in _TEST_DROP_WITH_VALUE and nxt is not None:
i += 2
elif item == "--ple-io" and nxt == "ram":
out += [item, _TEST_PLE_IO]
i += 2
elif item in _TEST_DROP_FLAGS:
i += 2 if nxt is not None and not nxt.startswith("--") else 1
else:
@@ -1135,6 +1150,110 @@ def light_test_args(args: list) -> list:
return out
#: #5400: the result mode of a test start that did not load the model because memory was short (the engine's binary check only), and the
#: share of a model's RAM figure (setup's MODELS[size]["ram_gb"], which counts the whole PC) that is the operating system's.
LOW_MEMORY_MODE = "binary-low-memory"
TABLE_OS_SHARE_GB = 4.0
_SETUP_MODELS: list = []
def _setup_models() -> dict:
"""setup.py's model table (MODELS), read once, quietly; {} when it cannot be read."""
if not _SETUP_MODELS:
table: dict = {}
try:
import importlib.util
path = Path(__file__).resolve().parents[1] / "setup.py"
spec = importlib.util.spec_from_file_location("strata_setup_for_update", path)
mod = importlib.util.module_from_spec(spec)
real = sys.stdout
sys.stdout = sys.stderr
try:
spec.loader.exec_module(mod)
finally:
sys.stdout = real
table = dict(getattr(mod, "MODELS", {}) or {})
except (Exception, SystemExit): # noqa: BLE001 - no table: the files' sizes decide
table = {}
_SETUP_MODELS.append(table)
return _SETUP_MODELS[0]
#: RAM the test start keeps free beside what it plans (#5400; the resident mode's own STRATA_RESIDENT_HEADROOM_GIB is the same 4 GB), and the
#: engine's own memory beside the expert arena and the PLE table: 84.4 GB peak (VmHWM) on l620 for IQ3_S = 50.3 arena + 28.8 PLE + 5.3
TEST_HEADROOM_GB = 4.0
ENGINE_BASE_GB = 5.3
_LOW_RAM_FLAGS = ("--mmap-experts", "--resident-experts")
def _flag_number(args: list[str], flag: str) -> float | None:
if flag in args[:-1]:
try:
return float(args[args.index(flag) + 1])
except ValueError:
return None
return None
def test_ram_need_gb(cfg: dict) -> float | None:
"""The RAM the update's test start (light_test_args) needs for this run config, in GB, from the engine's own plan of where the experts go
(docs/DETAILS.md "Low-RAM modes"), plus TEST_HEADROOM_GB:
- the normal mode copies every expert into RAM: the model's expert arena (setup's MODELS[size]["arena_gb"]);
- --resident-budget-gib N: N GiB of experts in RAM;
- --mmap-experts / --resident-experts: the experts are mapped, or copied only when they fit beside the headroom the engine keeps itself: nothing
beyond the headroom;
the light arguments leave no KV cache in RAM and no picture reader. Without the arena figure: setup's whole-PC figure less the system's share,
else the size of the model files. None when nothing is known (then the full test runs, as before)."""
args = [str(a) for a in cfg.get("args") or []]
extra = ENGINE_BASE_GB + TEST_HEADROOM_GB
if "--ple-io" in args[:-1] and args[args.index("--ple-io") + 1] == "ram" and "--ple-gguf" in args[:-1]:
try:
extra += Path(args[args.index("--ple-gguf") + 1]).stat().st_size / 1e9 # the PLE table locked in RAM (not after light_test_args)
except OSError:
pass
budget = _flag_number(args, "--resident-budget-gib")
if budget is not None:
return budget * 1.073741824 + extra
if any(f in args for f in _LOW_RAM_FLAGS):
return extra
name = str(cfg.get("model_name") or "").lower()
best = None
for size, entry in _setup_models().items():
if name.endswith("-" + str(size).lower()) and isinstance(entry, dict) and (entry.get("arena_gb") or entry.get("ram_gb")):
if best is None or len(str(size)) > len(best[0]):
best = (str(size), entry)
if best is not None:
entry = best[1]
if entry.get("arena_gb"):
return float(entry["arena_gb"]) + extra
return max(0.0, float(entry["ram_gb"]) - TABLE_OS_SHARE_GB)
total = 0
for flag in ("--native", "--ple-gguf"):
if flag in args[:-1]:
try:
total += Path(args[args.index(flag) + 1]).stat().st_size
except OSError:
pass
return total / 1e9 + extra if total else None
def free_ram_gb() -> float | None:
try:
from strata_control import tune_machine
mib = tune_machine.memory().get("available_mib")
return None if mib is None else mib * 1048576 / 1e9
except Exception: # noqa: BLE001 - unknown: the full test
return None
def low_memory(cfg: dict) -> tuple[float, float] | None:
"""(free GB, needed GB) when the memory free now is less than a test load of this model needs; None when there is room or either is unknown."""
need, free = test_ram_need_gb(cfg), free_ram_gb()
if need is None or free is None or free >= need:
return None
return free, need
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
@@ -1161,6 +1280,22 @@ def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Con
cfg.pop("lib_dirs", None)
if isinstance(cfg.get("args"), list):
cfg["args"] = light_test_args(cfg["args"])
cfg["env"] = {**(cfg.get("env") if isinstance(cfg.get("env"), dict) else {}), **TEST_ENV}
short = (ctx.memory_check or low_memory)(cfg)
if short:
# #5400: loading the model now would push this PC out of memory (other programs hold it). The engine gets the check an install with no
# model gets; it becomes "unproven" (_finish_engine_install), and if its first real start fails the previous engine is used again by itself.
free, need = short
model = cfg.get("model_name") or source.stem
if component.version in (State(ctx.components).section("engine").get("failed_unproven") or {}):
raise TestStartFailed(component.version, f"it could not be tested with your model: only {free:.0f} GB of memory is free right now and {model} needs "
f"about {need:.0f} GB, and the last time this engine was used without that test it could not start your model",
busy=True)
ctx.say("test", f"Only {free:.0f} GB of memory is free right now and {model} needs about {need:.0f} GB, so the new engine was checked without "
"loading the model. It loads your model the next time it starts.", component="engine")
out = binary_smoke(component, ctx=ctx)
return {**out, "mode": LOW_MEMORY_MODE, "model": model, "free_gb": round(free, 1), "need_gb": round(need, 1),
"detail": f"checked without the model: not enough free memory for a test load ({free:.0f} of {need:.0f} GB)"}
cfg["host"] = "127.0.0.1"
cfg["port"] = _free_port()
cfg["log"] = str(sandbox / "engine.log")
@@ -1293,6 +1428,11 @@ def _switch_to_installed(ctx: Context, state: State, folder: str, result: dict)
ctx.say("switch", "This engine is already on this computer; switching to it", component="engine")
out = engine_library.use_qwen_unlocked(ctx, state, folder)
chosen, _ = installed_engine(ctx.components, ctx.hardware)
section = state.section("engine")
if chosen is not None and chosen.version in (section.get("failed_unproven") or {}) and section.get("previous"):
# (#5400) asked for again with --force after it could not start the model: still not proven, so a failed first start goes back once more
section["unproven"] = {"version": chosen.version, "folder": chosen.root.name, "previous": section["previous"],
"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat()}
result.update({"changed": out.get("changed", False), "status": "updated" if out.get("changed") else "current", "installed_after": _engine_view(chosen),
"previous": state.section("engine").get("previous"), "removed": [], "presets_marked": bool(out.get("presets_marked")), "from_disk": True})
state.history({"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(), "action": "update-engine", "from": (result.get("installed_before") or {}).get("version"),
@@ -1368,6 +1508,13 @@ def _finish_engine_install(ctx: Context, state: State, pkg: feedmod.EnginePackag
section["previous"] = previous
section["active"] = final.name
section.get("failed", {}).pop(pkg.version, None)
if smoke.get("mode") == LOW_MEMORY_MODE and previous:
section["unproven"] = {"version": pkg.version, "folder": final.name, "previous": previous,
"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat()} # #5400: proven by its first real start
else:
section.pop("unproven", None)
if smoke.get("mode") == "full":
(section.get("failed_unproven") or {}).pop(pkg.version, None)
skipped = [v for v in section.get("skipped", []) if v != pkg.version]
section["skipped"] = skipped
after_identity = preset_marks.identity_of(chosen, pkg.manifest_sha256)
@@ -1465,6 +1612,7 @@ def switch_engine(ctx: Context, state: State, name: str, target: ec.EngineCompon
when the package is what a start picks anyway (the newest one), so the engine follows updates again. One writer of the pin and of the
previous / skipped bookkeeping: `strata components rollback` and `use_engine` (Settings > Engine, `strata components use`) both come here."""
section = state.section("engine")
section.pop("unproven", None) # (#5400) an engine the person chose, or went back to, is never switched away from by itself
current, _ = installed_engine(ctx.components, ctx.hardware)
leaving = current.root.name if current else None
before_identity = preset_marks.identity_of(current, _manifest_sha(current.root)) if current else None
@@ -1535,6 +1683,66 @@ def rollback_engine(ctx: Context) -> dict:
return switch_engine(ctx, state, previous, target, what="previous engine")
#: #5400: what a start says after it went back to the previous engine by itself.
FALLBACK_NOTE = ("The new engine {new} could not start your model, so Strata went back to engine {old}. Your settings are unchanged; "
"the update will be offered again.")
def unproven_in_use(root: Path | None = None, hardware: dict | None = None) -> dict | None:
"""The "unproven" record (#5400) when the engine a start uses now is the one the update switched to without a test load; else None."""
root = Path(root) if root else ec.components_dir()
try:
u = State(root).section("engine").get("unproven")
if not isinstance(u, dict) or not u.get("folder"):
return None
current, _ = installed_engine(root, hardware if hardware is not None else detect_hardware())
return u if current is not None and current.root.name == u["folder"] else None
except Exception: # noqa: BLE001 - a start never fails on this bookkeeping
return None
def mark_proven(root: Path | None = None, hardware: dict | None = None) -> bool:
"""A start reached ready with the unproven engine: it is proven, the record goes. True when there was one."""
root = Path(root) if root else ec.components_dir()
if unproven_in_use(root, hardware) is None:
return False
try:
with update_lock(root):
state = State(root)
state.section("engine").pop("unproven", None)
state.save()
return True
except Exception: # noqa: BLE001
return False
def fall_back_from_unproven(root: Path | None = None, *, hardware: dict | None = None, emit: Callable[[dict], None] = lambda event: None,
serving: Callable[[], list[dict]] = serving_now) -> dict | None:
"""The first real start with an unproven engine failed (#5400): go back to the previous engine (rollback_engine: nothing downloaded), once.
The version is remembered (failed_unproven) so the next offer of it needs the full test, and it is not hidden from the update (not "skipped").
None when there is nothing to do or the switch is not possible now (another model serving, the previous engine gone)."""
root = Path(root) if root else ec.components_dir()
hardware = hardware if hardware is not None else detect_hardware()
u = unproven_in_use(root, hardware)
if u is None:
return None
ctx = Context(components=root, source="", trusted={}, hardware=hardware, emit=emit, serving=serving)
try:
out = rollback_engine(ctx)
except (UpdateError, Busy, OSError):
return None
with update_lock(root):
state = State(root)
section = state.section("engine")
section.pop("unproven", None)
section.setdefault("failed_unproven", {})[u["version"]] = (dt.datetime.now(dt.timezone.utc)).isoformat()
section["skipped"] = [v for v in section.get("skipped", []) if v != u["version"]]
state.history({"at": dt.datetime.now(dt.timezone.utc).isoformat(), "action": "fallback-engine", "from": u["version"], "to": out.get("to"),
"ok": True, "detail": "the first start with an engine switched to without a test load failed"})
state.save()
return {"from": u["version"], "to": out.get("to"), "message": FALLBACK_NOTE.format(new=u["version"], old=out.get("to"))}
# ---------------------------------------------------------------------------------------------- control
def control_dir(root: Path) -> Path:
+1 -1
View File
@@ -49,7 +49,7 @@ class PendingState(unittest.TestCase):
self.fail("a complete state file of the wrong shape must not read as waiting")
def test_the_start_waits_with_pending_ok(self):
src = inspect.getsource(runtime.start)
src = inspect.getsource(runtime._start_once) # (#5400: start wraps _start_once, the one start)
self.assertIn("while _read_state(name, pending_ok=True) is None and proc.poll() is None", src)
self.assertIn("if _read_state(name, pending_ok=True) is None:", src)
+233
View File
@@ -0,0 +1,233 @@
"""#5400: an engine update loaded the model "for testing" and pushed a busy PC out of memory. When the memory free now is less than a test load of the
model needs, the new engine gets the check an install without a model gets (it runs and answers --version), the update goes on and the person is told;
that engine is "unproven" until a real start reaches ready. If its first real start fails (the engine itself, not a refusal such as no room), the
previous engine is used again by itself, once, and the version is not switched to again without the person asking (--force). Unknown memory: the full
test as before. No model installed: as before."""
from __future__ import annotations
import json
import unittest
from unittest import mock
from strata_control import runtime, updater
from tests.terminal import update_fixture as fx
from tests.terminal.test_updater import PLATFORM, UpdaterCase
SHORT = (20.0, 58.0)
class LowMemoryUpdate(UpdaterCase):
def update(self, memory, **over):
events: list = []
out = updater.run_update(self.ctx(memory_check=lambda cfg: memory, events=events, **over), control=False)
return out, events
def engine_state(self):
return updater.State(self.components).section("engine")
def test_short_memory_switches_without_loading_the_model_and_says_so(self):
self.install_current()
self.publish(("0.1.46", fx.GOOD_ENGINE))
with mock.patch.object(runtime, "start", side_effect=AssertionError("the model must not be loaded")):
out, events = self.update(SHORT)
self.assertEqual(out["results"][0]["status"], "updated", out)
self.assertEqual(self.resolved(), "0.1.46")
said = [e.get("message", "") for e in events]
self.assertIn("Only 20 GB of memory is free right now and fake needs about 58 GB, so the new engine was checked without loading the model. "
"It loads your model the next time it starts.", said)
u = self.engine_state()["unproven"]
self.assertEqual((u["version"], u["previous"]), ("0.1.46", f"0.1.45-{PLATFORM}-cuda-cuda13"))
self.assertEqual(updater.State(self.components).data["history"][-1]["detail"], updater.LOW_MEMORY_MODE)
def test_enough_memory_is_the_full_test_and_nothing_is_unproven(self):
self.install_current()
self.publish(("0.1.46", fx.GOOD_ENGINE))
out, _events = self.update(None)
self.assertEqual(out["results"][0]["status"], "updated", out)
self.assertNotIn("unproven", self.engine_state())
self.assertEqual(updater.State(self.components).data["history"][-1]["detail"], "full")
def test_a_failed_first_start_goes_back_once_and_the_version_waits_for_the_person(self):
self.install_current()
self.publish(("0.1.46", fx.GOOD_ENGINE))
with mock.patch.object(runtime, "start", side_effect=AssertionError("no test load")):
self.update(SHORT)
self.assertIsNotNone(updater.unproven_in_use(self.components, self.hardware))
back = updater.fall_back_from_unproven(self.components, hardware=self.hardware, serving=lambda: [])
self.assertEqual((back["from"], back["to"]), ("0.1.46", "0.1.45"))
self.assertEqual(back["message"], "The new engine 0.1.46 could not start your model, so Strata went back to engine 0.1.45. "
"Your settings are unchanged; the update will be offered again.")
self.assertEqual(self.resolved(), "0.1.45")
st = self.engine_state()
self.assertNotIn("unproven", st)
self.assertIn("0.1.46", st["failed_unproven"])
self.assertNotIn("0.1.46", st.get("skipped", []), "not hidden from the update")
self.assertIsNone(updater.fall_back_from_unproven(self.components, hardware=self.hardware, serving=lambda: []), "once: nothing more to do")
# the next update offers it, but does not switch to it by itself again (no loop)
again, _ = self.update(SHORT)
self.assertEqual(again["results"][0]["status"], "failed-before", again)
self.assertIn("could not start your model after the last update", again["results"][0].get("note", "") + json.dumps(again))
self.assertEqual(self.resolved(), "0.1.45")
# the person asks for it: it is used, and still unproven (a failed first start would go back once more)
forced, _ = self.update(SHORT, force=True)
self.assertEqual(self.resolved(), "0.1.46", forced)
self.assertEqual(self.engine_state()["unproven"]["version"], "0.1.46")
def test_a_ready_start_proves_it(self):
self.install_current()
self.publish(("0.1.46", fx.GOOD_ENGINE))
with mock.patch.object(runtime, "start", side_effect=AssertionError("no test load")):
self.update(SHORT)
self.assertTrue(updater.mark_proven(self.components, self.hardware))
self.assertNotIn("unproven", self.engine_state())
self.assertIsNone(updater.fall_back_from_unproven(self.components, hardware=self.hardware, serving=lambda: []))
self.assertEqual(self.resolved(), "0.1.46")
def test_an_engine_the_person_chose_is_never_unproven(self):
self.install_current()
self.publish(("0.1.46", fx.GOOD_ENGINE))
with mock.patch.object(runtime, "start", side_effect=AssertionError("no test load")):
self.update(SHORT)
updater.rollback_engine(self.ctx()) # the person goes back by hand (components rollback / use)
self.assertNotIn("unproven", self.engine_state())
self.assertIsNone(updater.unproven_in_use(self.components, self.hardware))
def test_no_model_installed_is_unchanged(self):
self.install_current()
self.publish(("0.1.46", fx.GOOD_ENGINE))
check = mock.Mock(return_value=SHORT)
with mock.patch.object(updater, "discover_run_config", return_value=None):
out = updater.run_update(self.ctx(run_config=None, memory_check=check), control=False)
self.assertEqual(out["results"][0]["status"], "updated", out)
check.assert_not_called()
self.assertNotIn("unproven", self.engine_state())
class MemoryRule(unittest.TestCase):
def test_unknown_memory_or_need_is_the_full_test(self):
with mock.patch.object(updater, "free_ram_gb", return_value=None), mock.patch.object(updater, "test_ram_need_gb", return_value=58.0):
self.assertIsNone(updater.low_memory({}))
with mock.patch.object(updater, "free_ram_gb", return_value=10.0), mock.patch.object(updater, "test_ram_need_gb", return_value=None):
self.assertIsNone(updater.low_memory({}))
with mock.patch.object(updater, "free_ram_gb", return_value=60.0), mock.patch.object(updater, "test_ram_need_gb", return_value=58.0):
self.assertIsNone(updater.low_memory({}))
with mock.patch.object(updater, "free_ram_gb", return_value=20.0), mock.patch.object(updater, "test_ram_need_gb", return_value=58.0):
self.assertEqual(updater.low_memory({}), (20.0, 58.0))
def test_the_need_is_the_test_starts_own_plan(self):
table = {"IQ3_S": {"ram_gb": 62, "arena_gb": 50.3}, "Q2_0": {"ram_gb": 48}}
with mock.patch.object(updater, "_setup_models", return_value=table):
iq3 = {"model_name": "qwen3.8-flash-next-iq3_s", "args": ["--expert-cache", "auto", "--max-context", "4096"]}
self.assertAlmostEqual(updater.test_ram_need_gb(iq3), 50.3 + 5.3 + 4.0) # every expert in RAM: the arena + the engine base + 4 GB
self.assertAlmostEqual(updater.test_ram_need_gb({**iq3, "args": ["--mmap-experts"]}), 9.3) # mapped: the OS cache
self.assertAlmostEqual(updater.test_ram_need_gb({**iq3, "args": ["--resident-experts"]}), 9.3) # copied only when they fit
self.assertAlmostEqual(updater.test_ram_need_gb({**iq3, "args": ["--resident-budget-gib", "10"]}), 10 * 1.073741824 + 9.3)
self.assertEqual(updater.test_ram_need_gb({"model_name": "qwen3.8-flash-next-q2_0", "args": []}), 44.0) # no arena figure: the PC figure
self.assertIsNone(updater.test_ram_need_gb({"model_name": "something-else", "args": []}))
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
ple = Path(tmp) / "ple.gguf"
ple.write_bytes(b"x" * 2_000_000)
held = {**iq3, "args": ["--ple-gguf", str(ple), "--ple-io", "ram"]}
self.assertAlmostEqual(updater.test_ram_need_gb(held), 50.3 + 5.3 + 4.0 + 0.002) # the PLE table when it stays in RAM
self.assertAlmostEqual(updater.test_ram_need_gb({**held, "args": updater.light_test_args(held["args"])}), 50.3 + 9.3)
def test_the_light_test_reads_the_ple_table_from_the_file(self):
self.assertEqual(updater.light_test_args(["--ple-gguf", "p", "--ple-io", "ram", "--max-context", "131072"]),
["--ple-gguf", "p", "--ple-io", "direct", "--max-context", "4096"])
self.assertEqual(updater.TEST_ENV, {"STRATA_PLE_AUTO_RAM": "0"}, "the engine's own choice of ram is off in the test start")
self.assertEqual(updater.light_test_args(["--ple-io", "mmap"]), ["--ple-io", "mmap"])
class StartFallsBack(unittest.TestCase):
"""runtime.start (the Terminal's launch and the app's `strata runtime start` both come here)."""
def run_start(self, results, *, unproven=True, back=True):
calls = []
def once(name, **kw):
calls.append(kw["wait"])
return dict(results[len(calls) - 1])
fall = {"from": "0.1.46", "to": "0.1.45", "message": "went back"} if back else None
with mock.patch.object(runtime, "_start_once", side_effect=once), \
mock.patch.object(runtime, "stop", return_value={"ok": True}), \
mock.patch.object(updater, "unproven_in_use", return_value={"version": "0.1.46"} if unproven else None), \
mock.patch.object(updater, "fall_back_from_unproven", return_value=fall) as fb, \
mock.patch.object(updater, "mark_proven") as proven:
out = runtime.start("p", wait=300)
return out, calls, fb, proven
FAILED = {"ok": False, "state": "failed", "error": "server_exited", "log_tail": "engine stopped: illegal instruction", "exit_code": 6}
READY = {"ok": True, "state": "ready", "exit_code": 0}
def test_an_engine_failure_goes_back_and_starts_once_more(self):
out, calls, fb, _p = self.run_start([self.FAILED, self.READY])
self.assertEqual(len(calls), 2)
self.assertEqual((out["state"], out["note"], out["engine_fallback"]["to"]), ("ready", "went back", "0.1.45"))
fb.assert_called_once()
def test_never_a_loop(self):
out, calls, fb, _p = self.run_start([self.FAILED, self.FAILED])
self.assertEqual(len(calls), 2, "one switch back, one more start, then the failure is the answer")
self.assertEqual(out["state"], "failed")
fb.assert_called_once()
def test_a_refusal_never_switches(self):
for tail in ("CUDA error: out of memory", "cudaErrorMemoryAllocation", "address already in use"):
out, calls, fb, _p = self.run_start([{**self.FAILED, "log_tail": tail}])
self.assertEqual(len(calls), 1, tail)
fb.assert_not_called()
def test_a_proven_engine_and_a_wait_that_ran_out_never_switch(self):
out, calls, fb, _p = self.run_start([self.FAILED], unproven=False)
self.assertEqual((len(calls), out["state"]), (1, "failed"))
fb.assert_not_called()
out, calls, fb, _p = self.run_start([{"ok": False, "state": "starting", "error": "startup_wait_expired", "exit_code": 8}])
self.assertEqual(len(calls), 1)
fb.assert_not_called()
def test_ready_proves_it(self):
out, calls, fb, proven = self.run_start([self.READY])
proven.assert_called_once()
fb.assert_not_called()
def test_the_second_start_keeps_inside_the_first_wait(self):
out, calls, _fb, _p = self.run_start([self.FAILED, self.READY])
self.assertLessEqual(calls[1], 300)
class TheAppsStartPath(unittest.TestCase):
"""The app starts a model with `strata runtime start --profile P --wait N --output json` (apps/host/server/control-runtime.mjs): the same
runtime.start, and its JSON carries the fallback and its line."""
def test_runtime_start_from_the_command_line(self):
import tempfile
from pathlib import Path
from strata_control import profiles
from tests.terminal.launch_support import Home, run_cli
results = [StartFallsBack.FAILED, StartFallsBack.READY]
calls = []
def once(name, **kw):
calls.append(name)
return dict(results[len(calls) - 1], profile=name)
with Home(), tempfile.TemporaryDirectory() as tmp:
cfg = Path(tmp) / "run.json"
(Path(tmp) / "tok").mkdir()
cfg.write_text(json.dumps({"exe": "/nowhere/strata", "args": [], "model_name": "fake", "port": 18555, "cwd": tmp,
"tokenizer": str(Path(tmp) / "tok")}), encoding="utf-8")
profiles.create("appslot", str(cfg))
back = {"from": "0.1.46", "to": "0.1.45", "message": "went back"}
with mock.patch.object(runtime, "_start_once", side_effect=once), mock.patch.object(runtime, "stop", return_value={"ok": True}), \
mock.patch.object(updater, "unproven_in_use", return_value={"version": "0.1.46"}), \
mock.patch.object(updater, "fall_back_from_unproven", return_value=back), mock.patch.object(updater, "mark_proven"):
code, out, err = run_cli(["runtime", "start", "--profile", "appslot", "--wait", "60", "--output", "json"])
self.assertEqual(len(calls), 2, err)
doc = json.loads(out)
self.assertEqual((doc["state"], doc["note"], doc["engine_fallback"]["to"]), ("ready", "went back", "0.1.45"))
if __name__ == "__main__":
unittest.main()