The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): tolerate stale catalog sizes — completeness is the server's own length
emozillae2423491d47d
diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex a52dbf996d9..b1b964cbc76 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -122,16 +122,17 @@ def _variant_files_on_disk(model_id: str) -> "list[Path]":def download_file(url: str, dest: Path, job: Dict[str, Any],*,- expected_bytes: int = 0,base_done: int = 0, keep_totals: bool = False) -> None:"""Download url -> dest with byte progress on ``job``.Ranged-parallel when the server supports it, single-stream fallback- otherwise. There is no hash check by design (product decision) — the- byte count against ``expected_bytes`` (the catalog size) is the one- remaining wrong-file tripwire: a short or oversized body errors the- job instead of staging a file llama.cpp will crash on later. Never- leaves a .part behind.+ otherwise. There is no integrity check against the CATALOG by design+ (product decision): catalog sizes may lag an upstream re-upload, and a+ newer file than we know about must download fine. Completeness is+ checked only against what the SERVER declared for this transfer+ (range-probe total / Content-Length) — self-consistent and always+ current — so a dropped connection still errors instead of staging a+ truncated file. Never leaves a .part behind.Multi-file variants: ``base_done`` offsets the progress so this file'sbytes accumulate onto the files before it, and ``keep_totals=True``@@ -198,7 +199,9 @@ def download_file(url: str, dest: Path, job: Dict[str, Any],raise RuntimeError(f"download incomplete ({file_done[0]} of {total} bytes)")else:- # No range support: single stream, large chunks.+ # No range support: single stream, large chunks. Completeness+ # is judged by the server's own Content-Length when it sent+ # one — never by the catalog, which may lag a re-upload.with urllib.request.urlopen(url, timeout=120) as r, open(tmp, "wb") as f:length = int(r.headers.get("Content-Length") or 0)if length and not keep_totals:@@ -209,11 +212,11 @@ def download_file(url: str, dest: Path, job: Dict[str, Any],breakf.write(chunk)bump(len(chunk))+ if length and file_done[0] != length:+ raise RuntimeError(+ f"Download ended at {file_done[0]:,} bytes but the server "+ f"said {length:,} — connection dropped? Removed; try again")- if expected_bytes and file_done[0] != expected_bytes:- raise RuntimeError(- f"Download ended at {file_done[0]:,} bytes but this file "- f"should be {expected_bytes:,} — removed; try again")shutil.move(str(tmp), str(dest))except Exception:tmp.unlink(missing_ok=True)@@ -707,7 +710,7 @@ async def local_models_download(body: ModelDownloadBody):done_before += sizejob["done_bytes"] = done_beforecontinue- download_file(url, dest, job, expected_bytes=size,+ download_file(url, dest, job,base_done=done_before, keep_totals=True)job["phase"] = "downloading"done_before += sizediff --git a/tests/hermes_cli/test_catalog_reachability.py b/tests/hermes_cli/test_catalog_reachability.pyindex 94eff1d71f0..1b7fa5b9915 100644--- a/tests/hermes_cli/test_catalog_reachability.py+++ b/tests/hermes_cli/test_catalog_reachability.py@@ -1,11 +1,15 @@-"""Catalog reachability: every entry's files must exist upstream with the-size the catalog claims (sizes feed the fit estimator and the download-progress bar, and a silent upstream re-upload that changes file size means-the fit math is stale).+"""Catalog reachability: every entry's repo and files must exist upstream.++Existence is the contract; SIZES are advisory (they feed the estimator and+progress bars, and downloads deliberately tolerate a stale size when+upstream re-uploads — completeness is judged against the server's own+declared length, never the catalog). Size drift prints as a warning so a+catalog refresh can be batched deliberately; only a MISSING file or repo+fails.Network-marked (skipped in hermetic CI unless explicitly enabled) — this is-the test that catches wrong repo names (the Nemotron 401), moved files, and-re-uploads that resize files. Run before any catalog commit:+the test that catches wrong repo names (the Nemotron 401) and moved files.+Run before any catalog commit:HERMES_TEST_NETWORK=1 scripts/run_tests.sh tests/hermes_cli/test_catalog_reachability.py"""@@ -28,6 +32,7 @@ def test_every_catalog_file_resolves():from hermes_cli.local_runtime.catalog import CATALOGproblems = []+ drift = []for entry in CATALOG:url = f"https://huggingface.co/api/models/{entry.repo}/tree/main?recursive=true"try:@@ -44,8 +49,11 @@ def test_every_catalog_file_resolves():continuelive_size = files[asset.path]if live_size and live_size != asset.size_bytes:- problems.append(+ drift.append(f"{entry.id}/{variant.quant}: size drift on {asset.path} — "- f"catalog {asset.size_bytes} vs live {live_size} "- f"(upstream re-uploaded; refresh the size deliberately)")+ f"catalog {asset.size_bytes} vs live {live_size}")+ if drift:+ print("\nADVISORY size drift (downloads tolerate this; refresh when convenient):")+ print("\n".join(drift))assert not problems, "\n".join(problems)+diff --git a/tests/hermes_cli/test_local_models_routes.py b/tests/hermes_cli/test_local_models_routes.pyindex aaecc9d9040..6ee98aae1ea 100644--- a/tests/hermes_cli/test_local_models_routes.py+++ b/tests/hermes_cli/test_local_models_routes.py@@ -124,14 +124,16 @@ def test_download_unknown_model_404s(client):assert r.status_code == 404-def test_download_job_short_body_errors_and_cleans_up(client, monkeypatch):- """A download that delivers fewer bytes than the file's size must error- the job and leave nothing staged — with no hash check (product- decision: no download-time integrity verification), the byte count is- the only remaining wrong-file tripwire, so it must hold."""+def test_download_short_of_server_length_errors_and_cleans_up(client, monkeypatch):+ """Catalog sizes are advisory (upstream re-uploads may make them+ stale — a mismatch against the CATALOG must not fail a download).+ The server's own declared length is the only completeness check:+ fewer bytes than the server promised means a dropped connection, so+ the job errors and nothing is staged."""class FakeResponse(io.BytesIO):- headers = {"Content-Length": "16"}+ # Body is 17 bytes; the server promises 32 — a truncated stream.+ headers = {"Content-Length": "32"}def __enter__(self):return self@@ -237,3 +239,55 @@ def test_eject_without_supervisor_is_not_a_500(client, monkeypatch):"hermes_cli.web_routers.local_models._state_endpoint", lambda: None)r = client.post("/api/local-models/eject", json={"model_id": "anything"})assert r.status_code == 409, (r.status_code, r.text)+++def test_download_tolerates_stale_catalog_size(client, monkeypatch):+ """Upstream re-uploads make catalog sizes stale; a download whose+ delivered bytes are self-consistent with the SERVER's declared length+ must succeed even when the catalog said something else. (This is the+ tolerance the sha removal was for — being out of date must not break+ downloads.)"""++ body = b"x" * 48 # server-consistent: Content-Length == body length++ class FakeResponse(io.BytesIO):+ headers = {"Content-Length": str(len(body))}++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ monkeypatch.setattr("urllib.request.urlopen",+ lambda *a, **k: FakeResponse(body))++ from hermes_cli.local_runtime.estimator import HardwareBudget++ budget = HardwareBudget(usable_vram_bytes=64 << 30,+ total_device_bytes=64 << 30,+ ram_available_bytes=64 << 30)+ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",+ lambda **kw: budget)+ # Keep the post-download server bounce out of this unit.+ monkeypatch.setattr(+ "hermes_cli.local_runtime.bootstrap.refresh_local_runtime",+ lambda: False)++ from hermes_cli.local_runtime.catalog import CATALOG++ # Catalog size for this entry is in the tens of GB — wildly stale+ # versus our 48-byte body. The download must still land.+ entry_id = CATALOG[0].id+ r = client.post("/api/local-models/download", json={"model_id": entry_id})+ assert r.status_code == 200+ job_id = r.json()["job_id"]++ deadline = time.time() + 10+ status = None+ while time.time() < deadline:+ status = client.get(f"/api/local-models/jobs/{job_id}").json()+ if status["status"] in ("done", "error"):+ break+ time.sleep(0.05)+ assert status is not None and status["status"] == "done", status.get("error")