Skip to content

The agent that grows with you

fix(pm): reuse upstream responses and new artifact hashes per update

ethernet308d653baadb
diff --git a/pm/cli.py b/pm/cli.py
index cd666e8ff5f..6b4f21178f2 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -16,9 +16,10 @@ from pm.package import InstallError
from pm.paths import repo_root
from pm.registry import get_package
from pm.store import ALL_TARGETS, current_target, hash_url
-from pm.update import Resolved, resolve_package
+from pm.update import Resolved, resolve_package, reuse_index_responses
+@reuse_index_responses()
def cmd_lock(args) -> int:
"""--bump <name> <version>: resolve every target's archives, hash them,
write. A target with one archive pins the object; several pin a list.
@@ -372,10 +373,12 @@ def cmd_update(args) -> int:
return 0
+@reuse_index_responses()
def _pin_artifacts(package, decision, current: dict) -> dict:
"""Retain unresolved targets and reuse hashes for unchanged artifact URLs."""
per_target = decision.per_target or {t: decision.version for t in ALL_TARGETS}
artifacts = dict(current)
+ hashes: dict[str, str] = {}
for target, version in per_target.items():
if package.missing_reason(target) is not None:
continue
@@ -387,8 +390,13 @@ def _pin_artifacts(package, decision, current: dict) -> dict:
urls = package.fetch_urls(version, target)
if urls == [row["url"] for row in old]:
continue
- pinned = [{"url": url, "sha256": known.get(url) or package.known_sha256(version, url) or hash_url(url)}
- for url in urls]
+ pinned = []
+ for url in urls:
+ digest = known.get(url) or hashes.get(url)
+ if not digest:
+ digest = package.known_sha256(version, url) or hash_url(url)
+ hashes[url] = digest
+ pinned.append({"url": url, "sha256": digest})
artifacts[target] = pinned[0] if len(pinned) == 1 else pinned
return artifacts
diff --git a/pm/update.py b/pm/update.py
index 73fb7652a82..1e73528b591 100644
--- a/pm/update.py
+++ b/pm/update.py
@@ -29,12 +29,30 @@ import json
import os
import re
import urllib.request
+from contextlib import contextmanager
+from contextvars import ContextVar
from dataclasses import dataclass, field
-from typing import Optional
+from typing import Iterator, Optional
from pm.network import retry_network
from pm.registry import get_package
+
+# The context holds no data outside a resolve/pin call, including failed calls.
+# Keep the Package hooks unchanged while sharing their nested index requests.
+_index_responses: ContextVar[dict | None] = ContextVar("pm_index_responses", default=None)
+
+
+@contextmanager
+def reuse_index_responses() -> Iterator[None]:
+ """Share successful index reads only within this resolve or pin operation."""
+ token = _index_responses.set({})
+ try:
+ yield
+ finally:
+ _index_responses.reset(token)
+
+
# ---------------------------------------------------------------------------
# Version parsing / comparison (pure)
# ---------------------------------------------------------------------------
@@ -145,6 +163,7 @@ def resolve_best(
return Resolved(name, locked, style, version=version, per_target={t: version for t in present})
+@reuse_index_responses()
def resolve_package(package, targets: list[str], locked: Optional[str], *, artifacts: dict | None = None) -> Resolved:
"""Resolve versions and detect new artifacts within a shared minor."""
latest = {
@@ -197,10 +216,18 @@ def _get_json(url: str) -> dict | list:
from hermes_cli.urllib_security import open_credentialed_url
def request():
+ headers = _index_headers(url)
+ key = (url, tuple(sorted(headers.items())), "json")
+ responses = _index_responses.get()
+ if responses is not None and key in responses:
+ return responses[key]
with open_credentialed_url(
- urllib.request.Request(url, headers=_index_headers(url)), timeout=60
+ urllib.request.Request(url, headers=headers), timeout=60
) as resp:
- return json.load(resp)
+ result = json.load(resp)
+ if responses is not None:
+ responses[key] = result
+ return result
return retry_network(request)
@@ -213,10 +240,17 @@ def _get_text(url: str, headers: Optional[dict] = None) -> str:
hdrs.update(headers)
def request():
+ key = (url, tuple(sorted(hdrs.items())), "text")
+ responses = _index_responses.get()
+ if responses is not None and key in responses:
+ return responses[key]
with open_credentialed_url(
urllib.request.Request(url, headers=hdrs), timeout=60
) as resp:
- return resp.read().decode("utf-8", "replace")
+ result = resp.read().decode("utf-8", "replace")
+ if responses is not None:
+ responses[key] = result
+ return result
return retry_network(request)
@@ -336,7 +370,7 @@ def node_latest_versions() -> list[str]:
def martin_riedl_index() -> dict[str, dict[str, str]]:
- """ffmpeg.martin-riedl.de index, cached: target -> {version: epoch}.
+ """ffmpeg.martin-riedl.de index: target -> {version: epoch}.
The site has no directory listing or API — the root page is the index,
and it lists the CURRENT build per platform (both snapshot builds like
@@ -344,13 +378,9 @@ def martin_riedl_index() -> dict[str, dict[str, str]]:
<epoch>_<semver> download dir; snapshots never match the numeric
pattern. The epoch is needed to reconstruct the download URL at pin
time, so the index maps version -> epoch per target."""
- cached = _martin_cache.get()
- if cached is not None:
- return cached
try:
page = _get_text("https://ffmpeg.martin-riedl.de/")
except Exception:
- _martin_cache.set({})
return {}
out: dict[str, dict[str, str]] = {}
# /download/<os>/<arch>/<epoch>_<version>/ffmpeg.zip
@@ -364,7 +394,6 @@ def martin_riedl_index() -> dict[str, dict[str, str]]:
versions = out.setdefault(target, {})
if version not in versions or int(epoch) > int(versions[version]):
versions[version] = epoch
- _martin_cache.set(out)
return out
@@ -379,9 +408,6 @@ def btbn_index() -> dict[str, dict[str, tuple[str, str]]]:
Releases also contain Linux, shared and LGPL builds. Retain target
identity here so discovery and pinning select the same artifact.
"""
- cached = _btbn_cache.get()
- if cached is not None:
- return cached
out: dict[str, dict[str, tuple[str, str]]] = {}
for page in range(1, 4):
data = _get_json(f"https://api.github.com/repos/BtbN/FFmpeg-Builds/releases?per_page=30&page={page}")
@@ -404,7 +430,6 @@ def btbn_index() -> dict[str, dict[str, tuple[str, str]]]:
out.setdefault(target, {}).setdefault(version, (tag, name))
if len(data) < 30:
break
- _btbn_cache.set(out)
return out
@@ -433,22 +458,3 @@ def pbs_versions(minor: str, triple: str) -> list[str]:
if len(data) < 30:
break
return []
-
-
-class _TTL:
- """Tiny per-process cache so --check and the pin step share one fetch."""
-
- def __init__(self) -> None:
- self._value: object = None
- self._set = False
-
- def get(self):
- return self._value if self._set else None
-
- def set(self, value: object) -> None:
- self._value = value
- self._set = True
-
-
-_martin_cache = _TTL()
-_btbn_cache = _TTL()
diff --git a/tests/pm/test_ffmpeg_resolution.py b/tests/pm/test_ffmpeg_resolution.py
index d82c9c1ebd1..4fe2843bda9 100644
--- a/tests/pm/test_ffmpeg_resolution.py
+++ b/tests/pm/test_ffmpeg_resolution.py
@@ -10,8 +10,6 @@ from pm.packages import Ffmpeg
@pytest.fixture
def indexes(monkeypatch):
- monkeypatch.setattr(update, "_btbn_cache", update._TTL())
- monkeypatch.setattr(update, "_martin_cache", update._TTL())
tag = "autobuild-2026-09-01-12-00"
version = "9.1.2"
assets = [
diff --git a/tests/pm/test_update_request_reuse.py b/tests/pm/test_update_request_reuse.py
new file mode 100644
index 00000000000..db0d126057f
--- /dev/null
+++ b/tests/pm/test_update_request_reuse.py
@@ -0,0 +1,200 @@
+"""An update reads each successful index/artifact once, not once per target."""
+from __future__ import annotations
+
+from argparse import Namespace
+from collections import Counter
+import hashlib
+import json
+from urllib.error import HTTPError
+from urllib.parse import urlsplit
+
+import pytest
+
+from pm import cli, downloader, packages, update
+from pm.lock import Lockfile
+from pm.registry import get_package
+from pm.store import ALL_TARGETS
+from tests.pm._fixtures import make_tar
+from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
+
+
+def upstream(dl_server, monkeypatch):
+ from hermes_cli import urllib_security
+
+ calls = []
+ failures = {}
+ original_get = RangeHandler.do_GET
+
+ def record(handler):
+ calls.append((handler.path, handler.headers.get("Authorization")))
+ pending = failures.get(handler.path, [])
+ if pending:
+ handler.send_error(pending.pop(0))
+ return
+ original_get(handler)
+
+ def route(request):
+ parsed = urlsplit(request.full_url)
+ request.full_url = url(dl_server, parsed.path + (f"?{parsed.query}" if parsed.query else ""))
+ return request
+
+ real_open = urllib_security.open_credentialed_url
+ real_artifact_open = downloader._OPENER.open
+ monkeypatch.setattr(RangeHandler, "do_GET", record)
+ monkeypatch.setattr(urllib_security, "open_credentialed_url", lambda req, **kw: real_open(route(req), **kw))
+ monkeypatch.setattr(downloader._OPENER, "open", lambda req, **kw: real_artifact_open(route(req), **kw))
+ return calls, failures
+
+
[email protected]("name", ["npm", "node", "uv", "python", "llamacpp-cpu", "ffmpeg"])
+def test_resolution_reuses_successful_responses_but_refreshes_next_operation(upstream, monkeypatch, tmp_path, name):
+ calls, failures = upstream
+ package = get_package(name)
+ targets = [t for t in ALL_TARGETS if package.missing_reason(t) is None]
+ for generation in (1, 2):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / f"profile-{generation}"))
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / f"store-{generation}"))
+ monkeypatch.setenv("GH_TOKEN", f"github-{generation}")
+ monkeypatch.setenv("HF_TOKEN", f"huggingface-{generation}")
+ calls.clear()
+ payloads = {}
+ expected_targets = targets
+ version = f"2.0.{generation}"
+ locked = "1.0.0"
+ artifacts = None
+ if name == "npm":
+ payloads["/-/package/npm/dist-tags"] = {"latest": version}
+ elif name == "node":
+ payloads["/dist/index.json"] = [{"version": f"v{version}"}, {"version": "nightly"}]
+ elif name == "uv":
+ # Three populated pages exercise the real pagination loop.
+ for page in range(1, 4):
+ payloads[f"/repos/astral-sh/uv/releases?per_page=30&page={page}"] = [
+ {"tag_name": version}, *[{"tag_name": "9.0.0", "prerelease": True}] * 29,
+ ]
+ elif name == "python":
+ version = f"3.14.{generation}+20990102"
+ locked = "3.14.0+20990101"
+ # Only one architecture is advertised: sharing JSON must not share its candidates.
+ expected_targets = ["linux-x64"]
+ payloads["/repos/astral-sh/python-build-standalone/releases?per_page=30&page=1"] = [{
+ "tag_name": "20990102", "assets": [
+ {"name": f"cpython-{version}-x86_64-unknown-linux-gnu-install_only.tar.gz"},
+ {"name": "cpython-3.15.0+20990102-aarch64-apple-darwin-install_only.tar.gz"},
+ ],
+ }]
+ elif name == "llamacpp-cpu":
+ version = str(100 + generation)
+ locked = "100"
+ payloads["/buckets/ggml-org/install.sh/resolve/latest"] = f"b{version}\n"
+ payloads["/api/buckets/ggml-org/install.sh/tree?limit=1000&offset=0"] = []
+ else:
+ locked = version = "9.1.2"
+ artifacts = {}
+ expected_targets = [t for t in targets if t != "linux-arm64-bionic"]
+ payloads["/"] = "\n".join(
+ f'<a href="/download/{osname}/{arch}/{generation}_{version}/ffmpeg.zip">build</a>'
+ for osname in ("linux", "macos") for arch in ("amd64", "arm64")
+ )
+ payloads["/repos/BtbN/FFmpeg-Builds/releases?per_page=30&page=1"] = [{
+ "tag_name": f"autobuild-{generation}", "assets": [
+ {"name": f"ffmpeg-n{version}-1-gabcdef-win{arch}-gpl-9.1.zip"}
+ for arch in ("64", "arm64")
+ ],
+ }]
+ RangeHandler.payloads = {path: (value if isinstance(value, str) else json.dumps(value)).encode()
+ for path, value in payloads.items()}
+ # A failed transfer still retries; only the eventual success is reusable.
+ retry_path = next(iter(payloads))
+ failures[retry_path] = [503]
+ decision = update.resolve_package(package, targets, locked, artifacts=artifacts)
+ assert decision.version == version
+ assert decision.per_target == dict.fromkeys(expected_targets, version)
+ assert decision.changed
+ if name == "ffmpeg":
+ assert set(decision.artifact_updates) == set(expected_targets)
+ assert all(f"/{generation}_{version}/" in urls[0] or f"/autobuild-{generation}/" in urls[0]
+ for urls in decision.artifact_updates.values())
+ expected = Counter(dict.fromkeys(payloads, 1))
+ expected[retry_path] += 1
+ assert Counter(path for path, _ in calls) == expected
+ for path, auth in calls:
+ token = (f"github-{generation}" if path.startswith("/repos/") else
+ f"huggingface-{generation}" if "ggml-org/install.sh" in path else None)
+ assert auth == (f"Bearer {token}" if token else None)
+
+ # Recovery semantics differ: npm propagates, while llama's optional pointer
+ # falls back and must try again on the next target, not memoize its failure.
+ calls.clear()
+ failures[retry_path] = [404]
+ if name == "npm":
+ with pytest.raises(HTTPError, match="404"):
+ update.resolve_package(package, targets, locked)
+ assert len(calls) == 1
+ assert update.resolve_package(package, targets, locked).version == version
+ assert Counter(path for path, _ in calls) == {retry_path: 2}
+ elif name == "llamacpp-cpu":
+ fallback = "/repos/ggml-org/llama.cpp/releases?per_page=30&page=1"
+ RangeHandler.payloads[fallback] = json.dumps([{"tag_name": f"b{version}"}]).encode()
+ assert update.resolve_package(package, targets, locked).version == version
+ assert Counter(path for path, _ in calls) == {**expected, fallback: 1}
+ elif name == "uv":
+ failures.clear()
+ endpoint = "https://api.github.com" + retry_path
+ with update.reuse_index_responses():
+ for credential in ("first", "second"):
+ monkeypatch.setenv("GH_TOKEN", credential)
+ for _ in range(2):
+ assert update._get_json(endpoint) == payloads[retry_path]
+ assert calls == [(retry_path, "Bearer first"), (retry_path, "Bearer second")]
+ elif name == "ffmpeg":
+ # Manual re-pinning also needs a short-lived index scope after removing
+ # the old process-wide FFmpeg indexes. Pin real bytes into a real lock.
+ failures.clear()
+ monkeypatch.setattr(package, "gaps", {"linux-arm64-bionic": "separate supplier"})
+ body = b"advertised ffmpeg artifact"
+ for urls in decision.artifact_updates.values():
+ RangeHandler.payloads[urlsplit(urls[0]).path] = body
+ lock = Lockfile(tmp_path / "lock.json")
+ monkeypatch.setattr(cli, "_lockfile", lambda: lock)
+ assert cli.cmd_lock(Namespace(name=name, version=version)) == 0
+ pinned = Lockfile(lock.path)
+ assert pinned.version(name) == version
+ for target, urls in decision.artifact_updates.items():
+ assert pinned.artifacts(name, target) == [{"url": urls[0], "sha256": hashlib.sha256(body).hexdigest()}]
+ assert Counter(path for path, _ in calls) == dict.fromkeys(RangeHandler.payloads, 1)
+
+
+def test_pinning_hashes_new_npm_url_once_and_keeps_existing_rows(upstream, tmp_path, monkeypatch):
+ calls, failures = upstream
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "store"))
+ package = packages.Npm()
+ version = "2.0.0"
+ artifact_url = package.fetch_url(version, ALL_TARGETS[0])
+ artifact_path = urlsplit(artifact_url).path
+ filename, digest = make_tar(tmp_path, "npm.tgz", {"package/package.json": '{"version":"2.0.0"}'})
+ RangeHandler.payloads[artifact_path] = (tmp_path / filename).read_bytes()
+ old = {"url": package.fetch_url("1.0.0", ALL_TARGETS[0]), "sha256": "a" * 64}
+ current = {"any": old, "unresolved-target": old}
+ decision = update.Resolved("npm", "1.0.0", "semver", version,
+ per_target=dict.fromkeys(ALL_TARGETS, version))
+ pinned = cli._pin_artifacts(package, decision, current)
+ assert current == {"any": old, "unresolved-target": old}
+ assert pinned == {**current, **dict.fromkeys(ALL_TARGETS, {"url": artifact_url, "sha256": digest})}
+ assert Counter(path for path, _ in calls) == {artifact_path: 1}
+
+ # Existing pins need no download; a separate pin invocation must not retain new hashes.
+ calls.clear()
+ assert cli._pin_artifacts(package, decision, pinned) == pinned
+ assert not calls
+ replacement = b"changed upstream bytes"
+ RangeHandler.payloads[artifact_path] = replacement
+ failures[artifact_path] = [404]
+ with pytest.raises(HTTPError, match="404"):
+ cli._pin_artifacts(package, decision, current)
+ assert current == {"any": old, "unresolved-target": old}
+ calls.clear()
+ repinned = cli._pin_artifacts(package, decision, current)
+ assert repinned[ALL_TARGETS[-1]]["sha256"] == hashlib.sha256(replacement).hexdigest()
+ assert Counter(path for path, _ in calls) == {artifact_path: 1}