Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Update rules: Control --version waits longer and tries twice, a busy card is not held against an engine (other failures expire after a day), pre-release Control handover, a wrong PC clock says so
Niko1221cf34e915c4eb
diff --git a/strata_cli/handover.py b/strata_cli/handover.pyindex 7067abc3a..1e5119505 100644--- a/strata_cli/handover.py+++ b/strata_cli/handover.py@@ -28,7 +28,7 @@ def running_from_checkout() -> bool:"""True when this Terminal runs from a git checkout (the source route) rather than an installed bundle."""return (Path(__file__).resolve().parents[1] / ".git").exists()_FOLDER = re.compile(r"^[\w.+-]+$")-_VERSION = re.compile(r"^[0-9]+(\.[0-9]+){1,3}$")+_VERSION = re.compile(r"^[0-9]+(\.[0-9]+){1,3}(-[0-9A-Za-z][0-9A-Za-z.]*)?$") # 0.2.2, or a pre-release such as 0.2.2-rc1def components_dir(environ=None) -> Path:@@ -45,8 +45,18 @@ def components_dir(environ=None) -> Path:def version_key(text) -> tuple[int, ...] | None:if not isinstance(text, str) or not _VERSION.fullmatch(text.strip()):return None- parts = [int(p) for p in text.strip().split(".")]- return tuple(parts + [0] * (4 - len(parts)))+ base, dash, _pre = text.strip().partition("-")+ parts = [int(p) for p in base.split(".")]+ # a pre-release sorts below the same number without the suffix (0.2.2-rc1 < 0.2.2); two pre-releases of one number compare by name+ return tuple(parts + [0] * (4 - len(parts))) + ((0, _pre_rank(_pre)) if dash else (1, ()))+++def _pre_rank(pre: str) -> tuple:+ """alpha < beta < rc < anything else, then the number inside ("rc2" > "rc1")."""+ order = {"alpha": 0, "a": 0, "beta": 1, "b": 1, "rc": 2}+ m = re.match(r"([A-Za-z]*)\.?([0-9]*)", pre)+ word, number = (m.group(1).lower(), int(m.group(2) or 0)) if m else ("", 0)+ return (order.get(word, 3), number)def _read_json(path: Path):@@ -93,8 +103,12 @@ def find_target(running: str, environ=None, root: Path | None = None):if version is None:version = pointer.get("version")have, want = version_key(running), version_key(version)- if want is None or have is None or want <= have:- return None, None, None # never an older or equal Control; an unreadable version is ignored+ if have is None:+ return None, None, None # this Control has no readable version (a development tree): nothing to compare+ if want is None:+ return (None, None, f"its version ({version!r}) cannot be read") if version else (None, None, None)+ if want <= have:+ return None, None, None # never an older or equal Controlif not (bundled_python(folder).is_file() and (folder / "strata.py").is_file() and (folder / "strata_control").is_dir()):return None, version, f"{folder} is missing its interpreter or entry point"return folder, version, Nonediff --git a/strata_control/feed.py b/strata_control/feed.pyindex 8497f7f51..688a41eda 100644--- a/strata_control/feed.py+++ b/strata_control/feed.py@@ -279,9 +279,21 @@ def parse(payload: bytes, *, source: str, key_id: str) -> Feed:control=tuple(control), engine=tuple(engine), source=source, key_id=key_id, raw=payload)+def _expired_words(expires_at: str, now: dt.datetime, server_now: dt.datetime | None) -> str:+ """Expired by this PC's clock. If the update server's own clock says otherwise (or says the PC is far off), the clock is what is wrong."""+ fix = "Set the date and time right (Windows: Settings, Time & language, Date & time, Set time automatically) and try again."+ if server_now is not None:+ off = abs((server_now - now).total_seconds())+ if off > 15 * 60 and _time(expires_at, "expires_at") >= server_now:+ return (f"your PC clock is wrong: it says {now:%Y-%m-%d %H:%M} (UTC) but the update server says {server_now:%Y-%m-%d %H:%M}, "+ f"so the update feed looks expired. {fix}")+ return (f"the update feed expired on {expires_at} by this PC's clock ({now:%Y-%m-%d}). If that is not today's date, your PC clock is wrong. "+ f"{fix} Otherwise the update source needs to publish a new feed; nothing was downloaded.")++def verify_and_parse(payload: bytes, signature_bytes: bytes, *, source: str, trusted: dict[str, bytes],last_sequence: int | None = None, channel: str | None = None,- now: dt.datetime | None = None) -> Feed:+ now: dt.datetime | None = None, server_now: dt.datetime | None = None) -> Feed:"""Check the signature over `payload`, then parse; then the three guards: the channel is the one asked for, the feed hasnot expired, and its sequence is not lower than the last one accepted (a replayed older feed is a downgrade)."""if not trusted:@@ -300,7 +312,7 @@ def verify_and_parse(payload: bytes, signature_bytes: bytes, *, source: str, truraise FeedError(f"the feed is for the {feed.channel!r} channel, this PC follows {channel!r}")now = now or dt.datetime.now(dt.timezone.utc)if feed.expires_at and _time(feed.expires_at, "expires_at") < now:- raise FeedError(f"the update feed expired on {feed.expires_at}; refusing a stale feed")+ raise FeedError(_expired_words(feed.expires_at, now, server_now))if last_sequence is not None and feed.sequence < last_sequence:raise FeedDowngrade(f"the update feed is older than the one already accepted (sequence {feed.sequence} < {last_sequence}); ""refusing a replayed feed")@@ -324,6 +336,7 @@ def fetch(source: str, trusted: dict[str, bytes], **guards) -> Feed:signature = transfer.read_small(location + SIGNATURE_SUFFIX)except transfer.TransferError as exc:raise FeedError(f"the update feed could not be read: {exc}", 6) from None+ guards.setdefault("server_now", transfer.server_date())return verify_and_parse(payload, signature, source=location, trusted=trusted, **guards)diff --git a/strata_control/transfer.py b/strata_control/transfer.pyindex 5aa85fb65..256877319 100644--- a/strata_control/transfer.py+++ b/strata_control/transfer.py@@ -16,6 +16,8 @@ import http.clientimport ipaddressimport osimport threading+import email.utils+import datetime as _dtimport urllib.errorimport urllib.parseimport urllib.request@@ -131,14 +133,34 @@ _opener = urllib.request.build_opener(_PolicyRedirects)_USER_AGENT = "strata-updater/1"+_SERVER_DATE: list = []+++def server_date():+ """The time the update server named in the `Date` header of its last answer (a timezone-aware datetime), or None. It lets a feed that+ looks expired be told from a PC whose clock is wrong."""+ return _SERVER_DATE[-1] if _SERVER_DATE else None+++def _remember_date(response) -> None:+ try:+ parsed = email.utils.parsedate_to_datetime(response.headers.get("Date") or "")+ if parsed is not None:+ _SERVER_DATE[:] = [parsed if parsed.tzinfo else parsed.replace(tzinfo=_dt.timezone.utc)]+ except (TypeError, ValueError):+ pass++def read_small(location: str, *, limit: int = SMALL_LIMIT, timeout: float = 30) -> bytes:"""A small document (the feed, its signature). Larger than `limit` is refused, not truncated."""kind = kind_of(location)+ _SERVER_DATE.clear() # only the answer of this read countstry:if kind in ("http", "https"):check_url_policy(location)request = urllib.request.Request(location, headers={"User-Agent": _USER_AGENT, "Cache-Control": "no-cache"})with _opener.open(request, timeout=timeout) as response:+ _remember_date(response)data = response.read(limit + 1)else:path = _local_path(location)@@ -151,7 +173,11 @@ def read_small(location: str, *, limit: int = SMALL_LIMIT, timeout: float = 30)raise TransferError(f"the update server answered {exc.code} for {location}") from Noneexcept (urllib.error.URLError, OSError, TimeoutError) as exc:reason = getattr(exc, "reason", exc)- raise TransferError(f"could not read {location} ({type(exc).__name__}: {reason})") from None+ hint = ""+ if "CERTIFICATE_VERIFY_FAILED" in str(reason):+ hint = (". This computer did not accept the update server's certificate: check that its date and time are right, "+ "or that a company proxy is not replacing the certificate")+ raise TransferError(f"could not read {location} ({type(exc).__name__}: {reason}){hint}") from Noneif len(data) > limit:raise TransferError(f"{location} is larger than {limit} bytes")return datadiff --git a/strata_control/updater.py b/strata_control/updater.pyindex 65c5e62be..f93d90413 100644--- a/strata_control/updater.py+++ b/strata_control/updater.py@@ -72,9 +72,16 @@ class Busy(UpdateError):class TestStartFailed(UpdateError):__test__ = False # not a pytest class+ #: reasons that say the graphics card or memory was busy, not that the engine is broken+ BUSY = re.compile(r"timed?[ -]?out|out of memory|\boom\b|not enough (gpu |video |free )?memory|vram|memory allocation|"+ r"cudaerrormemory|device (is )?(busy|in use)|resource busy|no free (gpu|memory)", re.I)+def __init__(self, label: str, reason: str):+ self.busy = bool(self.BUSY.search(reason))super().__init__(f"The new engine {label} did not pass its test start ({reason}). It was not installed; "- "your current engine is unchanged.", 6)+ "your current engine is unchanged."+ + (" The graphics card or memory looks busy: close programs that use the card (games, video, other models) "+ "and run `strata update` again." if self.busy else ""), 6)self.label = labelself.reason = reason@@ -476,6 +483,8 @@ def _choose_engine(feed: feedmod.Feed, ctx: Context, state: State) -> tuple[dictelse:report["status"] = "available"bad = (section.get("failed") or {}).get(offered.version)+ if bad and _failed_mark_is_old(bad, ctx):+ bad = None # a failure is held against a version for a day, not for everif report["status"] == "available" and not ctx.force:if bad and bad.get("manifest_sha256") == offered.manifest_sha256:report["status"] = "failed-before"@@ -786,10 +795,11 @@ def update_engine(ctx: Context, feed: feedmod.Feed, state: State) -> dict:smoke = runner(stage_root, staged, ctx)except TestStartFailed as exc:section = state.section("engine")- section.setdefault("failed", {})[pkg.version] = {- "manifest_sha256": pkg.manifest_sha256, "reason": exc.reason[:300],- "at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat()}- state.history({"at": section["failed"][pkg.version]["at"], "action": "update-engine", "to": pkg.version,+ at = (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat()+ if not exc.busy: # a busy card says nothing about the engine: the next update tries again+ section.setdefault("failed", {})[pkg.version] = {+ "manifest_sha256": pkg.manifest_sha256, "reason": exc.reason[:300], "at": at}+ state.history({"at": at, "action": "update-engine", "to": pkg.version,"from": before_installed.version if before_installed else None, "ok": False,"detail": f"test start failed: {exc.reason[:200]}"})state.save()@@ -924,6 +934,40 @@ def decide_control(feed: feedmod.Feed, ctx: Context, state: State) -> dict:return report+CONTROL_VERSION_TIMEOUTS = (240, 360) # seconds: antivirus scans a fresh python.exe on its first run, which can take minutes+++def _control_version(interpreter: str, entry: Path, stage: Path, ctx: Context, version: str):+ """Run `--version` of the staged Control; once more, with more time, when the first try timed out, failed to start or said nothing."""+ last_error = None+ done = None+ for attempt, timeout in enumerate(CONTROL_VERSION_TIMEOUTS):+ try:+ done = subprocess.run([interpreter, str(entry), "--version"], capture_output=True, text=True, timeout=timeout, cwd=str(stage),+ env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1", "STRATA_HANDOVER": "1"},+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ last_error = None+ if done.returncode == 0 and version in done.stdout:+ return done+ except (OSError, subprocess.SubprocessError) as exc:+ last_error = exc+ if attempt + 1 < len(CONTROL_VERSION_TIMEOUTS):+ ctx.say("test", f"Control {version} did not answer yet (a virus scanner may be checking it); trying once more", component="control")+ if last_error is not None:+ raise TestStartFailed(f"Control {version}", f"{type(last_error).__name__}: {last_error}") from None+ return done+++def _failed_mark_is_old(mark: dict, ctx: Context, hours: float = 24.0) -> bool:+ try:+ then = dt.datetime.fromisoformat(str(mark.get("at")))+ if then.tzinfo is None:+ then = then.replace(tzinfo=dt.timezone.utc)+ return (ctx.now or dt.datetime.now(dt.timezone.utc)) - then > dt.timedelta(hours=hours)+ except (TypeError, ValueError):+ return False++def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict:"""Stage a newer Control bundle beside the running one, run it once (`--version`), and only then point the app and theterminal at it (``components/control/active.json``). The running Control is never modified."""@@ -945,12 +989,7 @@ def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict:python = stage / "python" / ("python.exe" if os.name == "nt" else "bin/python3")interpreter = str(python) if python.is_file() else sys.executablectx.say("test", f"Test-starting Control {pkg.version}", component="control")- try:- done = subprocess.run([interpreter, str(entry), "--version"], capture_output=True, text=True, timeout=120, cwd=str(stage),- env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1", "STRATA_HANDOVER": "1"},- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))- except (OSError, subprocess.SubprocessError) as exc:- raise TestStartFailed(f"Control {pkg.version}", f"{type(exc).__name__}: {exc}") from None+ done = _control_version(interpreter, entry, stage, ctx, pkg.version)if done.returncode != 0 or pkg.version not in done.stdout:raise TestStartFailed(f"Control {pkg.version}", f"--version said {done.stdout.strip()[:120]!r} (exit {done.returncode})")final = control_dir(root) / pkg.versiondiff --git a/tests/terminal/test_update_rules_022.py b/tests/terminal/test_update_rules_022.pynew file mode 100644index 000000000..361116143--- /dev/null+++ b/tests/terminal/test_update_rules_022.py@@ -0,0 +1,155 @@+"""0.2.2 update rules: a slow first run of Control is waited for, a busy card is not held against an engine, a pre-release Control is+handed over to (or not) by its number, and a feed that looks expired on a PC with a wrong clock says so."""++import datetime as dt+import json+import subprocess+import tempfile+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest import mock++from strata_cli import handover+from strata_control import feed as feedmod, signing, updater+from tests.terminal import update_fixture as fx+from tests.terminal.test_handover import make_control+from tests.terminal.test_update_feed import document, signed+from tests.terminal import test_updater+++class ControlVersionTest(unittest.TestCase):+ def ctx(self):+ said = []+ return SimpleNamespace(environ={}, say=lambda *a, **k: said.append(a)), said++ def test_a_first_run_that_times_out_is_tried_once_more_with_more_time(self):+ ctx, said = self.ctx()+ good = SimpleNamespace(returncode=0, stdout="strata 0.2.2\n")+ calls = []++ def fake(cmd, **kw):+ calls.append(kw["timeout"])+ if len(calls) == 1:+ raise subprocess.TimeoutExpired(cmd, kw["timeout"])+ return good+ with mock.patch.object(updater.subprocess, "run", fake):+ done = updater._control_version("py", Path("strata.py"), Path("."), ctx, "0.2.2")+ self.assertIs(done, good)+ self.assertEqual(calls, list(updater.CONTROL_VERSION_TIMEOUTS))+ self.assertGreater(calls[0], 120)+ self.assertEqual(len(said), 1)++ def test_two_failures_end_as_a_failed_test_start(self):+ ctx, _ = self.ctx()+ with mock.patch.object(updater.subprocess, "run", side_effect=subprocess.TimeoutExpired("x", 1)):+ with self.assertRaises(updater.TestStartFailed):+ updater._control_version("py", Path("strata.py"), Path("."), ctx, "0.2.2")+++class BusyCardTest(test_updater.UpdaterCase):+ def refuse(self, reason):+ def runner(stage_root, staged, ctx):+ raise updater.TestStartFailed(staged.version, reason)+ return runner++ def test_a_busy_card_is_not_held_against_the_engine(self):+ self.install_current()+ self.publish(("0.1.47", fx.GOOD_ENGINE))+ out = updater.run_update(self.ctx(test_start=self.refuse("it timed out waiting for the graphics card")), control=False)+ result = out["results"][0]+ self.assertEqual(result["status"], "failed")+ self.assertIn("looks busy", result["error"])+ again = updater.run_update(self.ctx(), control=False)+ self.assertEqual(again["results"][0]["status"], "updated", again)++ def test_a_real_failure_is_remembered_for_a_day_and_then_tried_again(self):+ self.install_current()+ self.publish(("0.1.47", fx.GOOD_ENGINE))+ updater.run_update(self.ctx(test_start=self.refuse("the engine crashed on start")), control=False)+ soon = updater.run_update(self.ctx(), control=False)+ self.assertEqual(soon["results"][0]["status"], "failed-before")+ later = dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=25)+ retry = updater.run_update(self.ctx(now=later), control=False)+ self.assertEqual(retry["results"][0]["status"], "updated", retry)+++class HandoverPreRelease(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory(prefix="strata-rc-")+ self.addCleanup(self.temp.cleanup)+ self.comp = Path(self.temp.name) / "components"+ self.comp.mkdir()+ self.env = {"STRATA_COMPONENTS_DIR": str(self.comp)}++ def target(self, running):+ return handover.find_target(running, self.env)++ def test_the_order_of_releases_and_candidates(self):+ key = handover.version_key+ self.assertLess(key("0.2.2-rc1"), key("0.2.2"))+ self.assertLess(key("0.2.2-rc1"), key("0.2.2-rc2"))+ self.assertLess(key("0.2.2-beta"), key("0.2.2-rc1"))+ self.assertLess(key("0.2.1"), key("0.2.2-rc1"))+ self.assertIsNone(key("banana"))++ def test_a_release_candidate_is_handed_over_to_from_an_older_release(self):+ make_control(self.comp, "0.2.2-rc1")+ folder, version, problem = self.target("0.2.1")+ self.assertIsNone(problem)+ self.assertEqual(version, "0.2.2-rc1")+ self.assertEqual(folder.name, "0.2.2-rc1")++ def test_the_final_release_replaces_its_candidate_but_not_the_other_way(self):+ make_control(self.comp, "0.2.2")+ self.assertEqual(self.target("0.2.2-rc1")[1], "0.2.2")+ make_control(self.comp, "0.2.2-rc1", point=False)+ (self.comp / "control" / "active.json").write_text(json.dumps({"version": "0.2.2-rc1", "folder": "0.2.2-rc1"}))+ self.assertEqual(self.target("0.2.2"), (None, None, None))++ def test_a_version_nobody_can_read_is_said_not_ignored(self):+ make_control(self.comp, "banana")+ folder, version, problem = self.target("0.2.1")+ self.assertIsNone(folder)+ self.assertIn("cannot be read", problem)+++class ClockTest(unittest.TestCase):+ def setUp(self):+ self.key = signing.generate_key()+ self.trusted = fx.trusted_of(self.key)++ def load(self, **guards):+ payload, sig = signed(document(expires_at="2026-10-01T00:00:00Z"), self.key)+ return feedmod.verify_and_parse(payload, sig, source="/feeds/strata-feed.json", trusted=self.trusted, **guards)++ def test_the_server_clock_proves_the_pc_clock_wrong(self):+ pc = dt.datetime(2027, 3, 1, tzinfo=dt.timezone.utc)+ server = dt.datetime(2026, 9, 20, tzinfo=dt.timezone.utc)+ with self.assertRaises(feedmod.FeedError) as caught:+ self.load(now=pc, server_now=server)+ text = str(caught.exception)+ self.assertIn("your PC clock is wrong", text)+ self.assertIn("2026-09-20", text)+ self.assertNotIn("refusing a stale feed", text)++ def test_without_a_server_date_the_clock_is_named_as_a_cause(self):+ with self.assertRaisesRegex(feedmod.FeedError, "your PC clock is wrong.*new feed"):+ self.load(now=dt.datetime(2027, 3, 1, tzinfo=dt.timezone.utc))++ def test_a_feed_the_server_also_calls_expired_is_still_refused_as_expired(self):+ pc = dt.datetime(2026, 11, 1, tzinfo=dt.timezone.utc)+ with self.assertRaisesRegex(feedmod.FeedError, "expired on"):+ self.load(now=pc, server_now=pc)++ def test_a_certificate_error_hints_at_the_clock(self):+ import urllib.error+ from strata_control import transfer+ err = urllib.error.URLError("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed")+ with mock.patch.object(transfer._opener, "open", side_effect=err):+ with self.assertRaisesRegex(transfer.TransferError, "date and time"):+ transfer.read_small("https://example.org/strata-feed.json")+++if __name__ == "__main__":+ unittest.main()