The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(lazy_deps): bridge pip.conf index-url into the uv tier and make uv timeouts actionable (#95608)
liuhao10241ec887f795d5
diff --git a/tests/tools/test_lazy_deps.py b/tests/tools/test_lazy_deps.pyindex c62324be6bb..2141e7b40db 100644--- a/tests/tools/test_lazy_deps.py+++ b/tests/tools/test_lazy_deps.py@@ -600,3 +600,75 @@ class TestInstallWarmsBytecode:cmd = uv_cmds[0]assert "--compile-bytecode" in cmdassert cmd.index("--compile-bytecode") < cmd.index("zzzfake==1.0")+++# ---------------------------------------------------------------------------+# pip.conf index-url bridge for the uv tier (#95608)+# ---------------------------------------------------------------------------++class _FakeCompleted:+ returncode = 0+ stdout = ""+ stderr = ""+++class TestPipConfIndexBridge:+ def _record_uv_env(self, monkeypatch):+ """Run _venv_pip_install with a fake uv and capture the env it got."""+ captured = {}++ def fake_run(cmd, *args, **kwargs):+ captured["cmd"] = cmd+ captured["env"] = kwargs.get("env")+ return _FakeCompleted()++ monkeypatch.setattr(ld.subprocess, "run", fake_run)+ monkeypatch.setattr(ld, "resolve_uv", lambda: "/fake/uv", raising=False)+ return captured++ def test_pip_conf_index_url_bridged_into_uv_env(self, monkeypatch, tmp_path):+ conf = tmp_path / "pip.conf"+ conf.write_text(+ "[global]\nindex-url = https://mirror.example/simple\n",+ encoding="utf-8",+ )+ monkeypatch.setenv("PIP_CONFIG_FILE", str(conf))+ monkeypatch.delenv("UV_INDEX_URL", raising=False)+ captured = self._record_uv_env(monkeypatch)+ result = ld._venv_pip_install(("somepkg==1.0",))+ assert result.success+ assert captured["env"]["UV_INDEX_URL"] == "https://mirror.example/simple"++ def test_explicit_uv_index_url_wins_over_pip_conf(self, monkeypatch, tmp_path):+ conf = tmp_path / "pip.conf"+ conf.write_text(+ "[global]\nindex-url = https://mirror.example/simple\n",+ encoding="utf-8",+ )+ monkeypatch.setenv("PIP_CONFIG_FILE", str(conf))+ monkeypatch.setenv("UV_INDEX_URL", "https://custom.example/simple")+ captured = self._record_uv_env(monkeypatch)+ ld._venv_pip_install(("somepkg==1.0",))+ assert captured["env"]["UV_INDEX_URL"] == "https://custom.example/simple"++ def test_no_pip_conf_leaves_uv_env_unchanged(self, monkeypatch, tmp_path):+ monkeypatch.setenv("PIP_CONFIG_FILE", str(tmp_path / "missing.conf"))+ monkeypatch.delenv("UV_INDEX_URL", raising=False)+ captured = self._record_uv_env(monkeypatch)+ ld._venv_pip_install(("somepkg==1.0",))+ assert "UV_INDEX_URL" not in captured["env"]++ def test_uv_timeout_error_carries_actionable_hint(self, monkeypatch, tmp_path):+ monkeypatch.setenv("PIP_CONFIG_FILE", str(tmp_path / "missing.conf"))+ monkeypatch.delenv("UV_INDEX_URL", raising=False)++ def fake_run(cmd, *args, **kwargs):+ raise ld.subprocess.TimeoutExpired(cmd, timeout=kwargs.get("timeout", 300))++ monkeypatch.setattr(ld.subprocess, "run", fake_run)+ monkeypatch.setattr(ld, "resolve_uv", lambda: "/fake/uv", raising=False)+ result = ld._venv_pip_install(("somepkg==1.0",), timeout=5)+ assert result.success is False+ assert "timed out after 5s" in result.stderr+ assert "-m pip install somepkg==1.0" in result.stderr+ assert "mirror" in result.stderrdiff --git a/tools/lazy_deps.py b/tools/lazy_deps.pyindex f1b847a66c2..f7431fc0eef 100644--- a/tools/lazy_deps.py+++ b/tools/lazy_deps.py@@ -422,6 +422,43 @@ def _core_constraints_file() -> Optional[Path]:return None+def _pip_config_candidates(env: dict[str, str]) -> list[Path]:+ """Return pip config files in the same precedence order pip documents.++ Mirrors the twin helper in ``hermes_cli.main`` (#17761); kept local+ because this module deliberately has no CLI dependency.+ """+ explicit = env.get("PIP_CONFIG_FILE")+ if explicit:+ return [Path(explicit)]+ return [+ Path("/etc/pip.conf"),+ Path.home() / ".config" / "pip" / "pip.conf",+ Path.home() / ".pip" / "pip.conf",+ ]+++def _pip_conf_index_url(env: dict[str, str]) -> Optional[str]:+ """Read pip's configured index-url so uv can use the same mirror.++ uv does not read ``pip.conf`` — without this bridge a user whose pip is+ mirrored (common behind restricted networks) watches every lazy install+ hit the default pypi.org and time out (#95608).+ """+ try:+ import configparser++ parser = configparser.ConfigParser()+ found = parser.read(str(p) for p in _pip_config_candidates(env))+ if not found or not parser.has_section("global"):+ return None+ value = parser.get("global", "index-url", fallback="").strip()+ return value or None+ except Exception as e: # noqa: BLE001 — config reading is best-effort+ logger.debug("Could not read pip.conf for index-url: %s", e)+ return None++def _installed_dist_roots(spec: str, target: Optional[Path]) -> set[Path]:"""Package dirs a freshly installed *spec* owns, from the dist's file list (``python-telegram-bot``ships ``telegram``; some ship several)."""@@ -539,6 +576,14 @@ def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300, constraint_from tools.environments.local import hermes_subprocess_envuv_env = hermes_subprocess_env(inherit_credentials=False)uv_env["VIRTUAL_ENV"] = str(Path(sys.executable).parent.parent)+ # uv never reads pip.conf, so a mirrored-pip user would see every+ # lazy install stall against the default pypi.org for the full+ # timeout (#95608). Bridge pip's index-url unless uv is configured+ # explicitly — same policy as the update path (#17761).+ if not uv_env.get("UV_INDEX_URL"):+ pip_index_url = _pip_conf_index_url(uv_env)+ if pip_index_url:+ uv_env["UV_INDEX_URL"] = pip_index_url# Tier 1: uv. --compile-bytecode because uv writes no __pycache__ by default, so the first# import would recompile the backend AND its transitives (_warm_installed_bytecode is the# belt-and-braces pass for the spec's own roots on any tier).@@ -552,7 +597,17 @@ def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300, constraint_return _finish(r)except subprocess.TimeoutExpired as e:logger.debug("uv invocation failed: %s", e)- return _InstallResult(False, "", f"uv pip install timed out: {e}")+ # Actionable context for the #95608 shape: a 300s stall with+ # no feedback, then silence. The failure string flows into+ # FeatureUnavailable, which callers surface as warnings.+ hint = (+ f"uv pip install timed out after {timeout}s: {e}. "+ "If your network needs a package mirror, set index-url in "+ "pip.conf (bridged to uv automatically) or UV_INDEX_URL "+ f"directly; or install manually with: "+ f"{sys.executable} -m pip install {' '.join(specs)}"+ )+ return _InstallResult(False, "", hint)except FileNotFoundError as e: # uv vanished between lookup and spawn; it never evaluated the requirementslogger.debug("uv invocation failed: %s", e)# Tier 2: python -m pip (ensurepip bootstrap if needed)