okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
43.5 KiB816 linesraw
1"""The signed update feed: what is published, how it is checked, which engine package fits a PC.
2
3One small document, ``strata-feed.json``, with a detached Ed25519 signature ``strata-feed.json.sig`` (the signature covers the
4file's exact bytes, so there is no canonicalisation to get wrong). It lists, for one channel:
5
6* ``app``: the desktop app, in exactly the shape of Tauri's static updater JSON (``version``, ``notes``, ``pub_date``,
7  ``platforms{<tauri target>: {url, signature}}``), plus ``sha256`` and ``size`` per platform. The Tauri updater plugin
8  reads a copy of this member at ``app/latest.json`` and checks the minisign signature itself;
9* ``control``: the runtime component (Control: bundled Python, ``strata_control``, the CLI and server), one archive per platform;
10* ``engine``: the engine packages, one entry per platform / backend / variant, each with ``version``, ``archs``,
11  ``min_driver``, ``min_runtime``, ``size``, ``sha256`` of the archive, ``manifest_sha256`` of the package's
12  ``engine-component.json`` (which holds every file's hash) and a URL.
13
14The feed's signature plus those hashes is the whole chain of trust: a package whose archive hash or manifest hash is not the
15one in the signed feed is never installed. Three refusals are tested: a bad signature, a bad hash and a downgrade. The
16downgrade guard has two parts: a feed whose ``sequence`` is lower than the last one this PC accepted is refused (a replayed
17old feed), and a package older than the installed one is never installed by an update.
18
19Nothing here touches the network itself; `strata_control.transfer` does.
20"""
21
22from __future__ import annotations
23
24import dataclasses
25import datetime as dt
26import json
27import logging
28import re
29from dataclasses import dataclass, field
30
31from strata_control import netpolicy, shape_engine, signing, transfer
32from strata_control.targets import BACKEND_MATRIX, host_platform
33
34SCHEMA_VERSION = 1
35FEED_NAME = "strata-feed.json"
36#: The Linux ARM64 (DGX Spark) Terminal reads this file instead. A Control older than 0.1.53 refuses a feed that names a platform it does not know, so
37#: the linux-aarch64 entries cannot sit in strata-feed.json: that file stays as every released client can read it. Same format, same key.
38AARCH64_FEED_NAME = "strata-feed-linux-aarch64.json"
39SIGNATURE_SUFFIX = ".sig"
40FORMATS = ("tar.gz", "tar.xz", "zip")
41PLATFORMS = ("windows-x86_64", "linux-x86_64", "linux-aarch64", "macos-arm64", "macos-x86_64")
42#: Tauri's names for the same platforms (no desktop app is built for linux-aarch64: the entry only keeps the name parsable).
43TAURI_TARGETS = {"windows-x86_64": "windows-x86_64", "linux-x86_64": "linux-x86_64", "linux-aarch64": "linux-aarch64",
44                 "macos-arm64": "darwin-aarch64", "macos-x86_64": "darwin-x86_64"}
45_VERSION = re.compile(r"\d+\.\d+\.\d+(?:\.\d+)?")
46_HEX64 = re.compile(r"[0-9a-f]{64}")
47_log = logging.getLogger("strata.feed")
48
49
50class FeedError(RuntimeError):
51    """The feed or something it lists cannot be trusted or used. `exit_code` is the CLI's."""
52
53    def __init__(self, message: str, exit_code: int = 5):
54        super().__init__(message)
55        self.exit_code = exit_code
56
57
58class FeedUnreachable(FeedError):
59    """The feed's host did not answer, or this computer is offline (strata_control/netpolicy.py's words): a check that runs by itself stays silent."""
60
61
62class FeedDowngrade(FeedError):
63    """A feed or a package older than what this PC already has."""
64    # .sequence is the feed's, .accepted the last one this PC took (the updater adds the folder that holds it)
65    sequence: int | None = None
66    accepted: int | None = None
67
68
69def version_key(value: str) -> tuple[int, ...]:
70    if not isinstance(value, str) or not _VERSION.fullmatch(value):
71        raise FeedError(f"{value!r} is not a version number (expected like 0.1.46 or 0.1.46.1)")
72    parts = [int(p) for p in value.split(".")]
73    return tuple(parts + [0] * (4 - len(parts)))
74
75
76def app_version_key(value: str) -> tuple[int, ...]:
77    """Compare the INSTALLED app's version: like `version_key`, but a pre-release (0.2.0-beta) is allowed and sorts below the same number without
78    the suffix. The feed's own versions stay strict (`version_key`)."""
79    base, dash, pre = str(value).partition("-")
80    if dash and not re.fullmatch(r"[0-9A-Za-z.]+", pre):
81        raise FeedError(f"{value!r} is not a version number (expected like 0.2.0 or 0.2.0-beta)")
82    return version_key(base) + (0 if dash else 1,)
83
84
85def _need(obj: dict, key: str, kind, where: str):
86    value = obj.get(key)
87    if not isinstance(value, kind) or isinstance(value, bool) and kind is int:
88        raise FeedError(f"the feed's {where} has no valid {key}")
89    return value
90
91
92def _hex(value, where: str) -> str:
93    if not isinstance(value, str) or not _HEX64.fullmatch(value.lower()):
94        raise FeedError(f"the feed's {where} has no valid sha256")
95    return value.lower()
96
97
98@dataclass(frozen=True)
99class EnginePackage:
100    version: str
101    platform: str
102    backend: str
103    variant: str
104    archs: tuple[str, ...]
105    min_driver: dict
106    min_runtime: str | None
107    build_id: str
108    url: str
109    format: str
110    size: int
111    sha256: str
112    manifest_sha256: str
113    installed_bytes: int
114    notes: str = ""
115    shape: str = ""                 # the engine of one model shape (feed member ``shape_engines``, strata_control/shape_engine.py): its compiled geometry's name; "" for the others
116
117    @property
118    def label(self) -> str:
119        return f"{self.version} {self.platform}-{self.backend}" + (f"-{self.variant}" if self.variant else "")
120
121    def to_dict(self) -> dict:
122        return {"version": self.version, "platform": self.platform, "backend": self.backend, "variant": self.variant,
123                "archs": list(self.archs), "min_driver": dict(self.min_driver), "min_runtime": self.min_runtime,
124                "build_id": self.build_id, "size": self.size, "installed_bytes": self.installed_bytes,
125                "format": self.format, "url": self.url, "sha256": self.sha256, "manifest_sha256": self.manifest_sha256,
126                **({"shape": self.shape} if self.shape else {})}
127
128
129@dataclass(frozen=True)
130class DrafterPackage:
131    """A DFlash2 drafter file Strata hosts (feed member ``drafters``): one pinned file, not an archive. ``backends`` are the engine families it was measured on
132    (``metal``); ``url`` is relative to the feed (flat release assets) or an https address; ``size`` and ``sha256`` are the file's. The code that fetches it
133    pins the same size and SHA-256 (strata_control/drafting.py), so the feed can move the file but never swap its bytes."""
134    name: str
135    version: str
136    url: str
137    size: int
138    sha256: str
139    backends: tuple[str, ...]
140    base: str = ""
141    licence: str = ""
142    notes: str = ""
143
144    @property
145    def label(self) -> str:
146        return f"drafter {self.name} {self.version}"
147
148    def to_dict(self) -> dict:
149        return {"name": self.name, "version": self.version, "url": self.url, "size": self.size, "sha256": self.sha256,
150                "backends": list(self.backends), "base": self.base, "licence": self.licence, "notes": self.notes}
151
152
153#: Families a ``models`` entry may name that this Control knows how to install (GGUF architectures the engine runs: ``strata --families``). A model of another family
154#: is still listed, as "not available on this engine"; it is never offered to install.
155MODEL_FAMILIES_INSTALLABLE = ("qwen4exp", "qwen35moe")
156_MODEL_ID = re.compile(r"[a-z0-9][a-z0-9.-]{1,39}")
157_MODEL_FAMILY = re.compile(r"[a-z0-9_]{2,32}")
158_MODEL_REPO = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,95}/[A-Za-z0-9][A-Za-z0-9._-]{0,95}")
159_MODEL_REVISION = re.compile(r"[0-9a-f]{40}")
160_MODEL_QUANT = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,31}")
161MODEL_DRAFTERS = ("mtp", "none")
162
163
164@dataclass(frozen=True)
165class ModelFile:
166    """One pinned file of a feed model: ``path`` is its place in the Hugging Face repository (``name`` when it sits at the top), ``size`` and ``sha256`` are its exact bytes."""
167    name: str
168    size: int
169    sha256: str
170    path: str = ""
171
172    @property
173    def repo_path(self) -> str:
174        return self.path or self.name
175
176    def to_dict(self) -> dict:
177        out = {"name": self.name, "size": self.size, "sha256": self.sha256}
178        if self.path:
179            out["path"] = self.path
180        return out
181
182
183@dataclass(frozen=True)
184class ModelQuant:
185    """One size of a feed model: the files that make it, and the setup recommendation for it (``ram_gb`` the memory it wants; ``arena_gb`` the experts' share, 0: not given)."""
186    name: str
187    about: str
188    ram_gb: float
189    arena_gb: float
190    files: tuple[ModelFile, ...]
191
192    @property
193    def download_bytes(self) -> int:
194        return sum(f.size for f in self.files)
195
196    def to_dict(self) -> dict:
197        return {"name": self.name, "about": self.about, "ram_gb": self.ram_gb, "arena_gb": self.arena_gb, "files": [f.to_dict() for f in self.files]}
198
199
200@dataclass(frozen=True)
201class FeedModel:
202    """A model Strata lists after the built-in ones (feed member ``models``). Everything setup needs to install it is here and signed: the repository and the pinned revision,
203    each file's exact size and SHA-256 (setup checks them after the download, and a wrong file is kept as ``.bad``, exactly as for a built-in model), the engine family,
204    the licence and the first engine version that reads it."""
205    id: str
206    title: str
207    by: str
208    about: str
209    licence: str
210    licence_url: str
211    family: str
212    repo: str
213    revision: str
214    quants: tuple[ModelQuant, ...]
215    mmproj: ModelFile | None = None
216    pictures: bool = False
217    drafter: str = "none"
218    context: int = 0
219    min_engine: str = ""
220    kv_bytes_per_token: int = 0
221    mtp_drafts: int = 0
222    state_gb: float = 0.0
223
224    @property
225    def label(self) -> str:
226        return f"model {self.id}"
227
228    @property
229    def shape(self) -> str | None:
230        """The model shape whose own engine runs it (``q4_lite``), or None: it runs on the Strata engine."""
231        return shape_engine.shape_of_family(self.family)
232
233    def to_dict(self) -> dict:
234        out = {"id": self.id, "title": self.title, "by": self.by, "about": self.about, "licence": self.licence, "licence_url": self.licence_url,
235               "family": self.family, "repo": self.repo, "revision": self.revision, "quants": [q.to_dict() for q in self.quants],
236               "pictures": self.pictures, "drafter": self.drafter, "context": self.context, "min_engine": self.min_engine}
237        if self.mmproj:
238            out["mmproj"] = self.mmproj.to_dict()
239        if self.kv_bytes_per_token:
240            out["kv_bytes_per_token"] = self.kv_bytes_per_token
241        if self.mtp_drafts:
242            out["mtp_drafts"] = self.mtp_drafts
243        if self.state_gb:
244            out["state_gb"] = self.state_gb
245        return out
246
247
248@dataclass(frozen=True)
249class ControlPackage:
250    version: str
251    platform: str
252    url: str
253    format: str
254    size: int
255    sha256: str
256    installed_bytes: int
257    entry: str = "strata.py"
258
259    @property
260    def label(self) -> str:
261        return f"control {self.version} {self.platform}"
262
263
264@dataclass(frozen=True)
265class AppRelease:
266    version: str
267    notes: str
268    pub_date: str
269    platforms: dict          # {platform: {"url", "signature", "sha256", "size", "format"?}}
270
271    def for_platform(self, platform: str) -> dict | None:
272        return self.platforms.get(platform)
273
274
275@dataclass
276class Feed:
277    sequence: int
278    channel: str
279    generated_at: str
280    expires_at: str | None
281    app: AppRelease | None
282    control: tuple[ControlPackage, ...]
283    engine: tuple[EnginePackage, ...]
284    source: str                    # where it was read from (the base for relative URLs)
285    key_id: str                    # who signed it
286    raw: bytes = field(default=b"", repr=False)
287    #: entries this Control does not know how to use (a platform, a backend or an archive format added after it was built): left out, one plain line each.
288    #: A feed with such an entry is still a feed; only an entry of a kind this Control knows and that is malformed refuses the feed.
289    skipped: tuple[str, ...] = ()
290    #: the DFlash2 drafter files (feed member ``drafters``, DrafterPackage): fetched by setup, `strata drafting fetch` and Load for a set that has one. Older Controls ignore the member.
291    drafters: tuple[DrafterPackage, ...] = ()
292    #: the models Strata lists after the built-in ones (feed member ``models``, FeedModel). An entry that is malformed is left out of this tuple with one plain line in
293    #: ``models_dropped`` (and the log); the rest of the feed, and the other models, work. Older Controls ignore the member.
294    models: tuple[FeedModel, ...] = ()
295    models_dropped: tuple[str, ...] = ()
296    #: the detached signature that went with ``raw`` (fetch fills it for a feed that has models: the cache of the model list keeps both)
297    signature: bytes = b""
298    #: the engines of model shapes (feed member ``shape_engines``, EnginePackage with ``shape``): a separate component for each shape, fetched when a model of that shape is
299    #: chosen (strata_control/shape_engine.py). Kept out of ``engine`` so that `strata update` never picks one as THE engine. Older Controls ignore the member.
300    shape_engines: tuple[EnginePackage, ...] = ()
301
302    def url(self, ref: str) -> str:
303        return transfer.resolve_ref(transfer.base_of(self.source), ref)
304
305
306# ---------------------------------------------------------------------------------------------- parsing
307
308def _time(value, what: str) -> dt.datetime:
309    try:
310        parsed = dt.datetime.fromisoformat(str(value).replace("Z", "+00:00"))
311    except ValueError:
312        raise FeedError(f"the feed's {what} is not a timestamp") from None
313    return parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.timezone.utc)
314
315
316def _skipping(skipped: list | None, what: str, reason: str) -> None:
317    if skipped is None:                                  # a caller that wants the strict reading
318        raise FeedError(f"the update feed lists {what}, {reason}")
319    skipped.append(f"The update feed lists {what}, {reason}: skipped (a newer Strata may use it).")
320
321
322def _engine_package(item: dict, skipped: list | None = None) -> EnginePackage | None:
323    if not isinstance(item, dict):
324        raise FeedError("an engine entry in the feed is not an object")
325    where = f"engine entry {item.get('version')!r}"
326    version = _need(item, "version", str, where)
327    version_key(version)
328    platform = _need(item, "platform", str, where)
329    backend = _need(item, "backend", str, where)
330    label = f"{version} {platform}-{backend}" + (f"-{item['variant']}" if item.get("variant") else "")
331    if platform not in PLATFORMS:
332        _skipping(skipped, f"engine {label}", f"for a platform this Strata does not know ({platform})")
333        return None
334    if backend not in BACKEND_MATRIX:
335        _skipping(skipped, f"engine {label}", f"for a backend this Strata does not know ({backend})")
336        return None
337    archs = item.get("archs")
338    if not isinstance(archs, list) or not all(isinstance(a, str) and a for a in archs) or (backend != "cpu" and not archs):
339        raise FeedError(f"the feed's {where} needs a list of archs")
340    driver = item.get("min_driver") or {}
341    if not isinstance(driver, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in driver.items()):
342        raise FeedError(f"the feed's {where} has an invalid min_driver")
343    fmt = _need(item, "format", str, where)
344    if fmt not in FORMATS:
345        _skipping(skipped, f"engine {label}", f"in an archive format this Strata does not know ({fmt})")
346        return None
347    size = _need(item, "size", int, where)
348    installed = _need(item, "installed_bytes", int, where)
349    if size <= 0 or installed <= 0:
350        raise FeedError(f"the feed's {where} declares a size that cannot be a real file")
351    runtime = item.get("min_runtime")
352    if runtime is not None:
353        version_key(runtime)
354    return EnginePackage(version=version, platform=platform, backend=backend, variant=str(item.get("variant") or ""),
355                         archs=tuple(archs), min_driver=dict(driver), min_runtime=runtime,
356                         build_id=_need(item, "build_id", str, where), url=_need(item, "url", str, where), format=fmt,
357                         size=size, sha256=_hex(item.get("sha256"), where),
358                         manifest_sha256=_hex(item.get("manifest_sha256"), where), installed_bytes=installed,
359                         notes=str(item.get("notes") or ""))
360
361
362def _shape_engine_package(item: dict, skipped: list | None = None) -> EnginePackage | None:
363    """An entry of ``shape_engines``: an engine entry that names its model shape. An entry whose shape is not a name this Control accepts is left out like any entry of a kind it
364    does not know (a newer Strata may use it)."""
365    if not isinstance(item, dict):
366        raise FeedError("a shape engine entry in the feed is not an object")
367    shape = item.get("shape")
368    if not shape_engine.valid(shape):
369        _skipping(skipped, f"an engine for the model shape {shape!r}", "a shape name this Strata does not accept")
370        return None
371    pkg = _engine_package(item, skipped)
372    return dataclasses.replace(pkg, shape=shape) if pkg is not None else None
373
374
375def _control_package(item: dict, version: str, skipped: list | None = None) -> ControlPackage | None:
376    where = "control entry"
377    platform = _need(item, "platform", str, where)
378    if platform not in PLATFORMS:
379        _skipping(skipped, f"Control {version} {platform}", "for a platform this Strata does not know")
380        return None
381    fmt = _need(item, "format", str, where)
382    if fmt not in FORMATS:
383        _skipping(skipped, f"Control {version} {platform}", f"in an archive format this Strata does not know ({fmt})")
384        return None
385    size, installed = _need(item, "size", int, where), _need(item, "installed_bytes", int, where)
386    if size <= 0 or installed <= 0:
387        raise FeedError("the feed's control entry declares a size that cannot be a real file")
388    return ControlPackage(version=version, platform=platform, url=_need(item, "url", str, where), format=fmt,
389                          size=size, sha256=_hex(item.get("sha256"), where), installed_bytes=installed,
390                          entry=str(item.get("entry") or "strata.py"))
391
392
393def _drafter_package(item: dict) -> DrafterPackage:
394    if not isinstance(item, dict):
395        raise FeedError("a drafter entry in the feed is not an object")
396    where = f"drafter entry {item.get('name')!r}"
397    name = _need(item, "name", str, where)
398    if "/" in name or "\\" in name or name.startswith("."):
399        raise FeedError(f"the feed's {where} has a name that is not a plain file name")
400    size = _need(item, "size", int, where)
401    if size <= 0:
402        raise FeedError(f"the feed's {where} declares a size that cannot be a real file")
403    backends = item.get("backends")
404    if not isinstance(backends, list) or not backends or not all(isinstance(b, str) and b for b in backends):
405        raise FeedError(f"the feed's {where} needs a list of backends")
406    return DrafterPackage(name=name, version=str(item.get("version") or ""), url=_need(item, "url", str, where), size=size,
407                          sha256=_hex(item.get("sha256"), where), backends=tuple(backends), base=str(item.get("base") or ""),
408                          licence=str(item.get("licence") or ""), notes=str(item.get("notes") or ""))
409
410
411def _model_text(item: dict, key: str, where: str, *, limit: int = 400, required: bool = True) -> str:
412    value = item.get(key)
413    if value is None and not required:
414        return ""
415    if not isinstance(value, str) or (required and not value.strip()) or len(value) > limit or any(ord(c) < 32 for c in value):
416        raise FeedError(f"{where} has no valid {key}")
417    return value.strip()
418
419
420def _model_file(item, where: str) -> ModelFile:
421    if not isinstance(item, dict):
422        raise FeedError(f"{where} lists a file that is not an object")
423    name = _need(item, "name", str, where)
424    if "/" in name or "\\" in name or name.startswith(".") or not name.lower().endswith(".gguf"):
425        raise FeedError(f"{where} has a file name that is not a plain .gguf name")
426    size = _need(item, "size", int, where)
427    if size <= 0:
428        raise FeedError(f"{where} declares a size that cannot be a real file")
429    path = item.get("path")
430    if path is not None:
431        if not isinstance(path, str) or not path or path.startswith(("/", ".")) or "\\" in path or ".." in path.split("/") or path.rsplit("/", 1)[-1] != name:
432            raise FeedError(f"{where} has a file path that does not end in the file's name")
433    return ModelFile(name=name, size=size, sha256=_hex(item.get("sha256"), where), path=path or "")
434
435
436def _number(value, low: float, high: float) -> bool:
437    return isinstance(value, (int, float)) and not isinstance(value, bool) and low <= value <= high
438
439
440def _model_entry(item) -> FeedModel:
441    """One ``models`` entry, strictly: any fault raises FeedError (the caller drops that entry and goes on with the next)."""
442    if not isinstance(item, dict):
443        raise FeedError("a model entry in the feed is not an object")
444    ident = item.get("id")
445    where = f"model entry {ident!r}"
446    if not isinstance(ident, str) or not _MODEL_ID.fullmatch(ident) or ident.endswith(("-", ".")):
447        raise FeedError(f"the feed's {where} has no valid id")
448    family = _need(item, "family", str, where)
449    if not _MODEL_FAMILY.fullmatch(family):
450        raise FeedError(f"the feed's {where} has no valid family")
451    if family.startswith(shape_engine.FAMILY_PREFIX) and shape_engine.shape_of_family(family) is None:
452        raise FeedError(f"the feed's {where} names a model shape that is not a valid name ({family[len(shape_engine.FAMILY_PREFIX):]!r})")
453    repo = _need(item, "repo", str, where)
454    revision = _need(item, "revision", str, where)
455    if not _MODEL_REPO.fullmatch(repo) or ".." in repo:
456        raise FeedError(f"the feed's {where} has no valid repo")
457    if not _MODEL_REVISION.fullmatch(revision):
458        raise FeedError(f"the feed's {where} needs the repository's pinned revision (40 hex digits)")
459    licence_url = _need(item, "licence_url", str, where)
460    if not licence_url.startswith("https://") or any(c.isspace() for c in licence_url):
461        raise FeedError(f"the feed's {where} needs an https licence_url")
462    drafter = item.get("drafter", "none")
463    if drafter not in MODEL_DRAFTERS:
464        raise FeedError(f"the feed's {where} has an unknown drafter {drafter!r}")
465    context = item.get("context", 0)
466    if not isinstance(context, int) or isinstance(context, bool) or context < 0 or context > 4194304:
467        raise FeedError(f"the feed's {where} has no valid context")
468    min_engine = item.get("min_engine", "")
469    if min_engine:
470        version_key(min_engine)
471    pictures = item.get("pictures", False)
472    if not isinstance(pictures, bool):
473        raise FeedError(f"the feed's {where} has no valid pictures flag")
474    mmproj = _model_file(item["mmproj"], f"the feed's {where}") if item.get("mmproj") is not None else None
475    if pictures and mmproj is None:
476        raise FeedError(f"the feed's {where} offers pictures but lists no mmproj file")
477    raw_quants = item.get("quants")
478    if not isinstance(raw_quants, list) or not raw_quants:
479        raise FeedError(f"the feed's {where} lists no quants")
480    quants, seen_q, seen_f = [], set(), set()
481    for q in raw_quants:
482        if not isinstance(q, dict):
483            raise FeedError(f"the feed's {where} has a quant that is not an object")
484        qname = q.get("name")
485        if not isinstance(qname, str) or not _MODEL_QUANT.fullmatch(qname) or qname in seen_q:
486            raise FeedError(f"the feed's {where} has a quant without a valid, unique name")
487        seen_q.add(qname)
488        qwhere = f"the feed's {where} quant {qname!r}"
489        files = q.get("files")
490        if not isinstance(files, list) or not files:
491            raise FeedError(f"{qwhere} lists no files")
492        parsed = tuple(_model_file(f, qwhere) for f in files)
493        if len({f.name for f in parsed}) != len(parsed):
494            raise FeedError(f"{qwhere} lists a file twice")
495        for f in parsed:
496            if f.name in seen_f:
497                raise FeedError(f"{qwhere} reuses the file name {f.name!r} of another quant")
498            seen_f.add(f.name)
499        if not _number(q.get("ram_gb"), 0.001, 4096) or not _number(q.get("arena_gb", 0), 0, 4096):
500            raise FeedError(f"{qwhere} has no valid ram_gb or arena_gb")
501        quants.append(ModelQuant(name=qname, about=_model_text(q, "about", qwhere, required=False), ram_gb=float(q["ram_gb"]),
502                                 arena_gb=float(q.get("arena_gb", 0)), files=parsed))
503    if mmproj is not None and mmproj.name in seen_f:
504        raise FeedError(f"the feed's {where} uses the mmproj file name for a model file")
505    kv = item.get("kv_bytes_per_token", 0)
506    drafts = item.get("mtp_drafts", 2 if drafter == "mtp" else 0)
507    state = item.get("state_gb", 0)
508    if not isinstance(kv, int) or isinstance(kv, bool) or kv < 0 or not isinstance(drafts, int) or isinstance(drafts, bool) or not 0 <= drafts <= 8 \
509            or not _number(state, 0, 64):
510        raise FeedError(f"the feed's {where} has an invalid kv_bytes_per_token, mtp_drafts or state_gb")
511    if family == "qwen35moe" and kv <= 0:
512        raise FeedError(f"the feed's {where} (family qwen35moe) needs kv_bytes_per_token")
513    here = f"the feed's {where}"
514    return FeedModel(id=ident, title=_model_text(item, "title", here, limit=80), by=_model_text(item, "by", here, limit=160),
515                     about=_model_text(item, "about", here, limit=400, required=False),
516                     licence=_model_text(item, "licence", here, limit=120), licence_url=licence_url, family=family, repo=repo,
517                     revision=revision, quants=tuple(quants), mmproj=mmproj, pictures=pictures, drafter=drafter, context=context, min_engine=min_engine,
518                     kv_bytes_per_token=kv, mtp_drafts=drafts, state_gb=float(state))
519
520
521def _models_member(raw) -> tuple[list[FeedModel], list[str]]:
522    """The ``models`` member, leniently by entry: (the models that are well-formed, one plain line for each entry left out). A member that is not the
523    expected shape is ignored whole, with a line. Nothing here refuses the feed."""
524    dropped: list[str] = []
525    if raw is None:
526        return [], dropped
527    if not isinstance(raw, dict) or not isinstance(raw.get("packages"), list):
528        dropped.append("The update feed's models member is not a list of models: ignored.")
529        _log.warning(dropped[-1])
530        return [], dropped
531    out: list[FeedModel] = []
532    for item in raw["packages"]:
533        try:
534            model = _model_entry(item)
535        except FeedError as exc:
536            label = item.get("id") if isinstance(item, dict) else None
537            dropped.append(f"The update feed lists a model ({label!r}) that is not well-formed, so it is skipped: {exc}")
538            _log.warning(dropped[-1])
539            continue
540        if any(m.id == model.id for m in out):
541            dropped.append(f"The update feed lists the model {model.id!r} twice: the second one is skipped.")
542            _log.warning(dropped[-1])
543            continue
544        out.append(model)
545    return out, dropped
546
547
548def parse(payload: bytes, *, source: str, key_id: str) -> Feed:
549    """The feed document, strictly. Unknown members are ignored; missing or mistyped ones are errors."""
550    try:
551        data = json.loads(payload.decode("utf-8-sig"))
552    except (ValueError, UnicodeError):
553        raise FeedError("the update feed is not valid JSON") from None
554    if not isinstance(data, dict) or data.get("schema_version") != SCHEMA_VERSION:
555        raise FeedError("the update feed has an unsupported schema_version")
556    sequence = data.get("sequence")
557    if type(sequence) is not int or sequence < 0:
558        raise FeedError("the update feed has no sequence number")
559    channel = _need(data, "channel", str, "header")
560    generated = _need(data, "generated_at", str, "header")
561    _time(generated, "generated_at")
562    expires = data.get("expires_at")
563    if expires is not None:
564        _time(expires, "expires_at")
565    skipped: list = []
566    app = None
567    raw_app = data.get("app")
568    if raw_app is not None:
569        if not isinstance(raw_app, dict):
570            raise FeedError("the feed's app member is not an object")
571        app_version_key(_need(raw_app, "version", str, "app entry"))
572        platforms = raw_app.get("platforms")
573        if not isinstance(platforms, dict) or not platforms:
574            raise FeedError("the feed's app entry lists no platforms")
575        parsed_platforms = {}
576        by_tauri = {v: k for k, v in TAURI_TARGETS.items()}
577        for target, entry in platforms.items():
578            plat = by_tauri.get(str(target).split("-nsis")[0].split("-msi")[0])
579            if plat is None:
580                _skipping(skipped, f"the app for {target}", "a platform this Strata does not know")
581                continue
582            if not isinstance(entry, dict):
583                raise FeedError(f"the feed's app entry for {target!r} is not an object")
584            parsed_platforms[plat] = {"url": _need(entry, "url", str, "app entry"),
585                                      "signature": _need(entry, "signature", str, "app entry"),
586                                      "sha256": _hex(entry.get("sha256"), "app entry"),
587                                      "size": _need(entry, "size", int, "app entry"), "target": target}
588        app = AppRelease(version=raw_app["version"], notes=str(raw_app.get("notes") or ""),
589                         pub_date=str(raw_app.get("pub_date") or ""), platforms=parsed_platforms)
590    control = []
591    raw_control = data.get("control")
592    if raw_control is not None:
593        if not isinstance(raw_control, dict):
594            raise FeedError("the feed's control member is not an object")
595        cver = _need(raw_control, "version", str, "control entry")
596        version_key(cver)
597        control = [c for c in (_control_package(item, cver, skipped) for item in (raw_control.get("packages") or [])) if c is not None]
598    engine = []
599    raw_engine = data.get("engine")
600    if raw_engine is not None:
601        if not isinstance(raw_engine, dict) or not isinstance(raw_engine.get("packages"), list):
602            raise FeedError("the feed's engine member lists no packages")
603        engine = [e for e in (_engine_package(item, skipped) for item in raw_engine["packages"]) if e is not None]
604        seen = set()
605        for pkg in engine:
606            ident = (pkg.version, pkg.platform, pkg.backend, pkg.variant)
607            if ident in seen:
608                raise FeedError(f"the feed lists engine {pkg.label} twice")
609            seen.add(ident)
610    # (the member "dsv41", the DeepSeek-V4.1 engine packages of Strata 0.2.13 and earlier, may still be in the feed for those versions, frozen;
611    # this Control runs no DeepSeek model and does not read it)
612    shapes = []
613    raw_shapes = data.get("shape_engines")
614    if raw_shapes is not None:
615        if not isinstance(raw_shapes, dict) or not isinstance(raw_shapes.get("packages"), list):
616            raise FeedError("the feed's shape_engines member lists no packages")
617        shapes = [e for e in (_shape_engine_package(item, skipped) for item in raw_shapes["packages"]) if e is not None]
618        seen = set()
619        for pkg in shapes:
620            ident = (pkg.shape, pkg.version, pkg.platform, pkg.backend, pkg.variant)
621            if ident in seen:
622                raise FeedError(f"the feed lists the engine for {pkg.shape} {pkg.label} twice")
623            seen.add(ident)
624    drafters = []
625    raw_drafters = data.get("drafters")
626    if raw_drafters is not None:
627        if not isinstance(raw_drafters, dict) or not isinstance(raw_drafters.get("packages"), list):
628            raise FeedError("the feed's drafters member lists no packages")
629        drafters = [_drafter_package(item) for item in raw_drafters["packages"]]
630        if len({d.name for d in drafters}) != len(drafters):
631            raise FeedError("the feed lists a drafter twice")
632    models, models_dropped = _models_member(data.get("models"))
633    return Feed(sequence=sequence, channel=channel, generated_at=generated, expires_at=expires, app=app,
634                control=tuple(control), engine=tuple(engine), source=source, key_id=key_id, raw=payload,
635                skipped=tuple(skipped), drafters=tuple(drafters), models=tuple(models), models_dropped=tuple(models_dropped), shape_engines=tuple(shapes))
636
637
638def _expired_words(expires_at: str, now: dt.datetime, server_now: dt.datetime | None) -> str:
639    """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."""
640    fix = "Set the date and time right (Windows: Settings, Time & language, Date & time, Set time automatically) and try again."
641    if server_now is not None:
642        off = abs((server_now - now).total_seconds())
643        if off > 15 * 60 and _time(expires_at, "expires_at") >= server_now:
644            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}, "
645                    f"so the update feed looks expired. {fix}")
646    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. "
647            f"{fix} Otherwise the update source needs to publish a new feed; nothing was downloaded.")
648
649
650def verify_and_parse(payload: bytes, signature_bytes: bytes, *, source: str, trusted: dict[str, bytes],
651                     last_sequence: int | None = None, channel: str | None = None,
652                     now: dt.datetime | None = None, server_now: dt.datetime | None = None) -> Feed:
653    """Check the signature over `payload`, then parse; then the three guards: the channel is the one asked for, the feed has
654    not expired, and its sequence is not lower than the last one accepted (a replayed older feed is a downgrade)."""
655    if not trusted:
656        raise FeedError("this build trusts no update key (update_keys.json is empty and STRATA_UPDATE_TRUSTED_KEYS is not set), "
657                        "so no update can be verified; nothing was downloaded")
658    try:
659        signature = json.loads(signature_bytes.decode("utf-8-sig"))
660    except (ValueError, UnicodeError):
661        raise FeedError("the update feed's signature file is not valid") from None
662    try:
663        key_id = signing.verify_bytes(trusted, payload, signature)
664    except signing.SignatureError as exc:
665        raise FeedError(f"the update feed is not trusted: {exc}") from None
666    feed = parse(payload, source=source, key_id=key_id)
667    if channel and feed.channel != channel:
668        raise FeedError(f"the feed is for the {feed.channel!r} channel, this PC follows {channel!r}")
669    now = now or dt.datetime.now(dt.timezone.utc)
670    if feed.expires_at and _time(feed.expires_at, "expires_at") < now:
671        raise FeedError(_expired_words(feed.expires_at, now, server_now))
672    if last_sequence is not None and feed.sequence < last_sequence:
673        down = FeedDowngrade(f"the update feed is older than the one already accepted (sequence {feed.sequence} < {last_sequence}); "
674                             "refusing a replayed feed")
675        down.sequence, down.accepted = feed.sequence, last_sequence
676        raise down
677    return feed
678
679
680def feed_name(platform: str | None = None) -> str:
681    """The feed file this machine reads from a folder or a release address: ``strata-feed-linux-aarch64.json`` on a Linux ARM64 machine, else
682    ``strata-feed.json``. A source that names its file (``.../x.json``) is used as given, whatever the machine."""
683    if platform is None:
684        try:
685            platform = host_platform()
686        except Exception:                                             # noqa: BLE001 - an unknown OS reads the common feed
687            platform = None
688    return AARCH64_FEED_NAME if platform == "linux-aarch64" else FEED_NAME
689
690
691def fetch(source: str, trusted: dict[str, bytes], *, timeout: float = 30, say=None, automatic: bool = False, **guards) -> Feed:
692    """Read the feed and its signature from `source` (an https URL, a loopback http URL, a file URL or a folder/file path).  `automatic`: a read
693    nobody asked for by name (strata_control/netpolicy.py rule 4b: a host that refused within the last hours is not asked again)."""
694    if not trusted:
695        raise FeedError("this build trusts no update key (update_keys.json is empty and STRATA_UPDATE_TRUSTED_KEYS is not set), "
696                        "so no update can be verified; nothing was downloaded")
697    location = source
698    if transfer.kind_of(source) == "path":
699        path = transfer._local_path(source)
700        if path.is_dir():
701            location = str(path / feed_name())
702            if not (path / feed_name()).is_file() and (path / FEED_NAME).is_file():
703                location = str(path / FEED_NAME)                 # a local folder made for the common feed (a test feed, an offline copy)
704    elif transfer.kind_of(source) in ("http", "https") and not source.rsplit("/", 1)[-1].endswith(".json"):
705        location = source.rstrip("/") + "/" + feed_name()
706    try:
707        payload = transfer.read_small(location, timeout=timeout, say=say, automatic=automatic)
708        signature = transfer.read_small(location + SIGNATURE_SUFFIX, timeout=timeout, say=say, automatic=automatic)
709    except transfer.Unreachable as exc:
710        f = exc.failure                                  # the network rule (W7 and its two companions): the host, and that nothing installed is lost
711        key = {"offline": "update_offline", "again": "update_again"}.get(f.kind, "update_no_answer")
712        raise FeedUnreachable(netpolicy.WORDS[key].format(host=f.host, seconds=max(1, int(round(f.seconds)))), 6) from None
713    except transfer.TransferError as exc:
714        raise FeedError(f"the update feed could not be read: {exc}", 6) from None
715    guards.setdefault("server_now", transfer.server_date())
716    loaded = verify_and_parse(payload, signature, source=location, trusted=trusted, **guards)
717    return dataclasses.replace(loaded, signature=signature) if loaded.models else loaded
718
719
720# ---------------------------------------------------------------------------------------------- hardware and selection
721
722def gfx_covers(archs, present: list[str]) -> bool:
723    """HIP: the build holds machine code for at least one of the installed AMD GPUs (``gfx1201``). Unknown GPUs: not a refusal."""
724    if not present:
725        return True
726    return any(a in present for a in archs)
727
728
729def engine_fit_reasons(pkg: EnginePackage, hardware: dict) -> list[str]:
730    """Why `pkg` cannot run on the machine `hardware` describes; empty when it fits. `hardware` is what
731    `updater.detect_hardware()` returns: platform, backend, nvidia driver, cuda archs, gfx names, runtime version."""
732    from strata_control import engine_component as ec
733    reasons = []
734    if pkg.platform != hardware["platform"]:
735        reasons.append(f"{pkg.label} is for {pkg.platform}, this PC is {hardware['platform']}")
736        return reasons
737    wanted = hardware.get("backend") or "cpu"
738    if pkg.backend != wanted:
739        reasons.append(f"{pkg.label} is a {pkg.backend} engine, this PC needs {wanted}")
740        return reasons
741    runtime = hardware.get("runtime")
742    if pkg.min_runtime and runtime and ec._version_key(runtime) < ec._version_key(pkg.min_runtime):
743        reasons.append(f"{pkg.label} needs control {pkg.min_runtime} or newer, this is {runtime}")
744    cuda_archs = tuple(a for a in pkg.archs if a.startswith(("sm_", "compute_")))
745    if pkg.backend == "cuda" and cuda_archs and hardware.get("cuda_archs") and not ec.arch_covers(cuda_archs, hardware["cuda_archs"]):
746        reasons.append(f"{pkg.label} has code for {', '.join(cuda_archs)}, this PC's GPU is {', '.join(hardware['cuda_archs'])}")
747    if pkg.backend == "hip" and not gfx_covers(pkg.archs, hardware.get("gfx") or []):
748        reasons.append(f"{pkg.label} has code for {', '.join(pkg.archs)}, this PC's GPU is {', '.join(hardware['gfx'])}")
749    need, have = pkg.min_driver.get("nvidia"), hardware.get("nvidia_driver")
750    if pkg.backend == "cuda" and need and have and ec._version_key(have) < ec._version_key(need):
751        reasons.append(f"{pkg.label} needs NVIDIA driver {need} or newer, this PC has {have}")
752    return reasons
753
754
755def select_engine(packages, hardware: dict) -> tuple[EnginePackage | None, list[str]]:
756    """The best package for this PC and, when none fits, every reason. Best = newest version; with equal versions the build
757    that needs the newer driver (CUDA 13 beside CUDA 12), as `engine_component.resolve` chooses between installed ones."""
758    from strata_control import engine_component as ec
759    fitting, reasons = [], []
760    for pkg in packages:
761        why = engine_fit_reasons(pkg, hardware)
762        if why:
763            reasons.extend(why)
764        else:
765            fitting.append(pkg)
766    if not fitting:
767        return None, reasons
768    fitting = _settle_hip_variants(fitting, hardware, reasons)
769    if not fitting:
770        return None, reasons
771    best = max(fitting, key=lambda p: (version_key(p.version), ec._version_key(p.min_driver.get("nvidia", "0")),
772                                       ec.hip_preference(p.archs) if p.backend == "hip" else 1,
773                                       ec.arch_native(p.archs, hardware.get("cuda_archs") or []) if p.backend == "cuda" else False))
774    kept = str(hardware.get("installed_variant") or "")
775    if best.backend == "cuda" and kept and best.variant != kept:
776        # 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
777        # 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.
778        same = [p for p in fitting if p.backend == "cuda" and p.variant == kept and version_key(p.version) == version_key(best.version)]
779        if same:
780            reasons.append(f"the installed {kept} build is kept; {best.variant} would also fit another card in this PC")
781            best = same[0]
782    return best, reasons
783
784
785def _hip_variants(fitting) -> set[str]:
786    return {p.variant for p in fitting if p.backend == "hip"}
787
788
789def _settle_hip_variants(fitting: list, hardware: dict, reasons: list[str]) -> list:
790    """Several HIP builds "fit" only when this PC's gfx is unknown (an empty list fits everything). Version must never decide
791    between them: the newest build of the wrong card family would be refused at its test start. Order of evidence: the variant asked
792    for, the GPU's name, the variant already installed (an update never switches card family), then give up with a plain reason."""
793    if hardware.get("backend") != "hip" or hardware.get("gfx"):
794        return fitting
795    hip = [p for p in fitting if p.backend == "hip"]
796    if len({p.variant for p in hip}) < 2:
797        return fitting
798    from strata_control import engine_component as ec
799    chosen, why = [], ""
800    wanted = str(hardware.get("variant_wanted") or "").lower()
801    if wanted:
802        chosen = [p for p in hip if p.variant.lower() == wanted]
803        why = f"the {wanted} build was asked for"
804    if not chosen:
805        guesses = {g for g in (ec.gfx_from_name(n) for n in hardware.get("gpu_names") or []) if g}
806        chosen = [p for p in hip if any(a in guesses for a in p.archs)]
807        why = f"the GPU name ({', '.join(hardware.get('gpu_names') or [])}) is a {', '.join(sorted(guesses))}" if chosen else ""
808    if not chosen and hardware.get("installed_variant"):
809        chosen = [p for p in hip if p.variant == hardware["installed_variant"]]
810        why = f"the installed {hardware['installed_variant']} build is kept, this PC's AMD card could not be identified"
811    if not chosen:
812        reasons.append("Strata cannot tell which AMD build this PC needs (" + ", ".join(sorted(_hip_variants(hip))) +
813                       "); the card was not recognised, so nothing was chosen. Name the build with STRATA_ENGINE_BACKEND=hip-<build>")
814        return [p for p in fitting if p.backend != "hip"]
815    reasons.append(f"several AMD builds fit; chose {chosen[0].variant}: {why}")
816    return [p for p in fitting if p.backend != "hip" or p in chosen]