Skip to content

The agent that grows with you

fix(termux): pin upstream psutil Android support

ethernet6590ecdc2d61
diff --git a/.github/workflows/termux-verify.yml b/.github/workflows/termux-verify.yml
index 8d2966cbc57..ea1cee5298f 100644
--- a/.github/workflows/termux-verify.yml
+++ b/.github/workflows/termux-verify.yml
@@ -54,6 +54,7 @@ jobs:
run: |
bash scripts/run_tests.sh -j 2 \
tests/test_termux_python_linkage.py tests/test_termux_retag_wheel.py \
+ tests/test_termux_build_wheels.py \
tests/test_termux_wheelhouse_cache.py tests/test_termux_runtime_libs.py \
tests/test_termux_launchers.py tests/test_pm_bionic.py \
tests/pm/test_stage_only.py tests/pm/test_deb_safety.py tests/test_stage_apt_repo.py \
diff --git a/pyproject.toml b/pyproject.toml
index 97895a361b5..ccf3a9072c0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -123,7 +123,11 @@ dependencies = [
# macOS and Windows. It replaces POSIX-only idioms like `os.kill(pid, 0)`
# (which is a silent killer on Windows — see CONTRIBUTING.md) and
# `os.killpg` (which doesn't exist on Windows).
- "psutil==7.2.2",
+ "psutil==7.2.2; sys_platform != 'android'",
+ # Android Python 3.13+ needs upstream #2891 for platform recognition and
+ # disk_partitions(). The fix is not in a published psutil release yet.
+ # Keep this commit until a release includes it, then remove the source pin.
+ "psutil @ git+https://github.com/giampaolo/psutil.git@380bd2b59c67b0e1b04bbf3a90b11744f4f96644 ; sys_platform == 'android'",
# Browser CDP supervisor + browser_dialog import this directly. Keep core
# so browser tool discovery doesn't fail on lean installs.
"websockets==15.0.1",
diff --git a/scripts/termux/build_config.sh b/scripts/termux/build_config.sh
index ca6c888e96b..6be98e98c23 100644
--- a/scripts/termux/build_config.sh
+++ b/scripts/termux/build_config.sh
@@ -16,7 +16,7 @@ PLATFORM_TAG="android_24_arm64_v8a"
# because index.json's pythonAbi field must agree with it.
PYTHON_ABI="cp314"
-# Toolchain pins for the psutil patched-local build path (--no-build-
+# Toolchain pins for the uvloop configured-source build path (--no-build-
# isolation). Pure-python installs only: maturin is deliberately absent --
# it is a native wheel that uv (rightly) refuses to install onto bionic,
# and the rust-backend sdists (pydantic-core, jiter, ...) build through
diff --git a/scripts/termux/build_wheels.py b/scripts/termux/build_wheels.py
index 86a13880775..e2b5fbe5ca0 100644
--- a/scripts/termux/build_wheels.py
+++ b/scripts/termux/build_wheels.py
@@ -17,13 +17,16 @@ from __future__ import annotations
import argparse
import os
+import re
+import shutil
import subprocess
import sys
import sysconfig
import tarfile
import tempfile
-import shutil
+import tomllib
from pathlib import Path, PurePosixPath
+from urllib.parse import urlsplit
def parse_args() -> argparse.Namespace:
@@ -37,22 +40,43 @@ def parse_args() -> argparse.Namespace:
return p.parse_args()
-def parse_reqs(resolved: Path) -> list[tuple[str, str]]:
- """(name, spec) pairs for every non-empty resolved line."""
- out: list[tuple[str, str]] = []
- for line in resolved.read_text(encoding="utf-8").splitlines():
- if not line.strip():
+def normalize_reqs(export: Path, lock: Path, resolved: Path) -> None:
+ """Retain both the build source and the locked offline wheel version."""
+ from packaging.requirements import Requirement
+ from packaging.utils import canonicalize_name
+
+ packages = tomllib.loads(lock.read_text(encoding="utf-8"))["package"]
+ rows = []
+ for line in export.read_text(encoding="utf-8").splitlines():
+ if not line.strip() or line.lstrip().startswith("#"):
continue
- parts = line.split("\t")
- out.append((parts[0], parts[1] if len(parts) > 1 else ""))
- return out
+ req = Requirement(line)
+ name = canonicalize_name(req.name)
+ spec = str(req.specifier)
+ source = req.url or ""
+ if source:
+ repository, separator, commit = source.removeprefix("git+").rpartition("@")
+ if not source.startswith("git+") or not separator or not re.fullmatch(r"[a-f0-9]{40}", commit):
+ raise ValueError(f"Source requirement needs an exact Git commit: {name}")
+ matches = [p for p in packages if canonicalize_name(p["name"]) == name
+ and (git := p.get("source", {}).get("git"))
+ and urlsplit(git).fragment == commit
+ and git.split("?", 1)[0].split("#", 1)[0] == repository]
+ if len(matches) != 1:
+ raise ValueError(f"Source requirement does not match one locked package: {name}")
+ spec = f"=={matches[0]['version']}"
+ rows.append((name, spec, str(req.marker) if req.marker else "", source))
+ resolved.write_text("".join("\t".join(row) + "\n" for row in rows), encoding="utf-8")
def load_entries(resolved: Path) -> dict[str, str]:
- """name -> version spec ('==x.y.z') for the build loop's locked pins."""
+ """Select build requirements using the payload's platform markers."""
entries: dict[str, str] = {}
- for name, spec in parse_reqs(resolved):
- entries[name] = spec.strip()
+ for name, spec, marker, source in _parse_full(resolved):
+ if _marker_admits(marker):
+ if name in entries:
+ raise ValueError(f"Duplicate applicable requirement: {name}")
+ entries[name] = f" @ {source}" if source else spec.strip()
return entries
@@ -63,7 +87,7 @@ def write_reqs_file(resolved: Path, reqs: Path) -> None:
are skipped (no offline solution exists for them, by design).
"""
out = []
- for name, spec, marker in _parse_full(resolved):
+ for name, spec, marker, source in _parse_full(resolved):
if name in BUILD_MISSES:
continue
line = f"{name}{spec.strip()}" if spec.strip() else name
@@ -102,27 +126,14 @@ def safe_extract(archive: Path, dest: Path) -> Path:
return roots[0] if roots else dest
-PSUTIL_MARKER = 'LINUX = sys.platform.startswith("linux")'
-PSUTIL_PATCH = 'LINUX = sys.platform.startswith(("linux", "android"))'
-
-
-def patch_psutil(src_root: Path) -> None:
- common = src_root / "psutil" / "_common.py"
- if not common.is_file():
- return # not a psutil sdist; nothing to patch
- content = common.read_text(encoding="utf-8-sig")
- if PSUTIL_MARKER not in content:
- raise RuntimeError("psutil android patch marker not found -- update the patch for the pinned psutil pin")
- common.write_text(content.replace(PSUTIL_MARKER, PSUTIL_PATCH), encoding="utf-8")
-
-
def _dist_version(name: str, spec: str) -> str | None:
# Exact pins carry the version ("==X.Y.Z"); anything else cannot be
# skip-checked safely, so it always builds.
return spec.strip().lstrip("=") if spec.strip().startswith("==") else None
-def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path) -> None:
+def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path,
+ *, python: str = sys.executable) -> None:
for name in build_set:
spec = specs.get(name, "")
req = f"{name}{spec}" if spec else name
@@ -132,14 +143,14 @@ def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path)
):
print(f"==> {name} {ver} already in the wheelhouse (cache restore); skipping")
continue
- if name in ("psutil", "uvloop"):
+ if name == "uvloop":
print(f"==> building {name} (download + extract + pre-build fixups)")
with tempfile.TemporaryDirectory(prefix=f"hermes-build-{name}-") as tmp:
tmp = Path(tmp)
sdist_dir = tmp / "sdist"
sdist_dir.mkdir()
subprocess.run(
- [sys.executable, "-m", "pip", "download", "--no-deps", "--no-binary", ":all:",
+ [python, "-m", "pip", "download", "--no-deps", "--no-binary", ":all:",
"--no-build-isolation", "-d", str(sdist_dir), req],
check=True, cwd=tmp,
)
@@ -147,48 +158,46 @@ def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path)
if len(archives) != 1:
raise RuntimeError(f"expected exactly one sdist archive for {name}, got {len(archives)}")
src = safe_extract(archives[0], tmp / "src")
- patch_psutil(src)
- if name == "uvloop":
- # uvloop vendors libuv at vendor/libuv/ WITH its own
- # autogen.sh + generated configure; the build backend
- # expects libuv CONFIGURED (build artifacts present)
- # before setup.py runs it. We run configure ourselves:
- # setup.py's own ['./configure'] invocation 127s on the
- # rewritten shebang (subprocess execv semantics), but a
- # completed configure leaves artifacts setup.py reuses.
- libuv = src / "vendor" / "libuv"
- if libuv.is_dir():
- # bash-invoked: the sdist's autogen.sh may carry a
- # non-exec mode (extraction preserves it). autogen
- # also (re)writes ./configure WITHOUT the exec bit
- # (setup.py then 127s) -- chmod after bootstrap.
- proc = subprocess.run(["bash", "autogen.sh"], cwd=libuv,
- check=False, capture_output=True, text=True)
- if proc.returncode == 0 and (libuv / "configure").is_file():
- # Run configure under the container's own sh
- # (its #!/bin/sh shebang can't exec here).
- cfg_proc = subprocess.run(
- [os.environ["PREFIX"] + "/bin/sh", "./configure"],
- cwd=libuv, check=False, capture_output=True, text=True,
- )
- if cfg_proc.returncode != 0:
- print(f"FIXUP FAILED (libuv configure) for {name}")
- print("stdout:", cfg_proc.stdout[-1500:])
- print("stderr:", cfg_proc.stderr[-1500:])
- raise subprocess.CalledProcessError(cfg_proc.returncode, cfg_proc.args)
- if proc.returncode != 0:
- # autogen needs autoreconf when configure is
- # stale; fall back to explicit bootstrap
- proc2 = subprocess.run(["autoreconf", "-i"], cwd=libuv,
- check=False, capture_output=True, text=True)
- if proc2.returncode != 0:
- print(f"FIXUP FAILED (libuv bootstrap) for {name}")
- print("autogen stdout:", proc.stdout[-1200:])
- print("autogen stderr:", proc.stderr[-1200:])
- print("autoreconf stderr:", proc2.stderr[-1200:])
- raise subprocess.CalledProcessError(proc2.returncode, proc2.args)
+ # uvloop vendors libuv at vendor/libuv/ WITH its own
+ # autogen.sh + generated configure; the build backend
+ # expects libuv CONFIGURED (build artifacts present)
+ # before setup.py runs it. We run configure ourselves:
+ # setup.py's own ['./configure'] invocation 127s on the
+ # rewritten shebang (subprocess execv semantics), but a
+ # completed configure leaves artifacts setup.py reuses.
+ libuv = src / "vendor" / "libuv"
+ if libuv.is_dir():
+ # bash-invoked: the sdist's autogen.sh may carry a
+ # non-exec mode (extraction preserves it). autogen
+ # also (re)writes ./configure WITHOUT the exec bit
+ # (setup.py then 127s) -- chmod after bootstrap.
+ proc = subprocess.run(["bash", "autogen.sh"], cwd=libuv,
+ check=False, capture_output=True, text=True)
+ if proc.returncode == 0 and (libuv / "configure").is_file():
+ # Run configure under the container's own sh
+ # (its #!/bin/sh shebang can't exec here).
+ cfg_proc = subprocess.run(
+ [os.environ["PREFIX"] + "/bin/sh", "./configure"],
+ cwd=libuv, check=False, capture_output=True, text=True,
+ )
+ if cfg_proc.returncode != 0:
+ print(f"FIXUP FAILED (libuv configure) for {name}")
+ print("stdout:", cfg_proc.stdout[-1500:])
+ print("stderr:", cfg_proc.stderr[-1500:])
+ raise subprocess.CalledProcessError(cfg_proc.returncode, cfg_proc.args)
+ if proc.returncode != 0:
+ # autogen needs autoreconf when configure is
+ # stale; fall back to explicit bootstrap
+ proc2 = subprocess.run(["autoreconf", "-i"], cwd=libuv,
+ check=False, capture_output=True, text=True)
+ if proc2.returncode != 0:
+ print(f"FIXUP FAILED (libuv bootstrap) for {name}")
+ print("autogen stdout:", proc.stdout[-1200:])
+ print("autogen stderr:", proc.stderr[-1200:])
+ print("autoreconf stderr:", proc2.stderr[-1200:])
+ raise subprocess.CalledProcessError(proc2.returncode, proc2.args)
proc = subprocess.run(
- [sys.executable, "-m", "pip", "wheel", "--no-deps", "--no-build-isolation",
+ [python, "-m", "pip", "wheel", "--no-deps", "--no-build-isolation",
"-w", str(wheelhouse), str(src)],
check=False, cwd=tmp, capture_output=True, text=True,
)
@@ -205,7 +214,7 @@ def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path)
# never resolves/compiles -- the build container may fetch.
print(f"==> building {name} (direct pip wheel, isolated backend)")
proc = subprocess.run(
- [sys.executable, "-m", "pip", "wheel", "--no-deps",
+ [python, "-m", "pip", "wheel", "--no-deps",
"--no-binary", ":all:", "-w", str(wheelhouse), req],
check=False, capture_output=True, text=True,
)
@@ -241,21 +250,19 @@ def _marker_admits(marker: str) -> bool:
if not marker:
return True
from packaging.markers import Marker
- try:
- return Marker(marker).evaluate(TARGET_ENV)
- except Exception:
- return True
+ return Marker(marker).evaluate(TARGET_ENV)
-def _parse_full(resolved: Path) -> list[tuple[str, str, str]]:
- """(name, spec, marker) triples from the tab-separated resolved file."""
- out: list[tuple[str, str, str]] = []
+def _parse_full(resolved: Path) -> list[tuple[str, str, str, str]]:
+ """Name, wheel version, marker and optional build source for each entry."""
+ out: list[tuple[str, str, str, str]] = []
for line in resolved.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
parts = line.split("\t")
- out.append((parts[0], parts[1] if len(parts) > 1 else "",
- parts[2] if len(parts) > 2 else ""))
+ if len(parts) != 4:
+ raise ValueError("Expected name, version, marker and source fields")
+ out.append((parts[0], parts[1], parts[2], parts[3]))
return out
@@ -274,7 +281,7 @@ def fetch_pure_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: P
The gate reqs keep all lines; pip/uv on bionic skips the win32 ones.
"""
reqs = []
- for name, spec, marker in _parse_full(resolved):
+ for name, spec, marker, source in _parse_full(resolved):
if name in build_set or name in BUILD_MISSES:
continue
if not _marker_admits(marker):
@@ -374,6 +381,9 @@ def wheelhouse_gates(resolved: Path, wheelhouse: Path, build_set: list[str], uv:
def main() -> int:
+ if sys.argv[1:2] == ["--normalize"]:
+ normalize_reqs(*(Path(value) for value in sys.argv[2:]))
+ return 0
if sys.argv[1:2] == ["--import-modules"]:
import_native_modules(sys.argv[2:])
return 0
diff --git a/scripts/termux/termux-builder.Dockerfile b/scripts/termux/termux-builder.Dockerfile
index cf11e590ff8..265d311f8ae 100644
--- a/scripts/termux/termux-builder.Dockerfile
+++ b/scripts/termux/termux-builder.Dockerfile
@@ -28,7 +28,7 @@ RUN printf '%s\n' "deb https://packages.termux.dev/apt/termux-main stable main"
&& rm -f "${PREFIX}/etc/apt/sources.list.d/"*.list \
&& (apt update || apt update) \
&& apt install -y \
- clang rust make patchelf binutils pkg-config protobuf cmake ninja \
+ clang rust make git patchelf binutils pkg-config protobuf cmake ninja \
autoconf automake libtool \
libandroid-posix-semaphore libandroid-support libbz2 libffi \
libjpeg-turbo libpng freetype libtiff libwebp openjpeg littlecms \
diff --git a/scripts/termux/termux_build.sh b/scripts/termux/termux_build.sh
index 58fa2a78fa1..ab4ed69a927 100755
--- a/scripts/termux/termux_build.sh
+++ b/scripts/termux/termux_build.sh
@@ -58,7 +58,7 @@ if [ "${1:-}" = "--in-container" ]; then
fi
# BUILD tools come from termux's own apt (the image is a bare
# bootstrap). The USER machine never does any of this.
- if ! command -v clang >/dev/null 2>&1; then
+ if ! command -v clang >/dev/null 2>&1 || ! command -v git >/dev/null 2>&1; then
log "Provisioning the container build toolchain (termux apt)"
export DEBIAN_FRONTEND=noninteractive
# Pin the OFFICIAL mirror and use apt DIRECTLY: pkg (the wrapper)
@@ -70,7 +70,7 @@ if [ "${1:-}" = "--in-container" ]; then
rm -f "$PREFIX/etc/apt/sources.list.d"/*.list 2>/dev/null || true
apt update || apt update \
|| fail "apt update failed in the container"
- apt install -y clang rust make patchelf binutils pkg-config protobuf cmake ninja autoconf automake libtool \
+ apt install -y clang rust make git patchelf binutils pkg-config protobuf cmake ninja autoconf automake libtool \
libandroid-posix-semaphore libandroid-support libbz2 libffi \
libjpeg-turbo libpng freetype libtiff libwebp openjpeg littlecms \
libyaml openssl readline zlib liblzma libsqlite ncurses \
@@ -78,7 +78,7 @@ if [ "${1:-}" = "--in-container" ]; then
fi
# BINARIES, not package names: the rust package provides rustc/cargo
# (there is no `rust` binary).
- for tool in clang rustc cargo make; do
+ for tool in clang rustc cargo make git; do
command -v "$tool" >/dev/null 2>&1 \
|| fail "container lacks $tool after provisioning"
done
@@ -218,43 +218,29 @@ mkdir -p "$WHEELHOUSE"
rm -f "$OUT_ABS/index.json" "$OUT_ABS/SHA256SUMS" "$WORK/resolved.txt" "$WORK/build_set.txt"
# [d] Resolve the real graph from the tag's own lock.
log "Resolving dependency graph from the tag's uv.lock"
-( cd "$WORK/tree" && uv export --frozen --no-emit-project --extra acp -o "$WORK/req.txt" ) \
+( cd "$WORK/tree" && uv export --frozen --no-emit-project --extra acp \
+ --no-hashes --no-annotate --no-header -o "$WORK/req.txt" ) \
|| fail "uv export failed (frozen lock at $TAG)"
+# Host parsing needs packaging too. Use the release lock, not runner packages.
+PACKAGING_SPEC="$(python3 - "$WORK/tree/uv.lock" <<'PY'
+import sys, tomllib
+with open(sys.argv[1], "rb") as stream:
+ packages = tomllib.load(stream)["package"]
+package, = [item for item in packages if item["name"] == "packaging"]
+print("packaging==" + package["version"])
+PY
+)" || fail "locked packaging dependency missing"
+HOST_PY=(uv run --isolated --no-project --python "$(command -v python3)" --with "$PACKAGING_SPEC" python)
RESOLVED="$WORK/resolved.txt"
-python3 - "$WORK/req.txt" "$RESOLVED" <<'PYEOF' || fail "failed to normalize requirements"
-import re, sys
-out = []
-for line in open(sys.argv[1], encoding="utf-8"):
- line = line.strip()
- # uv export wraps long lines with backslash continuations; strip the
- # trailing continuation BEFORE capturing markers/specs -- a backslash
- # riding into a marker makes Marker() throw (and a throwing marker
- # must not silently admit the package into the build set).
- line = re.sub(r"\\\s*$", "", line)
- if not line or line.startswith("#"):
- continue
- marker = ""
- m = re.search(r"\s;\s*(.+)$", line)
- if m:
- marker = m.group(1).strip()
- line = line[: m.start()]
- line = re.sub(r"\s*--.*$", "", line)
- if line.startswith("--") or not line:
- continue
- m = re.match(r"^([A-Za-z0-9._-]+)(\[[^]]*\])?([=<>~!^].*)?$", line)
- if m:
- out.append((m.group(1), m.group(3) or "", marker))
-open(sys.argv[2], "w", encoding="utf-8").write(
- "\n".join(f"{name}\t{spec}\t{marker}" for name, spec, marker in out) + "\n"
-)
-PYEOF
+"${HOST_PY[@]}" "$HERE/build_wheels.py" --normalize "$WORK/req.txt" "$WORK/tree/uv.lock" "$RESOLVED" \
+ || fail "failed to normalize requirements"
[ -s "$RESOLVED" ] || fail "resolved dependency list is empty"
# [e] Marker-aware PyPI wheel-coverage probe: build set = resolved deps
# whose marker admits android AND that have no installable none-any wheel.
log "Probing PyPI wheel coverage (android markers)"
BUILD_SET="$WORK/build_set.txt"
-python3 - "$RESOLVED" "$BUILD_SET" <<'PYEOF' || fail "PyPI wheel-coverage probe failed"
+"${HOST_PY[@]}" - "$RESOLVED" "$BUILD_SET" <<'PYEOF' || fail "PyPI wheel-coverage probe failed"
import json, re, sys, urllib.request
from concurrent.futures import ThreadPoolExecutor
@@ -296,13 +282,15 @@ entries = []
for line in open(sys.argv[1], encoding="utf-8"):
if not line.strip():
continue
- name, spec, marker = (line.split("\t", 2) + ["", ""])[:3]
- entries.append((name, spec, marker))
+ name, spec, marker, source = (line.rstrip("\n").split("\t") + [""])[:4]
+ entries.append((name, spec, marker, source))
def probe(item):
- name, spec, marker = item
+ name, spec, marker, source = item
if not marker_admits(marker):
return name, None, None
+ if source:
+ return name, False, None
try:
with urllib.request.urlopen(f"https://pypi.org/pypi/{name}/json", timeout=30) as r:
d = json.load(r)
diff --git a/tests/test_termux_build_wheels.py b/tests/test_termux_build_wheels.py
new file mode 100644
index 00000000000..b9636e43d3d
--- /dev/null
+++ b/tests/test_termux_build_wheels.py
@@ -0,0 +1,86 @@
+"""Pinned source dependencies build online and install from wheelhouse offline."""
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import venv
+from pathlib import Path
+
+import pytest
+
+from scripts.termux import build_wheels as builder
+
+
+def test_source_pin_survives_resolution_build_and_offline_install(tmp_path):
+ repo = tmp_path / "source"
+ repo.mkdir()
+ (repo / "pyproject.toml").write_text(
+ '[build-system]\nrequires = ["setuptools>=75.3.4"]\n'
+ 'build-backend = "setuptools.build_meta"\n'
+ '[project]\nname = "hermes-source-fixture"\nversion = "8.0.0"\n', encoding="utf-8")
+ (repo / "source_fixture.py").write_text('VALUE = "from pinned source"\n', encoding="utf-8")
+ subprocess.run(["git", "init", str(repo)], check=True, capture_output=True)
+ subprocess.run(["git", "-C", str(repo), "add", "."], check=True)
+ subprocess.run(["git", "-C", str(repo), "-c", "user.name=Fixture", "-c",
+ "[email protected]", "commit", "-m", "fixture"],
+ check=True, capture_output=True)
+ commit = subprocess.check_output(["git", "-C", str(repo), "rev-parse", "HEAD"], text=True).strip()
+ (repo / "source_fixture.py").write_text('VALUE = "wrong moving head"\n', encoding="utf-8")
+ subprocess.run(["git", "-C", str(repo), "-c", "user.name=Fixture", "-c",
+ "[email protected]", "commit", "-am", "advance head"],
+ check=True, capture_output=True)
+ url = repo.as_uri()
+ source = f"git+{url}@{commit}"
+ lock = tmp_path / "uv.lock"
+ lock.write_text(
+ '[[package]]\nname = "hermes-source-fixture"\nversion = "8.0.0"\n'
+ f'source = {{ git = "{url}?rev={commit}#{commit}" }}\n', encoding="utf-8")
+ export = tmp_path / "requirements.txt"
+ export.write_text(
+ 'hermes-source-fixture==7.2.2 ; python_version < "3.11"\n'
+ f'hermes-source-fixture @ {source} ; python_version >= "3.11"\n', encoding="utf-8")
+ resolved = tmp_path / "resolved.txt"
+ builder.normalize_reqs(export, lock, resolved)
+ specs = builder.load_entries(resolved)
+ assert specs == {"hermes-source-fixture": f" @ {source}"}
+ reqs = tmp_path / "offline.txt"
+ builder.write_reqs_file(resolved, reqs)
+ assert "@" not in reqs.read_text(encoding="utf-8")
+ assert 'hermes-source-fixture==8.0.0 ; python_version >= "3.11"' in reqs.read_text(encoding="utf-8")
+
+ wheels = tmp_path / "wheels"
+ wheels.mkdir()
+ build_env = tmp_path / "build-env"
+ venv.EnvBuilder(with_pip=True).create(build_env)
+ python = build_env / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ subprocess.run([str(python), "-m", "pip", "install", "pip==26.2.1"],
+ check=True, capture_output=True)
+ builder.build_wheels(list(specs), specs, wheels, python=str(python))
+ assert len(list(wheels.glob("hermes_source_fixture-8.0.0-*.whl"))) == 1
+ # Remove the original source URL to rule out a Git fallback.
+ repo.rename(tmp_path / "unavailable-source")
+ target = tmp_path / "installed"
+ subprocess.run([str(python), "-m", "pip", "install", "--no-index", "--no-deps",
+ "--find-links", str(wheels), "--target", str(target), "-r", str(reqs)],
+ check=True, capture_output=True)
+ result = subprocess.check_output(
+ [sys.executable, "-c", "import source_fixture; print(source_fixture.VALUE)"],
+ cwd=tmp_path, env={**os.environ, "PYTHONPATH": str(target)}, text=True)
+ assert result.strip() == "from pinned source"
+
+
+def test_source_pin_rejects_moved_revision_and_missing_locked_metadata(tmp_path):
+ commit = "a" * 40
+ source = "https://example.invalid/package.git"
+ export, lock, resolved = (tmp_path / name for name in ("requirements.txt", "uv.lock", "resolved.txt"))
+ lock.write_text('[[package]]\nname = "example"\nversion = "8.0.0"\n'
+ f'source = {{ git = "{source}?rev={commit}#{commit}" }}\n', encoding="utf-8")
+ for revision in ("main", "b" * 40):
+ export.write_text(f"example @ git+{source}@{revision}\n", encoding="utf-8")
+ with pytest.raises(ValueError, match="commit|lock"):
+ builder.normalize_reqs(export, lock, resolved)
+ export.write_text(f"example @ git+{source}@{commit}\n", encoding="utf-8")
+ lock.write_text("package = []\n", encoding="utf-8")
+ with pytest.raises(ValueError, match="lock"):
+ builder.normalize_reqs(export, lock, resolved)
diff --git a/uv.lock b/uv.lock
index b4204ae37ba..b03d98e4be2 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1,6 +1,10 @@
version = 1
revision = 3
requires-python = "==3.14.*"
+resolution-markers = [
+ "sys_platform != 'android'",
+ "sys_platform == 'android'",
+]
[options]
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
@@ -1571,7 +1575,8 @@ dependencies = [
{ name = "pathspec" },
{ name = "pillow" },
{ name = "prompt-toolkit" },
- { name = "psutil" },
+ { name = "psutil", version = "7.2.2", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'android'" },
+ { name = "psutil", version = "8.0.0", source = { git = "https://github.com/giampaolo/psutil.git?rev=380bd2b59c67b0e1b04bbf3a90b11744f4f96644#380bd2b59c67b0e1b04bbf3a90b11744f4f96644" }, marker = "sys_platform == 'android'" },
{ name = "ptyprocess", marker = "sys_platform != 'win32'" },
{ name = "pydantic" },
{ name = "pyjwt", extra = ["crypto"] },
@@ -1930,7 +1935,8 @@ requires-dist = [
{ name = "pilk", marker = "extra == 'silk'", specifier = "==0.2.4" },
{ name = "pillow", specifier = "==12.3.0" },
{ name = "prompt-toolkit", specifier = "==3.0.52" },
- { name = "psutil", specifier = "==7.2.2" },
+ { name = "psutil", marker = "sys_platform != 'android'", specifier = "==7.2.2" },
+ { name = "psutil", marker = "sys_platform == 'android'", git = "https://github.com/giampaolo/psutil.git?rev=380bd2b59c67b0e1b04bbf3a90b11744f4f96644" },
{ name = "ptyprocess", marker = "sys_platform != 'win32'", specifier = ">=0.7.0,<1" },
{ name = "pvporcupine", marker = "extra == 'wake'", specifier = "==4.0.3" },
{ name = "pvporcupine", marker = "extra == 'wake-porcupine'", specifier = "==4.0.3" },
@@ -3120,6 +3126,9 @@ wheels = [
name = "psutil"
version = "7.2.2"
source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "sys_platform != 'android'",
+]
sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" },
@@ -3138,6 +3147,14 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" },
]
+[[package]]
+name = "psutil"
+version = "8.0.0"
+source = { git = "https://github.com/giampaolo/psutil.git?rev=380bd2b59c67b0e1b04bbf3a90b11744f4f96644#380bd2b59c67b0e1b04bbf3a90b11744f4f96644" }
+resolution-markers = [
+ "sys_platform == 'android'",
+]
+
[[package]]
name = "ptyprocess"
version = "0.7.0"