ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.
Python ai-agentsamdcomfyuidockerllama-cppllmlocal-ain8nnvidiaopen-webuiragself-hostedspeech-to-textstrix-halotext-to-speechworkflow-automation
feat(comfyui): adding ComfyUI from Extensions downloads its model (#8204)
Mike Bradley0f454cca34d0
diff --git a/ods/bin/extension_assets.py b/ods/bin/extension_assets.pynew file mode 100644index 000000000..eed91738c--- /dev/null+++ b/ods/bin/extension_assets.py@@ -0,0 +1,364 @@+"""Model files an extension's container reads that are not part of its image.++An extension may ship ``model-packs.json`` beside its manifest. Each pack lists+files with a pinned HTTPS URL, SHA-256 and size; ``model_root`` names, for each+GPU backend, the folder under the install directory that the extension's+container reads its models from. The host agent's prepare step (adding the+extension from the Extensions page) and the installer both fetch the default+packs here, so the container never starts without its model.++A file is downloaded to ``<name>.part``, resumed with an HTTP range request,+checked against its SHA-256 and only then renamed into place. A file already+in place with the pinned size counts as present; it was checked when fetched.++Standard library only: the installer runs this with the host's python3.+"""+from __future__ import annotations++import argparse+import contextlib+import errno+import hashlib+import http.client+import json+import os+import re+import shlex+import shutil+import ssl+import sys+import time+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass+from pathlib import Path, PurePosixPath+from typing import Callable, Iterator++try:+ import fcntl+except ImportError: # Windows; see _folder_lock+ fcntl = None++PACKS_FILE = "model-packs.json"+SCHEMA = "ods.model-packs.v1"+CHUNK_BYTES = 1 << 20+READ_TIMEOUT_SECONDS = 60+USER_AGENT = "ODS-extension-assets/1"+# The rule the host agent applies to model downloads (_download_disk_margin).+MARGIN_MIN_BYTES = 2 * 1024 ** 3+MARGIN_FRACTION = 0.05+_PLAIN_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")+_SHA256 = re.compile(r"[0-9a-f]{64}")+# flock errors that mean "this file system has no locks", not "someone holds it".+_NO_LOCKS = {errno.ENOLCK, errno.EOPNOTSUPP, errno.ENOTSUP, errno.ENOSYS, errno.EINVAL}+++class AssetError(Exception):+ """A pack file that could not be prepared; the message is for the owner.++ ``retryable`` marks a dropped connection, where trying again resumes.+ """++ def __init__(self, message: str, *, retryable: bool = False):+ super().__init__(message)+ self.retryable = retryable+++@dataclass(frozen=True)+class PackFile:+ pack_id: str+ label: str+ url: str+ sha256: str+ size: int+ target: Path+++def default_files(ext_dir: Path, install_dir: Path, backend: str) -> list[PackFile]:+ """The files of the default packs for ``backend``; empty when there are none."""+ path = ext_dir / PACKS_FILE+ if not path.is_file():+ return []+ doc = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(doc, dict) or doc.get("schema") != SCHEMA:+ raise ValueError(f"{path}: schema must be {SCHEMA}")+ try:+ return _parse(path, doc, install_dir.resolve(), backend)+ except (KeyError, TypeError, AttributeError) as exc:+ raise ValueError(f"{path}: malformed pack list ({type(exc).__name__}: {exc})") from exc+++def _parse(path: Path, doc: dict, install: Path, backend: str) -> list[PackFile]:+ root_name = doc["model_root"].get(backend)+ if root_name is None:+ return []+ # Checked by name, not resolved: a data folder linked to another disk is+ # the owner's layout, while a pack list may not climb out of the install.+ parts = PurePosixPath(root_name).parts if isinstance(root_name, str) else ()+ if not parts or not all(_PLAIN_NAME.fullmatch(part) for part in parts):+ raise ValueError(f"{path}: model_root for {backend} must be a relative path of plain names")+ root = install.joinpath(*parts)+ files = []+ for pack in doc["packs"]:+ if pack.get("default") is not True:+ continue+ for item in pack["files"]:+ names = (item["subdir"], item["file"])+ if not all(isinstance(name, str) and _PLAIN_NAME.fullmatch(name) for name in names):+ raise ValueError(f"{path}: {names} must be plain names")+ if not item["url"].startswith("https://") or not _SHA256.fullmatch(item["sha256"]):+ raise ValueError(f"{path}: {item['file']} needs an https URL and a lowercase SHA-256")+ if not isinstance(item["bytes"], int) or isinstance(item["bytes"], bool) or item["bytes"] <= 0:+ raise ValueError(f"{path}: {item['file']} needs its size in bytes")+ files.append(PackFile(pack["id"], pack["label"], item["url"], item["sha256"],+ item["bytes"], root / item["subdir"] / item["file"]))+ return files+++def missing(files: list[PackFile]) -> list[PackFile]:+ """The files not yet in place with their pinned size."""+ return [item for item in files+ if not (item.target.is_file() and item.target.stat().st_size == item.size)]+++def margin_bytes(needed: int) -> int:+ return max(MARGIN_MIN_BYTES, int(needed * MARGIN_FRACTION))+++def check_space(files: list[PackFile]) -> None:+ """Refuse before downloading when the disk cannot hold the files plus a margin."""+ if not files:+ return+ needed = sum(_remaining(item) for item in files)+ folder = files[0].target.parent+ while not folder.exists():+ folder = folder.parent+ free = shutil.disk_usage(folder).free+ if free < needed + margin_bytes(needed):+ raise AssetError(+ f"Not enough free disk for {files[0].label}: it needs {_gb(needed)} GB plus "+ f"{_gb(margin_bytes(needed))} GB to spare, and {folder} has {_gb(free)} GB free. "+ "Free some space, then try again.")+++def fetch(item: PackFile, report: Callable[[int], None], *,+ opener: Callable | None = None) -> None:+ """Download one file into place, resuming a partial download.++ Every failure is an AssetError that says what to do next.+ """+ opener = opener or urllib.request.urlopen+ folder = item.target.parent+ try:+ folder.mkdir(parents=True, exist_ok=True)+ with _folder_lock(folder, item):+ if not missing([item]): # finished meanwhile, by the installer's download say+ return+ _download(item, report, opener)+ except PermissionError as exc:+ raise _not_writable(item, exc) from exc+ except OSError as exc: # the disk: _request and _read turn network errors into AssetError+ raise AssetError(f"ODS could not save {item.label} in {folder} ({_reason(exc)}). "+ "Fix that, then try again; the part already downloaded is kept.") from exc+++def _download(item: PackFile, report: Callable[[int], None], opener: Callable) -> None:+ part = item.target.with_name(item.target.name + ".part")+ with open(part, "a+b") as out:+ done = out.seek(0, os.SEEK_END)+ if done > item.size: # not this file: start over+ out.truncate(0)+ done = 0+ # A part already at full size (the rename failed last time) is only checked.+ if done < item.size:+ with _request(item, out, done, opener) as response:+ if done and response.status != 206: # the server sent the whole file again+ out.truncate(0)+ done = 0+ # Never more than the pinned size, whatever the server sends.+ for chunk in iter(lambda: _read(item, response, item.size - done), b""):+ out.write(chunk)+ done += len(chunk)+ report(done)+ if done != item.size:+ raise AssetError(f"The download of {item.label} ended at {_gb(done)} of {_gb(item.size)} GB. "+ "Try again to resume it.", retryable=True)+ # The bytes on disk are what gets renamed, so they are what is checked:+ # without a lock (Windows, or a curl run by hand) another writer may+ # have appended to the same part.+ out.flush()+ verified = os.fstat(out.fileno()).st_size == item.size and _sha256(out) == item.sha256+ if not verified:+ part.unlink()+ raise AssetError(f"{item.label} did not match its pinned SHA-256, so it was deleted. "+ "Try again to download it once more.")+ os.replace(part, item.target)+++def _sha256(handle) -> str:+ handle.seek(0)+ digest = hashlib.sha256()+ for chunk in iter(lambda: handle.read(CHUNK_BYTES), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _request(item: PackFile, out, offset: int, opener: Callable):+ headers = {"User-Agent": USER_AGENT}+ if offset:+ headers["Range"] = f"bytes={offset}-"+ host = urllib.parse.urlsplit(item.url).netloc+ try:+ return opener(urllib.request.Request(item.url, headers=headers),+ timeout=READ_TIMEOUT_SECONDS)+ except urllib.error.HTTPError as exc:+ if exc.code == 416: # the server's copy is shorter than the part, so it cannot resume+ out.truncate(0)+ raise AssetError(f"The server's copy of {item.label} is not the pinned file, so the partial "+ "download was discarded. Try again to download it from the start.") from exc+ if exc.code in (408, 429) or exc.code >= 500:+ raise _interrupted(item, exc) from exc+ if exc.code in (404, 410):+ raise AssetError(f"The download link for {item.label} no longer works (HTTP {exc.code}). "+ "Update ODS for a current link, or ask for help on Discord.") from exc+ raise AssetError(f"The server refused {item.label} (HTTP {exc.code} {exc.reason}). Check that "+ f"this machine can reach {host} (a proxy or firewall may block it), "+ "then try again.") from exc+ except (http.client.HTTPException, OSError) as exc: # URLError and timeouts are OSErrors+ if isinstance(getattr(exc, "reason", exc), ssl.SSLCertVerificationError):+ raise AssetError(f"ODS could not verify the HTTPS certificate of {host} ({_reason(exc)}). "+ "Check the system clock and any proxy that inspects HTTPS traffic, "+ "then try again.") from exc+ raise _interrupted(item, exc) from exc+++def _read(item: PackFile, response, limit: int) -> bytes:+ try:+ return response.read(min(CHUNK_BYTES, limit))+ except (http.client.HTTPException, OSError) as exc:+ raise _interrupted(item, exc) from exc+++def _folder_lock(folder: Path, item: PackFile) -> Iterator[None]:+ """Let one download at a time write into ``folder``.++ On Linux the installer's background download and the Extensions page can+ both start one. Windows has no fcntl; its installer fetches no packs and+ the host agent runs one prepare per extension at a time, and the final+ check of the bytes on disk catches any other writer.+ """+ if fcntl is None:+ yield+ return+ handle = os.open(folder, os.O_RDONLY)+ try:+ try:+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError as exc:+ raise AssetError(f"{item.label} is already downloading, started by the installer or an "+ "earlier add. Wait for it to finish, then try again.") from exc+ except OSError as exc:+ # Some file systems (often network ones) offer no locks; the+ # download then runs unguarded, and the final check still holds.+ if exc.errno not in _NO_LOCKS:+ raise+ yield+ finally:+ os.close(handle)+++def _interrupted(item: PackFile, exc: BaseException) -> AssetError:+ return AssetError(f"The download of {item.label} stopped ({_reason(exc)}). "+ "Try again to resume it; the part already downloaded is kept.", retryable=True)+++def _not_writable(item: PackFile, exc: OSError) -> AssetError:+ folder = item.target.parent+ while not folder.exists():+ folder = folder.parent+ if hasattr(os, "getuid") and not os.access(folder, os.W_OK) and folder.stat().st_uid != os.getuid():+ return AssetError(f"ODS cannot write {item.label} into {folder} ({_reason(exc)}). The folder "+ "belongs to another account, often a container that runs as root. To fix it, "+ f"run this, then try again: sudo chown -R {os.getuid()}:{os.getgid()} "+ f"{shlex.quote(str(folder))}")+ return AssetError(f"ODS cannot write {item.label} ({_reason(exc)}). Check that your account can write "+ f"to {folder} and that no other program, such as an antivirus or sync tool, is "+ "holding the file, then try again.")+++def _remaining(item: PackFile) -> int:+ """Bytes still to download; a part larger than the file starts over."""+ part = item.target.with_name(item.target.name + ".part")+ have = part.stat().st_size if part.is_file() else 0+ return item.size - have if have <= item.size else item.size+++def _reason(exc: BaseException) -> str:+ reason = getattr(exc, "reason", None) or exc+ return str(reason) or type(reason).__name__+++def _gb(count: int) -> str:+ return f"{count / 1e9:.1f}"+++def _fetch_with_attempts(item: PackFile, attempts: int, delay: float) -> None:+ step = [0]++ def report(done: int) -> None:+ percent = done * 100 // item.size+ if percent >= step[0] + 10:+ step[0] = percent - percent % 10+ print(f" {item.label}: {step[0]}%", flush=True)++ for attempt in range(1, attempts + 1):+ try:+ fetch(item, report)+ return+ except AssetError as exc:+ if not exc.retryable or attempt == attempts:+ raise+ # Only the error's kind here: the installer summary reads words like+ # "failed" in this log as a failure, even after a later try works.+ print(f" The connection dropped ({_kind(exc)}); resuming in {delay:g} s "+ f"(try {attempt + 1} of {attempts})", flush=True)+ time.sleep(delay)+++def _kind(exc: AssetError) -> str:+ cause = exc.__cause__+ if cause is None:+ return "ended early"+ reason = getattr(cause, "reason", None)+ return type(reason if isinstance(reason, BaseException) else cause).__name__+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="Fetch an extension's default model packs.")+ parser.add_argument("ext_dir", type=Path)+ parser.add_argument("install_dir", type=Path)+ parser.add_argument("backend")+ # The installer's unattended download keeps going through dropped+ # connections, as its curl --retry did; each try resumes the part.+ parser.add_argument("--attempts", type=int, default=1, help="tries per file; each resumes the last")+ parser.add_argument("--retry-delay", type=float, default=10.0, help="seconds between tries")+ args = parser.parse_args(argv)+ try:+ todo = missing(default_files(args.ext_dir, args.install_dir, args.backend))+ check_space(todo)+ for item in todo:+ print(f"Downloading {item.label} ({_gb(item.size)} GB) to {item.target}", flush=True)+ _fetch_with_attempts(item, max(1, args.attempts), args.retry_delay)+ print(f"{item.label} is ready (SHA-256 verified)", flush=True)+ except (AssetError, ValueError) as exc:+ print(f"ERROR: {exc}", file=sys.stderr)+ return 1+ if not todo:+ print("All default model packs are already in place")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/ods/bin/ods-host-agent.py b/ods/bin/ods-host-agent.pyindex fedb85c94..0b26764fa 100755--- a/ods/bin/ods-host-agent.py+++ b/ods/bin/ods-host-agent.py@@ -53,6 +53,9 @@ if _SWITCHBOARD_BIN_DIR not in sys.path:from model_switchboard.router_transport import request as _router_transport_requestfrom model_switchboard.router_transport import exchange as _router_transport_exchangefrom model_switchboard import wsl_runtime as _wsl_runtime+# Model packs (extensions/services/<id>/model-packs.json): files an extension's+# container reads beside its image, fetched by the prepare step after images.+import extension_assets as _extension_assets# Model profiles (WP3): measured capabilities per GGUF x llama.cpp build x host.# Fail-open like the switchboard: without the package a switch runs as before.try:@@ -9555,6 +9558,41 @@ def _services_missing_images(flags: list[str], service_ids: list[str],return missing+def _missing_model_files(service_ids: list[str]) -> list:+ """Default model-pack files these bundled services read and this host lacks.++ Packs ship only with bundled extensions, so a Library recipe of the same+ name never supplies one.+ """+ files = []+ for service_id in service_ids:+ files.extend(_extension_assets.missing(+ _extension_assets.default_files(EXTENSIONS_DIR / service_id, INSTALL_DIR, GPU_BACKEND)))+ return files+++def _fetch_model_files(progress_id: str, files: list) -> tuple[bool, str]:+ """Download model-pack files with progress on the card; returns ``(ok, error)``."""+ try:+ _extension_assets.check_space(files)+ for item in files:+ _write_progress(progress_id, "pulling", f"Downloading the {item.label}...")+ reported = [time.monotonic()]++ def report(done: int, item=item) -> None:+ now = time.monotonic()+ if now - reported[0] >= _IMAGE_PULL_PROGRESS_SECONDS:+ reported[0] = now+ _write_progress(progress_id, "pulling",+ f"Downloading the {item.label}... "+ f"{done / 1e9:.1f} of {item.size / 1e9:.1f} GB")++ _extension_assets.fetch(item, report)+ except _extension_assets.AssetError as exc:+ return False, str(exc)+ return True, ""++def _pull_compose_images(flags: list[str], service_ids: list[str], progress_id: str,*, env: dict[str, str] | None = None) -> tuple[bool, str]:"""Download the images of ``service_ids`` with live progress under ``progress_id``.@@ -13376,13 +13414,14 @@ class AgentHandler(BaseHTTPRequestHandler):"action": "install", 'operation_id': operation_id})def _handle_prepare_images(self):- """Download the images a planned enable needs before anything is selected.+ """Download the images and models a planned enable needs before anything is selected.Takes service ids only: bundled extensions and Open WebUI, whose images- Compose resolves from their shipped files and pinned digests. Answers- 200 when every image is already here, otherwise 202 and downloads in- the background, reporting progress under ``progress_id`` until it- records ``prepared`` or ``error``. Each service allows one operation.+ Compose resolves from their shipped files and pinned digests. Their+ default model packs (model-packs.json) follow the images. Answers 200+ when everything is already here, otherwise 202 and downloads in the+ background, reporting progress under ``progress_id`` until it records+ ``prepared`` or ``error``. Each service allows one operation."""if not check_auth(self):return@@ -13418,23 +13457,31 @@ class AgentHandler(BaseHTTPRequestHandler):try:flags, env = _image_prepare_context(service_ids)missing = _services_missing_images(flags, service_ids, env)+ model_files = _missing_model_files(service_ids)except (RuntimeError, ValueError, OSError, subprocess.SubprocessError) as exc:_release()logger.warning("Image preparation could not resolve %s: %s", progress_id, type(exc).__name__)json_response(self, 503, {"error": str(exc)[:300]})return- if not missing:+ if not missing and not model_files:_release()json_response(self, 200, {"status": "ready", "service_ids": service_ids})returndef _download() -> None:try:- pulled, error = _pull_compose_images(flags, missing, progress_id, env=env)- if pulled:- _write_progress(progress_id, "prepared", "Images downloaded")- else:- _write_progress(progress_id, "error", "Image download failed", error=error)+ if missing:+ pulled, error = _pull_compose_images(flags, missing, progress_id, env=env)+ if not pulled:+ _write_progress(progress_id, "error", "Image download failed", error=error)+ return+ if model_files:+ fetched, error = _fetch_model_files(progress_id, model_files)+ if not fetched:+ _write_progress(progress_id, "error", "Model download failed", error=error)+ return+ _write_progress(progress_id, "prepared",+ "Images and models downloaded" if model_files else "Images downloaded")except (OSError, ValueError, subprocess.SubprocessError) as exc:logger.exception("Image preparation failed for %s", progress_id)_write_progress(progress_id, "error", "Image download failed", error=str(exc)[:500])@@ -13446,7 +13493,8 @@ class AgentHandler(BaseHTTPRequestHandler):except Exception:_release()raise- json_response(self, 202, {"status": "accepted", "service_ids": service_ids, "pulling": missing})+ json_response(self, 202, {"status": "accepted", "service_ids": service_ids, "pulling": missing,+ "models": [item.target.name for item in model_files]})# ── Model management handlers ──diff --git a/ods/extensions/services/comfyui/README.md b/ods/extensions/services/comfyui/README.mdindex 1d1bf861e..4266e4a35 100644--- a/ods/extensions/services/comfyui/README.md+++ b/ods/extensions/services/comfyui/README.md@@ -55,20 +55,38 @@ Open WebUI's image generation reads these from `.env` each time it starts:## Image model-When image generation is chosen in the installer, the installer downloads SDXL Lightning 4-step-(`sdxl_lightning_4step.safetensors`, 6.94 GB) into `checkpoints/` in the background.+ComfyUI's default image pack is SDXL Lightning 4-step (`sdxl_lightning_4step.safetensors`, 6.94 GB). It is pinned+by URL (a fixed Hugging Face revision), size and SHA-256 in `model-packs.json` and goes into `checkpoints/`. It is+downloaded:+- when you add ComfyUI from the Extensions page, after its image, with progress on the card;+- by the Linux installer, in the background, when image generation is chosen there. It keeps going through up to+ five dropped connections.-Adding ComfyUI later from the Extensions page does not download it yet. Fetch it once from your ODS install-directory, then click **Refresh** in ComfyUI. On AMD the folder is `data/comfyui/ComfyUI/models/checkpoints`.+The Windows installer and `ods enable comfyui` do not download it yet; fetch it by hand (below), or disable and add+ComfyUI again on the Extensions page.-If `mkdir` or `curl` reports "Permission denied" (the AMD container runs as root and owns its folder), run the commands-with `sudo`.+Both downloads use `bin/extension_assets.py`. It checks free disk first, resumes a partial download (`*.part`),+deletes a file that fails its checksum, and puts the model in place only once it is verified. If a download stops,+try again: click **Add** on the Extensions page again, or run the command below. Either way it resumes.++To fetch it by hand, run this from your ODS install directory (on Windows, `python` in PowerShell), then click+**Refresh** in ComfyUI:++```bash+python3 bin/extension_assets.py extensions/services/comfyui . nvidia # or amd+```++On AMD the folder is `data/comfyui/ComfyUI/models/checkpoints`. The AMD container runs as root and owns what it+creates there, so a download may report that the folder belongs to another account. Run the `sudo chown` command+the error prints, then try again.++Or with curl (`sudo` on AMD if `mkdir` or `curl` reports "Permission denied"):```bashdir=data/comfyui/models/checkpointsmkdir -p "$dir"curl -fL -C - -o "$dir/sdxl_lightning_4step.safetensors.part" \- https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_4step.safetensors+ https://huggingface.co/ByteDance/SDXL-Lightning/resolve/c9a24f48e1c025556787b0c58dd67a091ece2e44/sdxl_lightning_4step.safetensorsecho "e0d996ee0013e79d9d3561f50fcafb9a17e3ff07b780358e3b66d67932c4d490 $dir/sdxl_lightning_4step.safetensors.part" | sha256sum -c - \&& mv "$dir/sdxl_lightning_4step.safetensors.part" "$dir/sdxl_lightning_4step.safetensors"```diff --git a/ods/extensions/services/comfyui/model-packs.json b/ods/extensions/services/comfyui/model-packs.jsonnew file mode 100644index 000000000..90400f23f--- /dev/null+++ b/ods/extensions/services/comfyui/model-packs.json@@ -0,0 +1,25 @@+{+ "schema": "ods.model-packs.v1",+ "model_root": {+ "nvidia": "data/comfyui/models",+ "amd": "data/comfyui/ComfyUI/models"+ },+ "packs": [+ {+ "id": "image-default",+ "label": "SDXL Lightning 4-step model",+ "feature": "images",+ "default": true,+ "files": [+ {+ "subdir": "checkpoints",+ "file": "sdxl_lightning_4step.safetensors",+ "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/c9a24f48e1c025556787b0c58dd67a091ece2e44/sdxl_lightning_4step.safetensors",+ "sha256": "e0d996ee0013e79d9d3561f50fcafb9a17e3ff07b780358e3b66d67932c4d490",+ "bytes": 6938040682,+ "license": "openrail++"+ }+ ]+ }+ ]+}diff --git a/ods/extensions/services/dashboard-api/tests/test_host_agent_image_prepare.py b/ods/extensions/services/dashboard-api/tests/test_host_agent_image_prepare.pyindex f26bbee9e..cc3d2981b 100644--- a/ods/extensions/services/dashboard-api/tests/test_host_agent_image_prepare.py+++ b/ods/extensions/services/dashboard-api/tests/test_host_agent_image_prepare.py@@ -266,6 +266,119 @@ def test_prepare_refuses_while_the_service_is_being_changed(prepare, host, monkeassert not _mod._service_locks["hermes"].locked()+PACK_FILE = "model.safetensors"+++def model_pack(prepare, host, monkeypatch): # noqa: F811+ """A bundled extension that ships a default model pack (as ComfyUI does)."""+ _mod._service_locks.pop("painter", None)+ directory = host.builtins / "painter"+ directory.mkdir()+ (directory / "compose.yaml.disabled").write_text(+ "services:\n painter:\n image: example/painter:1\n", encoding="utf-8")+ (directory / "model-packs.json").write_text(json.dumps({+ "schema": "ods.model-packs.v1",+ "model_root": {"nvidia": "data/painter/models"},+ "packs": [{"id": "image-default", "label": "Painter model", "default": True,+ "files": [{"subdir": "checkpoints", "file": PACK_FILE,+ "url": "https://example.invalid/model.safetensors",+ "sha256": "a" * 64, "bytes": 5, "license": "test"}]}],+ }), encoding="utf-8")+ monkeypatch.setattr(_mod, "GPU_BACKEND", "nvidia")+ monkeypatch.setattr(_mod._extension_assets, "check_space", lambda files: None)+ return host.install_dir / "data/painter/models/checkpoints" / PACK_FILE+++def test_prepare_fetches_a_missing_model_pack_after_the_images(prepare, host, monkeypatch, model_pack): # noqa: F811+ monkeypatch.setattr(_mod, "_services_missing_images", lambda flags, ids, env: ["painter"])+ order = []++ def pull(*args, **kwargs):+ order.append("images")+ return True, ""++ monkeypatch.setattr(_mod, "_pull_compose_images", pull)++ def fetch(item, report):+ order.append("model")+ assert _mod._service_locks["painter"].locked() # one operation per service+ item.target.parent.mkdir(parents=True)+ item.target.write_bytes(b"model")+ report(5)++ monkeypatch.setattr(_mod._extension_assets, "fetch", fetch)++ status, response = prepare({"service_ids": ["painter"], "progress_id": "painter"})++ assert status == 202 and response["models"] == [PACK_FILE]+ assert order == ["images", "model"]+ assert model_pack.read_bytes() == b"model"+ record = host.progress("painter")+ assert (record["status"], record["phase_label"]) == ("prepared", "Images and models downloaded")+ assert not _mod._service_locks["painter"].locked()+++def test_prepare_downloads_a_missing_model_even_when_the_images_are_here(prepare, host, monkeypatch, model_pack): # noqa: F811+ monkeypatch.setattr(_mod, "_services_missing_images", lambda flags, ids, env: [])+ monkeypatch.setattr(_mod, "_pull_compose_images", lambda *args, **kwargs: pytest.fail("no image download"))+ labels = []+ real_write = _mod._write_progress++ def recording_write(service_id, status, label="", **kw):+ labels.append(label)+ real_write(service_id, status, label, **kw)++ monkeypatch.setattr(_mod, "_write_progress", recording_write)+ monkeypatch.setattr(_mod._extension_assets, "fetch", lambda item, report: (+ item.target.parent.mkdir(parents=True), item.target.write_bytes(b"model")))++ status, response = prepare({"service_ids": ["painter"], "progress_id": "painter"})++ assert status == 202 and response["pulling"] == []+ assert labels[0] == "Downloading the Painter model..."+ assert host.progress("painter")["status"] == "prepared"+++def test_prepare_is_ready_when_images_and_models_are_here(prepare, host, monkeypatch, model_pack): # noqa: F811+ model_pack.parent.mkdir(parents=True)+ model_pack.write_bytes(b"model") # the pinned size: 5 bytes+ monkeypatch.setattr(_mod, "_services_missing_images", lambda flags, ids, env: [])+ monkeypatch.setattr(_mod._extension_assets, "fetch", lambda *args: pytest.fail("no download expected"))++ status, response = prepare({"service_ids": ["painter"], "progress_id": "painter"})++ assert status == 200 and response["status"] == "ready"+ assert not _mod._service_locks["painter"].locked()+++def test_prepare_records_a_failed_model_download_for_the_card(prepare, host, monkeypatch, model_pack): # noqa: F811+ monkeypatch.setattr(_mod, "_services_missing_images", lambda flags, ids, env: [])++ def fail(item, report):+ raise _mod._extension_assets.AssetError("The download of Painter model stopped (timed out).")++ monkeypatch.setattr(_mod._extension_assets, "fetch", fail)++ status, _response = prepare({"service_ids": ["painter"], "progress_id": "painter"})++ assert status == 202+ record = host.progress("painter")+ assert (record["status"], record["phase_label"]) == ("error", "Model download failed")+ assert record["error"] == "The download of Painter model stopped (timed out)."+ assert not _mod._service_locks["painter"].locked()+++def test_prepare_reports_a_malformed_pack_list_without_downloading(prepare, host, monkeypatch, model_pack): # noqa: F811+ (host.builtins / "painter" / "model-packs.json").write_text('{"schema": "other"}', encoding="utf-8")+ monkeypatch.setattr(_mod, "_services_missing_images", lambda flags, ids, env: [])++ status, response = prepare({"service_ids": ["painter"], "progress_id": "painter"})++ assert status == 503 and "schema must be ods.model-packs.v1" in response["error"]+ assert not _mod._service_locks["painter"].locked()++def test_prepare_reports_an_unresolvable_stack_without_downloading(prepare, host, monkeypatch): # noqa: F811monkeypatch.setattr(_mod, "_services_missing_images",lambda flags, ids, env: (_ for _ in ()).throw(RuntimeError("Could not resolve")))diff --git a/ods/installers/phases/11-services.sh b/ods/installers/phases/11-services.shindex f0d2f744d..74e4895ae 100755--- a/ods/installers/phases/11-services.sh+++ b/ods/installers/phases/11-services.sh@@ -1146,11 +1146,11 @@ elsefifi+ # The checkpoint ComfyUI's default image pack (comfyui/model-packs.json) pins.SDXL_MODEL="sdxl_lightning_4step.safetensors"- SDXL_URL="https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_4step.safetensors"if [[ ! -f "$SDXL_CHECKPOINT_DIR/$SDXL_MODEL" ]]; then- ai "Downloading SDXL Lightning 4-step (~6.5GB) for image generation..."+ ai "Downloading SDXL Lightning 4-step (6.9 GB) for image generation..."# Source background task trackingif [[ -f "$SCRIPT_DIR/installers/lib/background-tasks.sh" ]]; then@@ -1158,27 +1158,26 @@ elsefi# This daemon must not inherit the installer model lifecycle lock;- # otherwise full-model activation waits for an unrelated 6.5 GB+ # otherwise full-model activation waits for an unrelated 6.9 GB# image download after the installer itself releases the lock.+ # It runs the downloader the Extensions page uses, from the install+ # directory (which outlives the installer's source): the pinned URL,+ # size and SHA-256 come from model-packs.json, a dropped connection+ # resumes (six tries, as curl --retry 5 did), and a file that fails+ # its checksum is deleted. The summary reads this log for ERROR, so+ # any non-zero exit, even one the downloader did not foresee, ends+ # with an ERROR line.(_phase11_close_inherited_fds_for_daemonexec nohup env \- SDXL_CHECKPOINT_DIR="$SDXL_CHECKPOINT_DIR" \- SDXL_MODEL="$SDXL_MODEL" \- SDXL_URL="$SDXL_URL" \+ ODS_ASSETS_PYTHON="${ODS_PYTHON_CMD:-python3}" \+ ODS_ASSETS="$INSTALL_DIR/bin/extension_assets.py" \+ COMFYUI_EXT_DIR="$INSTALL_DIR/extensions/services/comfyui" \+ INSTALL_DIR="$INSTALL_DIR" \+ GPU_BACKEND="$GPU_BACKEND" \bash -c '- echo "[SDXL] Starting SDXL Lightning model download..."- if [[ ! -f "$SDXL_CHECKPOINT_DIR/$SDXL_MODEL" ]]; then- echo "[SDXL] Downloading $SDXL_MODEL (~6.5GB)..."- curl -fSL -C - --connect-timeout 30 --max-time 3600 \- --retry 5 --retry-delay 10 --retry-all-errors \- -o "$SDXL_CHECKPOINT_DIR/$SDXL_MODEL.part" \- "$SDXL_URL" 2>&1 && \- mv "$SDXL_CHECKPOINT_DIR/$SDXL_MODEL.part" "$SDXL_CHECKPOINT_DIR/$SDXL_MODEL" && \- echo "[SDXL] $SDXL_MODEL complete" || \- echo "[SDXL] ERROR: Failed to download $SDXL_MODEL"- fi- echo "[SDXL] SDXL Lightning model download finished."+ "$ODS_ASSETS_PYTHON" "$ODS_ASSETS" --attempts 6 "$COMFYUI_EXT_DIR" "$INSTALL_DIR" "$GPU_BACKEND" \+ || echo "[SDXL] ERROR: the model download exited with status $?; see the lines above"' > "$INSTALL_DIR/logs/sdxl-download.log" 2>&1) &@@ -1190,7 +1189,7 @@ elsefilog "Background SDXL download started (PID: $sdxl_pid). Check: tail -f $INSTALL_DIR/logs/sdxl-download.log"- ai "SDXL Lightning downloading in background (~6.5GB). ComfyUI will be ready once complete."+ ai "SDXL Lightning downloading in background (6.9 GB). ComfyUI will be ready once complete."elseai_ok "SDXL Lightning model already present"fidiff --git a/ods/installers/phases/13-summary.sh b/ods/installers/phases/13-summary.shindex 7d156b650..2edb1377f 100755--- a/ods/installers/phases/13-summary.sh+++ b/ods/installers/phases/13-summary.sh@@ -14,6 +14,7 @@# BGRN, GRN, AMB, WHT, NC, DASHBOARD_PORT (:-3001),# CAP_HARDWARE_CLASS_ID (:-unknown), CAP_HARDWARE_CLASS_LABEL (:-Unknown),# BACKEND_SERVICE_NAME (:-llama-server),+# SDXL_CHECKPOINT_DIR, SDXL_MODEL (set by phase 11 when ComfyUI is enabled),# show_success_card(), bootline(), signal(), ai_ok(), log()# Provides: Desktop shortcut, sidebar pin, summary JSON#@@ -149,20 +150,34 @@ if [[ -f "$SCRIPT_DIR/installers/lib/background-tasks.sh" ]]; thenbg_task_summary >> "$LOG_FILE" 2>&1# Check SDXL Lightning download specifically- if bg_task_status "sdxl-download" &>/dev/null; then sdxl_status=0; else sdxl_status=$?; fi+ # The downloader renames only a verified file, so a model in place is+ # ready whatever an older log in the task registry says.+ if [[ -n "${SDXL_CHECKPOINT_DIR:-}" && -f "$SDXL_CHECKPOINT_DIR/${SDXL_MODEL:-}" ]]; then+ sdxl_status=4+ elif bg_task_status "sdxl-download" &>/dev/null; then sdxl_status=0; else sdxl_status=$?; fi+ # The same command finishes the download by hand; it resumes the part.+ printf -v sdxl_resume '%q ' "${ODS_PYTHON_CMD:-python3}" "$INSTALL_DIR/bin/extension_assets.py" \+ "$INSTALL_DIR/extensions/services/comfyui" "$INSTALL_DIR" "$GPU_BACKEND"+ sdxl_resume="${sdxl_resume% }"if [[ $sdxl_status -ne 3 ]]; thencase $sdxl_status in0) # Still runningai_warn "SDXL Lightning model download still in progress"ai "ComfyUI image generation will be available once download completes"ai "Check progress: tail -f $INSTALL_DIR/logs/sdxl-download.log"+ ai "If it stops, finish it with: $sdxl_resume";;1) # Completedai_ok "SDXL Lightning model download completed";;+ 4) # In place+ ai_ok "SDXL Lightning model is in place"+ ;;2) # Failedai_warn "SDXL Lightning model download encountered errors"ai "Check log: $INSTALL_DIR/logs/sdxl-download.log"+ ai "Fix what the log names, then finish it with: $sdxl_resume"+ ai "Need help? Ask on the ODS Discord: ${ODS_HELP_DISCORD_URL:-https://discord.gg/4ntNp9MAwC}";;esacfidiff --git a/ods/tests/ci-suite.txt b/ods/tests/ci-suite.txtindex ebf52c8e4..5217df499 100644--- a/ods/tests/ci-suite.txt+++ b/ods/tests/ci-suite.txt@@ -61,6 +61,7 @@ tests/test-cli-stt-env.pytests/test-cli-update-verification.shtests/test-comfyui-user-dir-persisted.shtests/test_comfyui_extension_contract.py+tests/test_extension_assets.pytests/test-compose-failure-evidence.shtests/test-compose-image-discovery.shtests/test-custom-menu-agent-flags.shdiff --git a/ods/tests/test-network-timeouts.sh b/ods/tests/test-network-timeouts.shindex e0539b343..2e5112b4b 100755--- a/ods/tests/test-network-timeouts.sh+++ b/ods/tests/test-network-timeouts.sh@@ -141,11 +141,13 @@ test_file_has_timeout \"--max-time" \"GGUF model download"+# The SDXL Lightning model (installer phase 11 and the Extensions page) goes+# through the shared model-pack downloader.test_file_has_timeout \- "$ROOT_DIR/installers/phases/11-services.sh" \- "curl.*SDXL_URL" \- "--max-time" \- "SDXL Lightning model download"+ "$ROOT_DIR/bin/extension_assets.py" \+ "opener(urllib.request.Request" \+ "timeout=READ_TIMEOUT_SECONDS" \+ "Model pack download (SDXL Lightning)"# Phase 12 - Health checkstest_file_has_timeout \diff --git a/ods/tests/test_comfyui_extension_contract.py b/ods/tests/test_comfyui_extension_contract.pyindex 29fb07874..96c9883b1 100644--- a/ods/tests/test_comfyui_extension_contract.py+++ b/ods/tests/test_comfyui_extension_contract.py@@ -105,8 +105,21 @@ def test_image_model_name_agrees_everywhere():loaders = [node for node in workflow.values() if node["class_type"] == "CheckpointLoaderSimple"]assert [node["inputs"]["ckpt_name"] for node in loaders] == [MODEL]+ packs = json.loads((COMFYUI / "model-packs.json").read_text(encoding="utf-8"))+ default = [item for pack in packs["packs"] if pack["default"] for item in pack["files"]]+ assert [(item["subdir"], item["file"]) for item in default] == [("checkpoints", MODEL)]+installer = (ODS / "installers/phases/11-services.sh").read_text(encoding="utf-8")assert f'SDXL_MODEL="{MODEL}"' in installer+ # The installer downloads through the same pinned pack list as the Extensions+ # page, keeps going through dropped connections, and logs ERROR on any failure+ # (the summary reads the log, not the exit code).+ assert 'ODS_ASSETS="$INSTALL_DIR/bin/extension_assets.py"' in installer+ assert 'COMFYUI_EXT_DIR="$INSTALL_DIR/extensions/services/comfyui"' in installer+ assert ('"$ODS_ASSETS_PYTHON" "$ODS_ASSETS" --attempts 6 "$COMFYUI_EXT_DIR" "$INSTALL_DIR" "$GPU_BACKEND" \\\n'+ ' || echo "[SDXL] ERROR: ') in installer+ assert "huggingface.co/ByteDance" not in installer+ assert "/resolve/main/" not in json.dumps(packs)n8n = (ODS / "extensions/library/workflows/comfyui/llm-to-image.json").read_text(encoding="utf-8")assert f"$env.COMFYUI_MODEL_NAME || '{MODEL}'" in n8ndiff --git a/ods/tests/test_extension_assets.py b/ods/tests/test_extension_assets.pynew file mode 100644index 000000000..646f3b36e--- /dev/null+++ b/ods/tests/test_extension_assets.py@@ -0,0 +1,477 @@+"""Model packs an extension's container reads beside its image (bin/extension_assets.py).++The prepare step and the installer fetch them; these tests drive the module+with a fake HTTP opener, so nothing leaves the machine.+"""+import errno+import hashlib+import http.client+import io+import json+import os+import shutil+import ssl+import sys+import urllib.error+from pathlib import Path++import pytest++ODS = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ODS / "bin"))+import extension_assets as assets # noqa: E402++PAYLOAD = b"model weights " * 4096+DIGEST = hashlib.sha256(PAYLOAD).hexdigest()+++def _pack_list(tmp_path, *, sha256=DIGEST, size=len(PAYLOAD), default=True, root="data/comfyui/models"):+ ext_dir = tmp_path / "ext"+ ext_dir.mkdir(exist_ok=True)+ (ext_dir / "model-packs.json").write_text(json.dumps({+ "schema": "ods.model-packs.v1",+ "model_root": {"nvidia": root, "amd": "data/comfyui/ComfyUI/models"},+ "packs": [{"id": "image-default", "label": "Test model", "feature": "images", "default": default,+ "files": [{"subdir": "checkpoints", "file": "test.safetensors",+ "url": "https://example.invalid/test.safetensors",+ "sha256": sha256, "bytes": size, "license": "test"}]}],+ }), encoding="utf-8")+ install = tmp_path / "install"+ install.mkdir(exist_ok=True)+ return ext_dir, install+++class Response(io.BytesIO):+ def __init__(self, body, status=200, fail_after=None, failure=None):+ super().__init__(body)+ self.status = status+ self.fail_after, self.failure = fail_after, failure++ def read(self, size=-1):+ if self.fail_after is not None and self.tell() >= self.fail_after:+ raise self.failure+ return super().read(size if self.fail_after is None else min(size, self.fail_after - self.tell()))+++def opener_for(body, status=200, seen=None):+ def opener(request, timeout):+ if seen is not None:+ seen.append((dict(request.header_items()), timeout))+ return Response(body, status)+ return opener+++def opener_sequence(*answers, seen=None):+ """Answer each request with the next Response, or raise the next exception."""+ pending = list(answers)++ def opener(request, timeout):+ if seen is not None:+ seen.append(dict(request.header_items()))+ answer = pending.pop(0)+ if isinstance(answer, BaseException):+ raise answer+ return answer+ return opener+++def no_network(request, timeout):+ raise AssertionError("fetch made a request it did not need")+++def _http_error(code, reason):+ return urllib.error.HTTPError("https://example.invalid/test.safetensors", code, reason, {}, None)+++def test_default_files_follow_the_backend_and_skip_optional_packs(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ assert item.target == install.resolve() / "data/comfyui/models/checkpoints/test.safetensors"+ assert (item.size, item.sha256, item.label) == (len(PAYLOAD), DIGEST, "Test model")+ [amd] = assets.default_files(ext_dir, install, "amd")+ assert amd.target.parent == install.resolve() / "data/comfyui/ComfyUI/models/checkpoints"+ assert assets.default_files(ext_dir, install, "cpu") == []+ assert assets.default_files(tmp_path / "no-packs", install, "nvidia") == []+ ext_dir, install = _pack_list(tmp_path, default=False)+ assert assets.default_files(ext_dir, install, "nvidia") == []++[email protected]("change", [+ {"root": "../outside"},+ {"root": "data/../../outside"},+ {"root": "/etc/ods"},+ {"root": ""},+ {"sha256": "ABC"},+ {"size": 0},+])+def test_unsafe_or_incomplete_pack_lists_are_refused(tmp_path, change):+ ext_dir, install = _pack_list(tmp_path, **change)+ with pytest.raises(ValueError):+ assets.default_files(ext_dir, install, "nvidia")+++def test_a_data_folder_linked_to_another_disk_is_accepted(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ elsewhere = tmp_path / "other-disk"+ elsewhere.mkdir()+ try:+ (install / "data").symlink_to(elsewhere, target_is_directory=True)+ except OSError as exc: # Windows without symlink rights+ pytest.skip(f"cannot create a symlink here: {exc}")+ [item] = assets.default_files(ext_dir, install, "nvidia")+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD))+ assert (elsewhere / "comfyui/models/checkpoints/test.safetensors").read_bytes() == PAYLOAD+++def test_a_malformed_pack_list_is_a_value_error(tmp_path):+ ext_dir = tmp_path / "ext"+ ext_dir.mkdir()+ (ext_dir / "model-packs.json").write_text('{"schema": "ods.model-packs.v1", "packs": []}', encoding="utf-8")+ with pytest.raises(ValueError, match="malformed"):+ assets.default_files(ext_dir, tmp_path, "nvidia")+++def test_a_file_counts_as_present_only_at_its_pinned_size(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ assert assets.missing([item]) == [item]+ item.target.parent.mkdir(parents=True)+ item.target.write_bytes(PAYLOAD[:100])+ assert assets.missing([item]) == [item]+ item.target.write_bytes(PAYLOAD)+ assert assets.missing([item]) == []+++def test_fetch_downloads_verifies_and_renames(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ progress, seen = [], []+ assets.fetch(item, progress.append, opener=opener_for(PAYLOAD, seen=seen))+ assert item.target.read_bytes() == PAYLOAD+ assert not item.target.with_name("test.safetensors.part").exists()+ assert progress[-1] == len(PAYLOAD)+ headers, timeout = seen[0]+ assert "Range" not in headers and headers["User-agent"] == assets.USER_AGENT+ assert timeout == assets.READ_TIMEOUT_SECONDS+++def test_fetch_resumes_a_partial_download_with_a_range_request(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ part = item.target.with_name("test.safetensors.part")+ part.parent.mkdir(parents=True)+ part.write_bytes(PAYLOAD[:1000])+ seen = []+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD[1000:], status=206, seen=seen))+ assert seen[0][0]["Range"] == "bytes=1000-"+ assert item.target.read_bytes() == PAYLOAD+++def test_fetch_starts_over_when_the_server_ignores_the_range(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ part = item.target.with_name("test.safetensors.part")+ part.parent.mkdir(parents=True)+ part.write_bytes(b"x" * 1000) # not even the right bytes+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD, status=200))+ assert item.target.read_bytes() == PAYLOAD+++def test_a_wrong_checksum_deletes_the_download(tmp_path):+ ext_dir, install = _pack_list(tmp_path, sha256="0" * 64)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ with pytest.raises(assets.AssetError, match="did not match its pinned SHA-256"):+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD))+ assert not item.target.exists()+ assert not item.target.with_name("test.safetensors.part").exists()+++def test_a_short_download_keeps_the_part_for_a_resume(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ with pytest.raises(assets.AssetError, match="Try again to resume it"):+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD[:5000]))+ assert item.target.with_name("test.safetensors.part").stat().st_size == 5000+ assert not item.target.exists()+++def test_a_network_failure_names_the_cause_and_keeps_the_part(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")++ def offline(request, timeout):+ raise urllib.error.URLError("Temporary failure in name resolution")++ with pytest.raises(assets.AssetError, match="Temporary failure in name resolution") as caught:+ assets.fetch(item, lambda done: None, opener=offline)+ assert caught.value.retryable+++def test_a_connection_dropped_mid_transfer_keeps_what_arrived(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ dropped = Response(PAYLOAD, fail_after=7000, failure=http.client.IncompleteRead(b""))+ with pytest.raises(assets.AssetError, match="Try again to resume it") as caught:+ assets.fetch(item, lambda done: None, opener=opener_sequence(dropped))+ assert caught.value.retryable+ assert item.target.with_name("test.safetensors.part").read_bytes() == PAYLOAD[:7000]+++def test_a_complete_part_is_checked_and_renamed_without_downloading(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ part = item.target.with_name("test.safetensors.part")+ part.parent.mkdir(parents=True)+ part.write_bytes(PAYLOAD)+ assets.fetch(item, lambda done: None, opener=no_network)+ assert item.target.read_bytes() == PAYLOAD and not part.exists()+++def test_a_complete_part_with_the_wrong_bytes_is_deleted(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ part = item.target.with_name("test.safetensors.part")+ part.parent.mkdir(parents=True)+ part.write_bytes(b"y" * len(PAYLOAD))+ with pytest.raises(assets.AssetError, match="did not match its pinned SHA-256") as caught:+ assets.fetch(item, lambda done: None, opener=no_network)+ assert not caught.value.retryable and not part.exists()+++def test_a_part_larger_than_the_file_starts_over(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ part = item.target.with_name("test.safetensors.part")+ part.parent.mkdir(parents=True)+ part.write_bytes(PAYLOAD + b"extra")+ assert assets._remaining(item) == len(PAYLOAD)+ seen = []+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD, seen=seen))+ assert "Range" not in seen[0][0]+ assert item.target.read_bytes() == PAYLOAD+++def test_a_refused_range_deletes_the_part_instead_of_looping(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ part = item.target.with_name("test.safetensors.part")+ part.parent.mkdir(parents=True)+ part.write_bytes(PAYLOAD[:1000])+ with pytest.raises(assets.AssetError, match="not the pinned file") as caught:+ assets.fetch(item, lambda done: None,+ opener=opener_sequence(_http_error(416, "Range Not Satisfiable")))+ assert not caught.value.retryable+ assert part.stat().st_size == 0+++def test_http_errors_say_whether_trying_again_can_help(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ with pytest.raises(assets.AssetError) as busy:+ assets.fetch(item, lambda done: None, opener=opener_sequence(_http_error(503, "Service Unavailable")))+ assert busy.value.retryable+ with pytest.raises(assets.AssetError, match=r"link for Test model no longer works \(HTTP 404\)") as gone:+ assets.fetch(item, lambda done: None, opener=opener_sequence(_http_error(404, "Not Found")))+ assert not gone.value.retryable+ with pytest.raises(assets.AssetError, match=r"refused Test model \(HTTP 403 Forbidden\).*example\.invalid") as no:+ assets.fetch(item, lambda done: None, opener=opener_sequence(_http_error(403, "Forbidden")))+ assert not no.value.retryable+++def test_a_certificate_that_fails_to_verify_is_not_retried(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ bad_certificate = urllib.error.URLError(ssl.SSLCertVerificationError(1, "certificate verify failed"))+ with pytest.raises(assets.AssetError, match="Check the system clock and any proxy") as caught:+ assets.fetch(item, lambda done: None, opener=opener_sequence(bad_certificate))+ assert not caught.value.retryable+++def _denied(*args, **kwargs):+ raise PermissionError(errno.EACCES, "Permission denied", str(args[0]))++[email protected](not hasattr(os, "getuid"), reason="file ownership is POSIX")+def test_a_folder_owned_by_another_account_says_how_to_fix_it(tmp_path, monkeypatch):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ uid, gid = os.getuid(), os.getgid()+ monkeypatch.setattr(assets, "open", _denied, raising=False)+ monkeypatch.setattr(assets.os, "access", lambda path, mode: False)+ monkeypatch.setattr(assets.os, "getuid", lambda: uid + 1) # the folder is now someone else's+ with pytest.raises(assets.AssetError, match="belongs to another account") as caught:+ assets.fetch(item, lambda done: None, opener=no_network)+ message = str(caught.value)+ assert message.endswith(f"sudo chown -R {uid + 1}:{gid} {item.target.parent}")+ assert not caught.value.retryable and "Try again to resume" not in message+++def test_a_write_refused_in_your_own_folder_does_not_blame_its_owner(tmp_path, monkeypatch):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ monkeypatch.setattr(assets, "open", _denied, raising=False)+ with pytest.raises(assets.AssetError, match="no other program, such as an antivirus") as caught:+ assets.fetch(item, lambda done: None, opener=no_network)+ message = str(caught.value)+ assert str(item.target.parent) in message+ assert "sudo chown" not in message and "another account" not in message+++def test_a_longer_answer_is_cut_at_the_pinned_size(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD + b"junk" * 50000))+ assert item.target.read_bytes() == PAYLOAD+++def test_bytes_another_writer_appended_fail_the_check(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ part = item.target.with_name("test.safetensors.part")++ class Interleaved(Response):+ def read(self, size=-1):+ if self.tell() == 0: # a second writer, with no lock to stop it, appends too+ with open(part, "ab") as other:+ other.write(b"X" * 100)+ return super().read(size)++ with pytest.raises(assets.AssetError, match="did not match its pinned SHA-256"):+ assets.fetch(item, lambda done: None, opener=opener_sequence(Interleaved(PAYLOAD)))+ assert not item.target.exists() and not part.exists()+++def test_a_file_finished_meanwhile_is_not_downloaded_again(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ item.target.parent.mkdir(parents=True)+ item.target.write_bytes(PAYLOAD)+ assets.fetch(item, lambda done: None, opener=no_network)+ assert not item.target.with_name("test.safetensors.part").exists()++[email protected](assets.fcntl is None, reason="the folder lock uses fcntl (POSIX)")+def test_a_file_system_without_locks_still_downloads(tmp_path, monkeypatch):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")++ def unsupported(fd, operation):+ raise OSError(errno.EOPNOTSUPP, "Operation not supported")++ monkeypatch.setattr(assets.fcntl, "flock", unsupported)+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD))+ assert item.target.read_bytes() == PAYLOAD+++def test_a_full_disk_while_writing_is_reported_as_the_disk(tmp_path, monkeypatch):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ real_open = open++ class FullDisk:+ def __init__(self, path, mode):+ self.handle = real_open(path, mode)++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.handle.close()++ def write(self, data):+ raise OSError(errno.ENOSPC, "No space left on device")++ def __getattr__(self, name):+ return getattr(self.handle, name)++ monkeypatch.setattr(assets, "open", FullDisk, raising=False)+ with pytest.raises(assets.AssetError, match=r"could not save Test model .*No space left") as caught:+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD))+ assert not caught.value.retryable++[email protected](assets.fcntl is None, reason="the folder lock uses fcntl (POSIX)")+def test_a_second_download_into_the_same_folder_is_refused(tmp_path):+ ext_dir, install = _pack_list(tmp_path)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ item.target.parent.mkdir(parents=True)+ holder = os.open(item.target.parent, os.O_RDONLY)+ try:+ assets.fcntl.flock(holder, assets.fcntl.LOCK_EX | assets.fcntl.LOCK_NB)+ with pytest.raises(assets.AssetError, match="already downloading"):+ assets.fetch(item, lambda done: None, opener=no_network)+ finally:+ os.close(holder)+ assets.fetch(item, lambda done: None, opener=opener_for(PAYLOAD))+ assert item.target.read_bytes() == PAYLOAD+++def test_space_check_counts_partial_downloads_and_refuses_with_numbers(tmp_path, monkeypatch):+ ext_dir, install = _pack_list(tmp_path, size=10 * 10 ** 9)+ [item] = assets.default_files(ext_dir, install, "nvidia")+ usage = shutil.disk_usage(tmp_path)+ monkeypatch.setattr(assets.shutil, "disk_usage",+ lambda path: usage._replace(free=5 * 10 ** 9))+ with pytest.raises(assets.AssetError, match=r"needs 10\.0 GB plus 2\.1 GB to spare.*has 5\.0 GB free"):+ assets.check_space([item])+ monkeypatch.setattr(assets.shutil, "disk_usage",+ lambda path: usage._replace(free=13 * 10 ** 9))+ assets.check_space([item])+++def test_the_command_line_fetches_what_is_missing(tmp_path, monkeypatch, capsys):+ ext_dir, install = _pack_list(tmp_path)+ monkeypatch.setattr(assets.urllib.request, "urlopen", opener_for(PAYLOAD))+ assert assets.main([str(ext_dir), str(install), "nvidia"]) == 0+ assert "Test model is ready (SHA-256 verified)" in capsys.readouterr().out+ assert assets.main([str(ext_dir), str(install), "nvidia"]) == 0+ assert "already in place" in capsys.readouterr().out+++def test_the_command_line_reports_a_failure(tmp_path, monkeypatch, capsys):+ ext_dir, install = _pack_list(tmp_path, sha256="0" * 64)+ monkeypatch.setattr(assets.urllib.request, "urlopen", opener_for(PAYLOAD))+ assert assets.main([str(ext_dir), str(install), "nvidia"]) == 1+ assert "ERROR:" in capsys.readouterr().err+++def test_the_command_line_resumes_through_dropped_connections(tmp_path, monkeypatch, capsys):+ ext_dir, install = _pack_list(tmp_path)+ seen = []+ monkeypatch.setattr(assets.urllib.request, "urlopen", opener_sequence(+ OSError("connect failed"),+ Response(PAYLOAD[:5000]),+ Response(PAYLOAD[5000:], status=206),+ seen=seen))+ assert assets.main([str(ext_dir), str(install), "nvidia", "--attempts", "3", "--retry-delay", "0"]) == 0+ assert "Range" not in seen[1] and seen[2]["Range"] == "bytes=5000-"+ out = capsys.readouterr().out+ assert "dropped (OSError); resuming in 0 s (try 2 of 3)" in out+ assert "dropped (ended early); resuming in 0 s (try 3 of 3)" in out and "Test model is ready" in out+ # The installer summary would read these words as a failure.+ assert not any(word in out for word in ("ERROR", "FAILED", "failed"))+++def test_the_command_line_does_not_retry_what_a_retry_cannot_fix(tmp_path, monkeypatch, capsys):+ ext_dir, install = _pack_list(tmp_path, sha256="0" * 64)+ seen = []+ monkeypatch.setattr(assets.urllib.request, "urlopen", opener_sequence(Response(PAYLOAD), seen=seen))+ assert assets.main([str(ext_dir), str(install), "nvidia", "--attempts", "6", "--retry-delay", "0"]) == 1+ assert len(seen) == 1+ assert "did not match its pinned SHA-256" in capsys.readouterr().err+++def test_the_command_line_reports_a_malformed_pack_list(tmp_path, capsys):+ ext_dir = tmp_path / "ext"+ ext_dir.mkdir()+ (ext_dir / "model-packs.json").write_text('{"schema": "ods.model-packs.v1", "packs": []}', encoding="utf-8")+ assert assets.main([str(ext_dir), str(tmp_path), "nvidia"]) == 1+ assert capsys.readouterr().err.startswith("ERROR: ")+++def test_the_comfyui_pack_list_parses_for_both_gpu_backends(tmp_path):+ comfyui = ODS / "extensions/services/comfyui"+ for backend in ("nvidia", "amd"):+ [item] = assets.default_files(comfyui, tmp_path, backend)+ assert item.target.name == "sdxl_lightning_4step.safetensors"+ assert item.size == 6938040682