The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): isolate download staging files
emozilla3c5659178874
diff --git a/hermes_cli/local_runtime/binaries.py b/hermes_cli/local_runtime/binaries.pyindex 6cc7a919297..c304f06ffa2 100644--- a/hermes_cli/local_runtime/binaries.py+++ b/hermes_cli/local_runtime/binaries.py@@ -9,6 +9,7 @@ import osimport platformimport shutilimport subprocess+import tempfileimport urllib.requestimport zipfilefrom dataclasses import dataclass, field@@ -185,9 +186,11 @@ def _download(url: str, dest: Path,"""Stream url -> dest. ``progress(done_bytes, total_bytes)`` ticks per chunk (total 0 whenthe server sends no Content-Length) — a several-hundred-MB archive must never look hung."""logger.info("downloading %s", url)- tmp = dest.with_suffix(dest.suffix + ".part")+ staging = tempfile.NamedTemporaryFile(+ mode="wb", dir=dest.parent, prefix=f"{dest.name}.", suffix=".part", delete=False)+ tmp = Path(staging.name)try:- with urllib.request.urlopen(url, timeout=120) as r, open(tmp, "wb") as f:+ with staging as f, urllib.request.urlopen(url, timeout=120) as r:length = r.headers.get("Content-Length")total = int(length) if length is not None else 0done = 0diff --git a/tests/hermes_cli/test_local_runtime_downloads.py b/tests/hermes_cli/test_local_runtime_downloads.pyindex e79d5dca063..c0ac8558e49 100644--- a/tests/hermes_cli/test_local_runtime_downloads.py+++ b/tests/hermes_cli/test_local_runtime_downloads.py@@ -1,7 +1,9 @@"""Runtime downloads must not turn a transient transfer failure into a poisoned cache."""import threading-from http.server import BaseHTTPRequestHandler, HTTPServer+from concurrent.futures import ThreadPoolExecutor+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.error import HTTPErrorimport pytest@@ -16,8 +18,8 @@ def asset_server():class Handler(BaseHTTPRequestHandler):def do_GET(self):requests.append(self.path)- body, length = responses.pop(0)- self.send_response(200)+ body, length, status = responses.pop(0)+ self.send_response(status)if length is not None:self.send_header("Content-Length", str(length))self.end_headers()@@ -27,7 +29,7 @@ def asset_server():def log_message(self, *args):pass- with HTTPServer(("127.0.0.1", 0), Handler) as server:+ with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()try:@@ -43,7 +45,7 @@ def test_download_only_publishes_complete_transfers(tmp_path, asset_server, failurl, responses, requests = asset_serverdest = tmp_path / "runtime.zip"payload = b"runtime archive bytes"- responses.append((payload[:-1], len(payload)))+ responses.append((payload[:-1], len(payload), 200))def progress(done, total):if failure == "callback":@@ -53,13 +55,42 @@ def test_download_only_publishes_complete_transfers(tmp_path, asset_server, failwith pytest.raises(error):binaries._download(url.format(asset=dest.name), dest, progress=progress)assert not dest.exists()- assert not dest.with_suffix(".zip.part").exists()+ assert not list(tmp_path.glob("*.part"))# A retry works, including servers that omit Content-Length.- responses.append((payload, len(payload) if known_length else None))+ responses.append((payload, len(payload) if known_length else None, 200))ticks = []binaries._download(url.format(asset=dest.name), dest,progress=lambda done, total: ticks.append((done, total)))assert dest.read_bytes() == payloadassert ticks[-1] == (len(payload), len(payload) if known_length else 0)assert len(requests) == 2+++def test_failed_request_preserves_another_active_download(tmp_path, asset_server):+ url, responses, requests = asset_server+ dest = tmp_path / "runtime.zip"+ payload = b"x" * (2 << 20)+ responses.extend([(payload, len(payload), 200), (b"", 0, 503)])+ started = threading.Event()+ resume = threading.Event()++ def pause_download(done, total):+ started.set()+ assert resume.wait(10), "active download was not resumed"++ with ThreadPoolExecutor(max_workers=1) as pool:+ active = pool.submit(binaries._download, url.format(asset=dest.name), dest,+ progress=pause_download)+ try:+ assert started.wait(10), "active download did not write its first chunk"+ with pytest.raises(HTTPError) as failed:+ binaries._download(url.format(asset=dest.name), dest)+ assert failed.value.code == 503+ finally:+ resume.set()+ active.result(timeout=10)++ assert dest.read_bytes() == payload+ assert not list(tmp_path.glob("*.part"))+ assert len(requests) == 2