The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): remove download archives after package publication
ethernet949a50830810
diff --git a/docs/shared-bundle-builds.md b/docs/shared-bundle-builds.mdindex 7cec3f69f4f..a50aa14bae6 100644--- a/docs/shared-bundle-builds.md+++ b/docs/shared-bundle-builds.md@@ -85,6 +85,12 @@ selected PM executable; direct Playwright callers select the `chromium` channel.Native staging removes retired package facts and directories from its buildcache. It does not remove browser files from the user's machine-wide store.+PM retains completed download archives until the package is verified and+published. Normal installs commit package facts before deleting their archives.+Cross-target staging verifies the published entry before deleting its archives.+Failed or paused installs keep downloads for retry. Cleanup leaves unrelated+archives and resumable partials alone. A later repair may download again.+## Verification boundaryTests execute shared snapshot/manifest helpers on real git fixtures, stagediff --git a/pm/ensure.py b/pm/ensure.pyindex 5d96697337f..090e136f78f 100644--- a/pm/ensure.py+++ b/pm/ensure.py@@ -180,6 +180,12 @@ def _remove_entry(store: Store, entry_name: str) -> None:time.sleep(0.2 * (attempt + 1))+def _remove_downloads(store: Store, artifacts: list[dict]) -> None:+ """Release this package's archives after publication, under its store lock."""+ for artifact in artifacts:+ _remove_entry(store, f"fetch-{artifact['sha256']}")++def _entry_verified(package: Package, fact: dict, store: Store, target: str) -> bool:"""Explicit installs re-check realized bytes; startup keeps its cheap facts check."""entry = store.entry(fact["entry"])@@ -247,6 +253,7 @@ def _install(if facts.installed(package.name, version, store.root, _identity(lockfile, package.name, target)) and _entry_verified(package, facts.get(package.name), store, target):+ _remove_downloads(store, artifacts)returnif not artifacts:raise InstallError(@@ -308,6 +315,7 @@ def _install(raiseif previous_entry.exists():_remove_entry(store, previous_entry.name)+ _remove_downloads(store, artifacts)except (InstallError, DownloadPaused):raiseexcept Exception as e:@@ -367,6 +375,7 @@ def stage_only(name: str, target: str, progress=None) -> "Path":except OSError:recorded = Noneif not package.verify(entry, target) and recorded == pin:+ _remove_downloads(store, artifacts)return entryif not artifacts:raise InstallError(@@ -406,6 +415,7 @@ def stage_only(name: str, target: str, progress=None) -> "Path":raiseif previous_entry.exists():_remove_entry(store, previous_entry.name)+ _remove_downloads(store, artifacts)return store.entry(entry_name)diff --git a/pm/store.py b/pm/store.pyindex 7dba809be49..8fd8639097d 100644--- a/pm/store.py+++ b/pm/store.py@@ -261,7 +261,7 @@ def tree_digest(root: Path) -> str:class Store:"""One directory of immutable published entries plus a scratch area.- Downloads are entries too, keyed by hash, so rebuilds never re-fetch."""+ Hash-keyed archives survive failed installs. Publication releases them."""def __init__(self, root: Path):self.root = rootdiff --git a/tests/docker/test_image_payload.py b/tests/docker/test_image_payload.pyindex d876f6dd888..105e033820f 100644--- a/tests/docker/test_image_payload.py+++ b/tests/docker/test_image_payload.py@@ -13,6 +13,7 @@ from pm.registry import get_packagefrom pm.store import current_targetstore = Path('/opt/hermes/tools')+assert not list(store.glob('fetch-*')), 'completed download archives must not ship'fact = Facts(store / 'facts.json').get('python')expected = get_package('python').binary(store / fact['entry'], current_target())assert Path(sys._base_executable).resolve() == expected.resolve()diff --git a/tests/pm/test_download_cleanup.py b/tests/pm/test_download_cleanup.pynew file mode 100644index 00000000000..42e4e6f0211--- /dev/null+++ b/tests/pm/test_download_cleanup.py@@ -0,0 +1,123 @@+"""Archive lifetime follows package publication, not transfer completion."""+from __future__ import annotations++import hashlib+import io+from pathlib import Path+import zipfile++import pytest++import pm+from pm import paths, registry+from pm.ensure import stage_only+from pm.lock import Facts, Lockfile+from pm.package import Package+from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401+++class Components(Package):+ name = "cleanup-components"++ def verify(self, entry, target):+ return "" if (entry / "engine").is_file() and (entry / "library").is_file() else "incomplete package"+++def install_case(tmp_path, monkeypatch, dl_server):+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ store = tmp_path / "store"+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))+ lock_path = tmp_path / "lock.json"+ monkeypatch.setattr(paths, "lockfile_path", lambda: lock_path)+ package = Components()+ monkeypatch.setitem(registry._packages, package.name, package)+ pins = []+ for name in ("engine", "library"):+ data = io.BytesIO()+ with zipfile.ZipFile(data, "w") as archive:+ archive.writestr(name, name.encode())+ path = f"/{name}.zip"+ RangeHandler.payloads[path] = data.getvalue()+ pins.append({"url": url(dl_server, path), "sha256": hashlib.sha256(data.getvalue()).hexdigest()})+ lock = Lockfile(lock_path)+ lock.set_pin(package.name, "1", {pm.current_target(): pins})+ lock.save()+ other = store / ("fetch-" + "f" * 64)+ other.mkdir(parents=True)+ (other / "other.zip").write_bytes(b"another install's download")+ partial = paths.partials_root() / "unrelated.part"+ partial.parent.mkdir(parents=True, exist_ok=True)+ partial.write_bytes(b"in-progress download")+ return package, store, pins, other, partial+++def install(package, mode):+ if mode == "stage":+ return stage_only(package.name, pm.current_target())+ pm.ensure(package.name, explicit=True, base_env={})+ return pm.installed_package(package.name).path++[email protected]("mode", ["install", "stage"])+def test_publication_removes_only_its_archives(install_case, mode):+ package, store, pins, other, partial = install_case+ entry = install(package, mode)+ for name in ("engine", "library"):+ assert (entry / name).read_bytes() == name.encode()+ assert not any((store / f"fetch-{pin['sha256']}").exists() for pin in pins)+ assert (other / "other.zip").read_bytes() == b"another install's download"+ assert partial.read_bytes() == b"in-progress download"+ RangeHandler.payloads.clear()+ assert install(package, mode) == entry # Already installed works offline without archives.++[email protected](("mode", "failure"), [+ (mode, failure)+ for mode in ("install", "stage")+ for failure in ("unpack", "verify", "publish", "published-verify", "facts")+ if mode == "install" or failure != "facts"+])+def test_failure_keeps_archives_for_offline_retry(install_case, monkeypatch, mode, failure):+ package, store, pins, _, _ = install_case+ original_verify = package.verify+ original_unpack = package.unpack++ def fail(*args, **kwargs):+ raise pm.InstallError(package.name, "injected failure")++ def unpack(archive, staged, target):+ original_unpack(archive, staged, target)+ if (staged / "library").exists():+ fail()++ def verify(entry, target):+ published = entry.parent == store+ if failure == "verify" or published:+ fail()+ return original_verify(entry, target)++ with monkeypatch.context() as fault:+ if failure == "unpack":+ fault.setattr(package, "unpack", unpack)+ elif failure in ("verify", "published-verify"):+ fault.setattr(package, "verify", verify)+ elif failure == "publish":+ original_publish = pm.Store.publish++ def publish(self, staged, name):+ if name.startswith(package.name):+ fail()+ return original_publish(self, staged, name)++ fault.setattr(pm.Store, "publish", publish)+ else:+ fault.setattr(Facts, "record", fail)+ with pytest.raises(pm.InstallError, match="injected failure"):+ install(package, mode)+ assert all((store / f"fetch-{pin['sha256']}").is_dir() for pin in pins)+ RangeHandler.payloads.clear()+ entry = install(package, mode)+ assert (entry / "engine").read_bytes() == b"engine"+ assert not any((store / f"fetch-{pin['sha256']}").exists() for pin in pins)diff --git a/tests/pm/test_install_download_control.py b/tests/pm/test_install_download_control.pyindex 60cf5e83ebb..c6d9dbd5708 100644--- a/tests/pm/test_install_download_control.py+++ b/tests/pm/test_install_download_control.py@@ -6,6 +6,7 @@ import hashlibimport ioimport threadingimport zipfile+from pathlib import Pathimport pytest@@ -29,6 +30,12 @@ def archive(files: dict[str, bytes]) -> bytes:return output.getvalue()[email protected](autouse=True)+def isolate_home(tmp_path, monkeypatch):+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))++def test_install_pause_preserves_archives_and_resumes_the_same_pin(tmp_path, monkeypatch, dl_server):root = tmp_path / "store"lock_path = tmp_path / "lock.json"@@ -68,6 +75,7 @@ def test_install_pause_preserves_archives_and_resumes_the_same_pin(tmp_path, monassert (root / fact["entry"] / name).read_bytes() == bodyassert [request for request in RangeHandler.ranges_seen if request[0] == "/component-0.zip"] == first_requestsassert not list(paths.partials_root().glob("*.part"))+ assert not list(root.glob("fetch-*"))def test_install_progress_covers_all_archives_including_cache(tmp_path, monkeypatch, dl_server):diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.pyindex 0bb83ead6ad..c4e7e8c0c3f 100644--- a/tests/pm/test_pm_core.py+++ b/tests/pm/test_pm_core.py@@ -93,6 +93,8 @@ def served(tmp_path):def pm_env(tmp_path, served, monkeypatch):docroot, base_url = servedruntime = tmp_path / "runtime"+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))monkeypatch.setenv("HERMES_RUNTIME_DIR", str(runtime))monkeypatch.delenv("HERMES_DISABLE_LAZY_INSTALLS", raising=False)# Policy is pinned open here; the disabled-path tests pin it closed.@@ -161,10 +163,11 @@ def test_bad_hash_rejected(pm_env):def test_fetch_is_a_store_entry(pm_env):- from pm.ensure import ensure-- _, runtime, docroot, _ = pm_env- ensure("faketool", base_env={})+ lock_path, runtime, _, _ = pm_env+ artifact = Lockfile(lock_path).artifacts("faketool", current_target())[0]+ store = Store(runtime)+ with store.scratch() as scratch:+ store.fetch(artifact["url"], artifact["sha256"], scratch)fetches = [p for p in runtime.iterdir() if p.name.startswith("fetch-")]assert len(fetches) == 1@@ -426,12 +429,15 @@ def test_gc_removes_fetch_cache_archives(pm_env):from pm.cli import cmd_gcfrom pm.ensure import ensure- _, runtime, *_ = pm_env+ lock_path, runtime, *_ = pm_envensure("faketool", base_env={})-- # install() fetched via store.fetch → a fetch-<sha> archive cache dir.+ # Downloads not consumed by a successful install remain eligible for GC.+ artifact = Lockfile(lock_path).artifacts("faketool", current_target())[0]+ store = Store(runtime)+ with store.scratch() as scratch:+ store.fetch(artifact["url"], artifact["sha256"], scratch)fetches = [p for p in runtime.iterdir() if p.name.startswith("fetch-")]- assert fetches, "install should have left fetch-<sha> download-cache dirs"+ assert fetchescmd_gc(None)assert not [p for p in runtime.iterdir() if p.name.startswith("fetch-")], \diff --git a/tests/pm/test_stage_only.py b/tests/pm/test_stage_only.pyindex 43b9acbb23f..377b779c70e 100644--- a/tests/pm/test_stage_only.py+++ b/tests/pm/test_stage_only.py@@ -66,6 +66,8 @@ def _seed_fetch_cache(store: Store, payload: bytes) -> None:@pytest.fixture()def sandbox(tmp_path, monkeypatch):runtime = tmp_path / "runtime"+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))monkeypatch.setenv("HERMES_RUNTIME_DIR", str(runtime))store = Store(runtime)package = _FakePackage()