diff --git a/contributors/emails/vivojf@gmail.com b/contributors/emails/vivojf@gmail.com new file mode 100644 index 0000000000..1685b01941 --- /dev/null +++ b/contributors/emails/vivojf@gmail.com @@ -0,0 +1,2 @@ +jfugalde +# PR #130255 salvage (pm: missing C/C++ compiler under the pinned Python) diff --git a/pm/build_compilers.py b/pm/build_compilers.py new file mode 100644 index 0000000000..43ad33b3e2 --- /dev/null +++ b/pm/build_compilers.py @@ -0,0 +1,96 @@ +"""Point native source builds under PM's pinned interpreter at tools this host has. + +python-build-standalone records the toolchain it was built with in sysconfig: +on Linux ``CC = 'clang -pthread'``, ``CXX = 'clang++ -pthread'``, linkers that +start with the same commands, and an ``AR`` under its deleted ``/tools/llvm`` +build directory; on macOS only that archiver is foreign. setuptools compiles +every extension with those values unless the environment overrides them, so a +Debian/Ubuntu/WSL host with only gcc/g++ failed any sdist build with +``No such file or directory: 'clang++'`` (python-olm, via the matrix extra). + +Stdlib only: ``pm.environment.classify_uv_failure`` imports this on the +bootstrap runner's pre-3.11 system python. +""" +from __future__ import annotations + +from collections.abc import Mapping +import functools +import json +from pathlib import Path +import re +import shutil +import subprocess +import sys + +# setuptools derives LDSHARED from an overridden CC but never LDCXXSHARED from +# CXX, so each compiler's own linker is rewritten with it. +_COMPILERS = (("CC", "LDSHARED"), ("CXX", "LDCXXSHARED")) +_GCC_FAMILY = {"clang": "gcc", "clang++": "g++"} +_RECORDED = ("CC", "CXX", "LDSHARED", "LDCXXSHARED", "AR") + +_MISSING_COMPILER = ( + re.compile(r"No such file or directory: '([^']+)'"), + re.compile(r"command '([^']+)' failed"), + re.compile(r"No CMAKE_(?:C|CXX)_COMPILER could be found"), +) +_COMPILER_NAME = re.compile(r"(?:clang(?:\+\+)?|g?cc|g\+\+|c\+\+)(?:-[\d.]+)?") +_COMPILER_REMEDY = ("{what}: install a C/C++ compiler (Debian/Ubuntu/WSL: `sudo apt install build-essential`; " + "Fedora: `sudo dnf install gcc gcc-c++`; macOS: `xcode-select --install`) " + "or point CC/CXX at one, then retry") + + +@functools.lru_cache(maxsize=None) # noqa: UP033 -- functools.cache is 3.9+; the bootstrap runner can be older +def _recorded_toolchain(python: str) -> dict[str, str]: + code = ("import json, sysconfig; " + f"print(json.dumps({{k: sysconfig.get_config_var(k) or '' for k in {_RECORDED!r}}}))") + try: + result = subprocess.run([python, "-I", "-c", code], capture_output=True, text=True, + timeout=30, check=False) + return json.loads(result.stdout) if result.returncode == 0 else {} + except (OSError, subprocess.TimeoutExpired, ValueError): + return {} + + +def _linux_defaults(recorded: Mapping[str, str], env: Mapping[str, str]) -> dict[str, str]: + search = env.get("PATH") + defaults: dict[str, str] = {} + for compiler_var, linker_var in _COMPILERS: + command = recorded.get(compiler_var, "") + program = command.split(" ", 1)[0] + substitute = _GCC_FAMILY.get(program) + if (compiler_var in env or substitute is None or shutil.which(program, path=search) + or not shutil.which(substitute, path=search)): + continue + defaults[compiler_var] = substitute + command[len(program):] + linker = recorded.get(linker_var, "") + if linker_var not in env and linker.split(" ", 1)[0] == program: + defaults[linker_var] = substitute + linker[len(program):] + archiver = recorded.get("AR", "") + if archiver and not shutil.which(archiver, path=search) and shutil.which("ar", path=search): + defaults["AR"] = "ar" + return defaults + + +def pinned_build_defaults(python: Path, env: Mapping[str, str]) -> dict[str, str]: + """Defaults for build variables the pinned interpreter records but this host lacks. + + Callers ``setdefault`` them, so a CC/CXX/AR the user set always wins. A recorded + compiler with no gcc-family equivalent on PATH is left alone; the build then + fails and ``missing_compiler_remedy`` names the fix. + """ + if sys.platform == "darwin": + return {"AR": "/usr/bin/ar"} + if sys.platform != "linux": + return {} + return _linux_defaults(_recorded_toolchain(str(python)), env) + + +def missing_compiler_remedy(output: str) -> str: + """The install hint for a build that failed because no compiler exists, else ''.""" + for pattern in _MISSING_COMPILER: + for match in pattern.finditer(output): + if not match.groups(): + return _COMPILER_REMEDY.format(what="this package compiles native code and no compiler was found") + if _COMPILER_NAME.fullmatch(Path(match.group(1)).name): + return _COMPILER_REMEDY.format(what=f"the build needs `{match.group(1)}`, which is not on PATH") + return "" diff --git a/pm/environment.py b/pm/environment.py index d62e071b74..5267db63d4 100644 --- a/pm/environment.py +++ b/pm/environment.py @@ -111,7 +111,9 @@ def classify_uv_failure(stage: str, returncode: int, output: str) -> InstallErro if any(marker in lowered for marker in _RESOLVER_MARKERS): return ResolutionConflict("venv", cause) if any(marker in lowered for marker in _BUILD_MARKERS): - return BuildFailure("venv", cause) + from pm.build_compilers import missing_compiler_remedy + + return BuildFailure("venv", cause, missing_compiler_remedy(output)) return InstallError("venv", cause) @@ -265,10 +267,12 @@ def managed_environment(destination: Path, *, python: Path | None = None, uv, pinned_python = tools python = pinned_python if python is None else python.absolute() build_env = _base_environment(env) - if sys.platform == "darwin" and python.resolve() == pinned_python.resolve(): - # PBS's AR still names its deleted build directory. Its CC is already - # clang; only the archiver needs a default, and only for our interpreter. - build_env.setdefault("AR", "/usr/bin/ar") + if python.resolve() == pinned_python.resolve(): + # Only our interpreter: a separately selected one (e.g. Nix) keeps its own sysconfig. + from pm.build_compilers import pinned_build_defaults + + for key, value in pinned_build_defaults(python, build_env).items(): + build_env.setdefault(key, value) return PythonEnvironment( uv=uv, python=python, destination=destination.absolute(), cache=uv_cache_dir() if cache is None else cache.absolute(), diff --git a/tests/pm/test_linux_build_compilers.py b/tests/pm/test_linux_build_compilers.py new file mode 100644 index 0000000000..6ad217f710 --- /dev/null +++ b/tests/pm/test_linux_build_compilers.py @@ -0,0 +1,70 @@ +"""Source builds under PM's pinned interpreter use compilers the host actually has.""" +from __future__ import annotations + +import json +from pathlib import Path +import sys + +import pytest + +# What python-build-standalone 3.14 records on x86_64 Linux (sysconfig.get_config_var). +_LDFLAGS = " -shared -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now -Wl,--build-id=sha1 -Wl,--exclude-libs,ALL" +_PBS_LINUX = { + "CC": "clang -pthread", "CXX": "clang++ -pthread", + "LDSHARED": "clang -pthread" + _LDFLAGS, "LDCXXSHARED": "clang++ -pthread" + _LDFLAGS, + "AR": "/tools/llvm/bin/llvm-ar", +} + + +def _executables(directory: Path, *names: str) -> str: + directory.mkdir() + for name in names: + tool = directory / name + tool.write_text("#!/bin/sh\n", encoding="utf-8") + tool.chmod(0o755) + return str(directory) + + +@pytest.mark.platforms("linux") +def test_pinned_interpreter_builds_with_gcc_when_its_clang_is_missing(tmp_path, monkeypatch): + from pm.environment import managed_environment + + pinned = tmp_path / "pinned-python" + pinned.write_text(f"#!/bin/sh\necho '{json.dumps(_PBS_LINUX)}'\n", encoding="utf-8") + pinned.chmod(0o755) + monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (tmp_path / "uv", pinned)) + gcc_only = _executables(tmp_path / "gcc-only", "gcc", "g++", "ar") + + built = managed_environment(tmp_path / "gcc", env={"PATH": gcc_only}, cache=tmp_path).env + assert {key: built.get(key) for key in _PBS_LINUX} == { + "CC": "gcc -pthread", "CXX": "g++ -pthread", + "LDSHARED": "gcc -pthread" + _LDFLAGS, "LDCXXSHARED": "g++ -pthread" + _LDFLAGS, + "AR": "ar", + } + # A compiler the user chose wins, and so does the linker setuptools derives from it. + chosen = managed_environment(tmp_path / "chosen", env={"PATH": gcc_only, "CXX": "clang++"}, + cache=tmp_path).env + assert (chosen["CXX"], chosen["CC"]) == ("clang++", "gcc -pthread") + assert "LDCXXSHARED" not in chosen + # A host with the recorded compilers keeps the interpreter's own toolchain. + with_clang = _executables(tmp_path / "with-clang", "clang", "clang++", "gcc", "g++") + kept = managed_environment(tmp_path / "kept", env={"PATH": with_clang}, cache=tmp_path).env + assert not {"CC", "CXX", "LDSHARED", "LDCXXSHARED"} & kept.keys() + # Any other interpreter (Nix, a user's own) keeps its sysconfig untouched. + other = managed_environment(tmp_path / "other", python=Path(sys.executable), + env={"PATH": gcc_only}, cache=tmp_path).env + assert other == {"PATH": gcc_only} + + +def test_build_failure_without_any_compiler_names_the_install(tmp_path): + from pm.environment import BuildFailure, classify_uv_failure + + # uv's real tail when neither clang++ nor g++ exists (python-olm 3.2.16, Ubuntu 24.04). + missing = ("error: Failed to build `python-olm==3.2.16`\n ├─▶ The build backend returned an error\n" + " ╰─▶ Call to `setuptools.build_meta.build_wheel` failed (exit status: 1)\n" + " error: [Errno 2] No such file or directory: 'clang++'\n") + failure = classify_uv_failure("pip", 1, missing) + assert isinstance(failure, BuildFailure) + assert "build-essential" in failure.remedy + other = classify_uv_failure("pip", 1, missing.replace("'clang++'", "'libolm/include/olm.h'")) + assert "build-essential" not in other.remedy diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.md index 188aa0c801..3cde2dd6de 100644 --- a/website/docs/reference/package-management.md +++ b/website/docs/reference/package-management.md @@ -238,6 +238,14 @@ This applies to source and bundle builds alike. Explicit `AR` and `CC` values remain authoritative; PM does not change the toolchain of a caller-supplied interpreter such as Nix Python. No `CC` default is needed for the current pin. +The pinned Linux Python records `clang`/`clang++` as `CC`/`CXX` and the same +temporary `llvm-ar` as `AR`. When a recorded compiler is not on `PATH` but its +GCC equivalent is (`gcc`/`g++`, as on stock Debian, Ubuntu and WSL), PM points +`CC`/`CXX` and the matching `LDSHARED`/`LDCXXSHARED` at it, keeping flags such +as `-pthread`, and defaults `AR` to the host's `ar`. A `CC`, `CXX`, `LDSHARED`, +`LDCXXSHARED` or `AR` you set yourself wins. With no compiler at all, a source +build fails with a hint to install one (`sudo apt install build-essential`). + Clone the repository and select your branch before preparing dependencies: ```bash