Skip to content

The agent that grows with you

fix(local-runtime): limit archive fix to incomplete downloads

Ryan Hillea09e2e40157
diff --git a/hermes_cli/local_runtime/binaries.py b/hermes_cli/local_runtime/binaries.py
index 9b62264643b..6cc7a919297 100644
--- a/hermes_cli/local_runtime/binaries.py
+++ b/hermes_cli/local_runtime/binaries.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import gzip
import hashlib
import json
import logging
@@ -10,10 +9,8 @@ import os
import platform
import shutil
import subprocess
-import tarfile
import urllib.request
import zipfile
-import zlib
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
@@ -218,6 +215,7 @@ def _extract(archive: Path, dest: Path,
opener, list_members, size = zipfile.ZipFile, "infolist", "file_size"
kwargs = {}
else:
+ import tarfile
opener, list_members, size = tarfile.open, "getmembers", "size"
kwargs = {"filter": "data"}
with opener(archive) as ar:
@@ -299,31 +297,19 @@ def ensure_runtime_installed(tag: str, backend: str,
for i, asset in enumerate(plan.assets, 1):
label = f"{i}/{n_assets}" if n_assets > 1 else ""
archive = downloads / asset
- # Older versions could cache truncated responses. Replace a corrupt
- # cache entry once; a corrupt fresh download must fail and be evicted.
- for attempt in range(2):
- cached = archive.exists()
- if not cached:
- _download(RELEASE_URL.format(tag=tag, asset=asset), archive,
- progress=stage_progress("download", label))
- if progress is not None:
- progress("verify", 0, 0, label)
- digest = _sha256(archive)
- expected = (expected_sha256 or {}).get(asset)
- if expected and digest != expected:
- archive.unlink(missing_ok=True)
- raise BinaryResolutionError(
- f"sha256 mismatch for {asset}: expected {expected}, got {digest}")
- try:
- _extract(archive, install_dir, progress=stage_progress("extract", label))
- except (zipfile.BadZipFile, tarfile.ReadError, gzip.BadGzipFile, EOFError, zlib.error) as exc:
- archive.unlink(missing_ok=True)
- if not cached or attempt == 1:
- raise BinaryResolutionError(f"invalid runtime archive {asset}: {exc}") from exc
- logger.warning("discarding corrupt cached runtime archive %s: %s", asset, exc)
- else:
- break
+ if not archive.exists():
+ _download(RELEASE_URL.format(tag=tag, asset=asset), archive,
+ progress=stage_progress("download", label))
+ if progress is not None:
+ progress("verify", 0, 0, label)
+ digest = _sha256(archive)
+ expected = (expected_sha256 or {}).get(asset)
+ if expected and digest != expected:
+ archive.unlink(missing_ok=True)
+ raise BinaryResolutionError(
+ f"sha256 mismatch for {asset}: expected {expected}, got {digest}")
recorded[asset] = digest
+ _extract(archive, install_dir, progress=stage_progress("extract", label))
if progress is not None:
progress("verify", 0, 0, "")
diff --git a/tests/hermes_cli/test_local_runtime_downloads.py b/tests/hermes_cli/test_local_runtime_downloads.py
index 55233083a55..e79d5dca063 100644
--- a/tests/hermes_cli/test_local_runtime_downloads.py
+++ b/tests/hermes_cli/test_local_runtime_downloads.py
@@ -1,14 +1,7 @@
"""Runtime downloads must not turn a transient transfer failure into a poisoned cache."""
-import hashlib
-import io
-import json
-import sys
-import tarfile
import threading
-import zipfile
from http.server import BaseHTTPRequestHandler, HTTPServer
-from pathlib import Path
import pytest
@@ -45,7 +38,8 @@ def asset_server():
@pytest.mark.parametrize("failure", ["short", "callback"])
-def test_download_only_publishes_complete_transfers(tmp_path, asset_server, failure):
[email protected]("known_length", [True, False])
+def test_download_only_publishes_complete_transfers(tmp_path, asset_server, failure, known_length):
url, responses, requests = asset_server
dest = tmp_path / "runtime.zip"
payload = b"runtime archive bytes"
@@ -62,74 +56,10 @@ def test_download_only_publishes_complete_transfers(tmp_path, asset_server, fail
assert not dest.with_suffix(".zip.part").exists()
# A retry works, including servers that omit Content-Length.
- responses.append((payload, None))
+ responses.append((payload, len(payload) if known_length else None))
ticks = []
binaries._download(url.format(asset=dest.name), dest,
progress=lambda done, total: ticks.append((done, total)))
assert dest.read_bytes() == payload
- assert ticks[-1] == (len(payload), 0)
+ assert ticks[-1] == (len(payload), len(payload) if known_length else 0)
assert len(requests) == 2
-
-
[email protected]("archive_format,corruption", [
- ("zip", "truncated"), ("zip", "crc"), ("tar.gz", "truncated"),
-])
[email protected]("replacement_kind", ["valid", "invalid", "permission"])
-def test_install_recovers_corrupt_cache_once(tmp_path, monkeypatch, asset_server,
- archive_format, corruption, replacement_kind):
- url, responses, requests = asset_server
- # Use the real cache/root resolution, HTTP transfer, digest and extraction.
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- tag = f"b{sys.version_info.major}"
- asset = f"runtime.{archive_format}"
- plan = binaries.AssetPlan(tag, "cpu", [asset])
- monkeypatch.setattr(binaries, "resolve_assets", lambda *args: plan)
- monkeypatch.setattr(binaries, "RELEASE_URL", url)
- # Exercise the real --version subprocess without downloading a native runtime.
- monkeypatch.setattr(binaries, "server_binary", lambda _: Path(sys.executable))
- payload = b"complete runtime payload"
- stream = io.BytesIO()
- if archive_format == "zip":
- with zipfile.ZipFile(stream, "w") as archive:
- archive.writestr("bin/runtime.dat", payload)
- else:
- with tarfile.open(fileobj=stream, mode="w:gz") as archive:
- member = tarfile.TarInfo("bin/runtime.dat")
- member.size = len(payload)
- archive.addfile(member, io.BytesIO(payload))
- valid = stream.getvalue()
- corrupt = (valid.replace(payload, b"!" * len(payload))
- if corruption == "crc" else valid[:10])
- cached = binaries.runtimes_root() / "downloads" / asset
- cached.parent.mkdir(parents=True)
- cached.write_bytes(corrupt)
- replacement = valid if replacement_kind == "valid" else corrupt
- responses.append((replacement, len(replacement)))
- ticks = []
-
- if replacement_kind == "permission":
- def denied(*args, **kwargs):
- raise PermissionError("destination is not writable")
-
- monkeypatch.setattr(binaries, "_extract", denied)
- with pytest.raises(PermissionError):
- binaries.ensure_runtime_installed(tag, "cpu")
- assert cached.read_bytes() == corrupt
- assert not requests
- return
-
- if replacement_kind == "valid":
- installed = binaries.ensure_runtime_installed(tag, "cpu", progress=lambda *p: ticks.append(p))
- assert (installed / "bin/runtime.dat").read_bytes() == payload
- manifest = json.loads((installed / "manifest.json").read_text(encoding="utf-8"))
- assert manifest["assets"][asset] == hashlib.sha256(valid).hexdigest()
- assert manifest["verified_version"]
- assert cached.read_bytes() == valid
- assert {p[0] for p in ticks} == {"download", "verify", "extract"}
- assert binaries.ensure_runtime_installed(tag, "cpu") == installed
- else:
- with pytest.raises(binaries.BinaryResolutionError, match="archive"):
- binaries.ensure_runtime_installed(tag, "cpu")
- assert not cached.exists()
- assert not (plan.install_dir / "manifest.json").exists()
- assert len(requests) == 1