|
| 1 | +"""Lazy install of a per-ABI runtime tree for cross-Python ``roar run``. |
| 2 | +
|
| 3 | +When ``uv tool install roar-cli`` installs roar under one Python (e.g. 3.13) |
| 4 | +but ``roar run`` is invoked against a different one (e.g. system 3.12), |
| 5 | +roar's bundled compiled deps don't match the traced Python's ABI. This |
| 6 | +module installs a matching tree of runtime deps on demand into a per-ABI |
| 7 | +cache directory under ``~/.cache/roar/runtime/<tag>/``. |
| 8 | +
|
| 9 | +``sitecustomize.py``'s ``_append_roar_runtime_pythonpath`` prepends the |
| 10 | +cache directory to ``sys.path`` in the traced process, so imports there |
| 11 | +resolve to the ABI-matched copies before reaching roar's bundled tree. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import contextlib |
| 17 | +import json |
| 18 | +import os |
| 19 | +import shutil |
| 20 | +import subprocess |
| 21 | +import sys |
| 22 | +import tempfile |
| 23 | +import time |
| 24 | +from pathlib import Path |
| 25 | + |
| 26 | +# Deps backend dispatch needs in the traced Python. Kept short — pip/uv |
| 27 | +# resolves transitive deps. Unpinned: roar tolerates any pydantic 2.x. |
| 28 | +_RUNTIME_DEPS: tuple[str, ...] = ("pydantic", "blake3") |
| 29 | + |
| 30 | +_STAMP_FILENAME = "roar_runtime.json" |
| 31 | +_INSTALL_TIMEOUT_SECONDS = 180 |
| 32 | + |
| 33 | + |
| 34 | +def runtime_cache_root() -> Path: |
| 35 | + """Return ``$XDG_CACHE_HOME/roar/runtime`` (default ``~/.cache/roar/runtime``).""" |
| 36 | + xdg_cache = os.environ.get("XDG_CACHE_HOME") |
| 37 | + base = Path(xdg_cache) if xdg_cache else Path.home() / ".cache" |
| 38 | + return base / "roar" / "runtime" |
| 39 | + |
| 40 | + |
| 41 | +def runtime_cache_dir(abi_tag: str) -> Path: |
| 42 | + """Return the per-ABI cache directory (e.g. ``.../roar/runtime/cp312/``).""" |
| 43 | + return runtime_cache_root() / abi_tag |
| 44 | + |
| 45 | + |
| 46 | +def runtime_site_packages(abi_tag: str) -> Path: |
| 47 | + return runtime_cache_dir(abi_tag) / "site-packages" |
| 48 | + |
| 49 | + |
| 50 | +def is_runtime_cached(abi_tag: str, roar_version: str) -> bool: |
| 51 | + """True iff a matching, roar-version-stamped runtime tree exists for ``abi_tag``.""" |
| 52 | + stamp_path = runtime_cache_dir(abi_tag) / _STAMP_FILENAME |
| 53 | + if not stamp_path.is_file(): |
| 54 | + return False |
| 55 | + try: |
| 56 | + stamp = json.loads(stamp_path.read_text()) |
| 57 | + except (OSError, ValueError): |
| 58 | + return False |
| 59 | + return stamp.get("roar_version") == roar_version |
| 60 | + |
| 61 | + |
| 62 | +def install_runtime( |
| 63 | + abi_tag: str, |
| 64 | + target_python: str, |
| 65 | + roar_version: str, |
| 66 | + deps: tuple[str, ...] = _RUNTIME_DEPS, |
| 67 | +) -> bool: |
| 68 | + """Install a matching runtime tree for ``abi_tag``. Returns ``True`` on success. |
| 69 | +
|
| 70 | + Atomic: installs into a tempdir alongside the cache root, then renames |
| 71 | + into place. Failures (no network, missing pip, etc.) leave the cache in |
| 72 | + its prior state — callers should treat a ``False`` return as "fall back |
| 73 | + to the sitecustomize gate." |
| 74 | + """ |
| 75 | + cache_dir = runtime_cache_dir(abi_tag) |
| 76 | + sys.stderr.write(f"🦖 installing roar runtime for {abi_tag} ...\n") |
| 77 | + sys.stderr.flush() |
| 78 | + |
| 79 | + try: |
| 80 | + cache_root = runtime_cache_root() |
| 81 | + cache_root.mkdir(parents=True, exist_ok=True) |
| 82 | + except OSError: |
| 83 | + return False |
| 84 | + |
| 85 | + tmpdir = Path(tempfile.mkdtemp(prefix="roar-runtime-", dir=cache_root)) |
| 86 | + moved = False |
| 87 | + try: |
| 88 | + target_site = tmpdir / "site-packages" |
| 89 | + target_site.mkdir(parents=True) |
| 90 | + installer_cmd = _select_installer(target_python, target_site, deps) |
| 91 | + if installer_cmd is None: |
| 92 | + sys.stderr.write("🦖 install failed: no installer found (need uv or pip)\n") |
| 93 | + return False |
| 94 | + try: |
| 95 | + result = subprocess.run( |
| 96 | + installer_cmd, |
| 97 | + capture_output=True, |
| 98 | + text=True, |
| 99 | + timeout=_INSTALL_TIMEOUT_SECONDS, |
| 100 | + check=False, |
| 101 | + ) |
| 102 | + except (OSError, subprocess.SubprocessError) as exc: |
| 103 | + sys.stderr.write(f"🦖 install failed: {exc}\n") |
| 104 | + return False |
| 105 | + if result.returncode != 0: |
| 106 | + stderr_tail = (result.stderr or "").strip()[-500:] |
| 107 | + sys.stderr.write(f"🦖 install failed (rc={result.returncode}): {stderr_tail}\n") |
| 108 | + return False |
| 109 | + |
| 110 | + stamp_data = { |
| 111 | + "roar_version": roar_version, |
| 112 | + "abi_tag": abi_tag, |
| 113 | + "installed_at": time.time(), |
| 114 | + "deps": list(deps), |
| 115 | + } |
| 116 | + (tmpdir / _STAMP_FILENAME).write_text(json.dumps(stamp_data, indent=2)) |
| 117 | + |
| 118 | + if cache_dir.exists(): |
| 119 | + with contextlib.suppress(OSError): |
| 120 | + shutil.rmtree(cache_dir) |
| 121 | + try: |
| 122 | + os.rename(tmpdir, cache_dir) |
| 123 | + moved = True |
| 124 | + except OSError: |
| 125 | + return False |
| 126 | + finally: |
| 127 | + if not moved: |
| 128 | + with contextlib.suppress(Exception): |
| 129 | + shutil.rmtree(tmpdir) |
| 130 | + |
| 131 | + return is_runtime_cached(abi_tag, roar_version) |
| 132 | + |
| 133 | + |
| 134 | +def _select_installer( |
| 135 | + target_python: str, target_dir: Path, deps: tuple[str, ...] |
| 136 | +) -> list[str] | None: |
| 137 | + """Pick the install command. Prefer ``uv pip install --target --python``.""" |
| 138 | + uv = shutil.which("uv") |
| 139 | + if uv: |
| 140 | + return [ |
| 141 | + uv, |
| 142 | + "pip", |
| 143 | + "install", |
| 144 | + "--target", |
| 145 | + str(target_dir), |
| 146 | + "--python", |
| 147 | + target_python, |
| 148 | + *deps, |
| 149 | + ] |
| 150 | + # Fallback: plain pip. Only works if `pip` is in the target Python's env; |
| 151 | + # best-effort. uv is strongly preferred because of the --python flag. |
| 152 | + pip = shutil.which("pip") or shutil.which("pip3") |
| 153 | + if pip: |
| 154 | + return [pip, "install", "--target", str(target_dir), *deps] |
| 155 | + return None |
| 156 | + |
| 157 | + |
| 158 | +def runtime_install_mode(start_dir: Path | None = None) -> str: |
| 159 | + """Resolve runtime.install mode: ``'auto'`` (default) or ``'skip'``. |
| 160 | +
|
| 161 | + ``ROAR_RUNTIME_INSTALL`` env var takes precedence over project config. |
| 162 | + Anything unrecognized falls back to ``'auto'``. |
| 163 | + """ |
| 164 | + env_value = os.environ.get("ROAR_RUNTIME_INSTALL") |
| 165 | + if env_value: |
| 166 | + normalized = env_value.strip().lower() |
| 167 | + if normalized in ("auto", "skip"): |
| 168 | + return normalized |
| 169 | + return "auto" |
| 170 | + |
| 171 | + try: |
| 172 | + from roar.integrations.config.access import config_get |
| 173 | + |
| 174 | + configured = config_get("runtime.install", start_dir=start_dir) |
| 175 | + except Exception: |
| 176 | + return "auto" |
| 177 | + if isinstance(configured, str) and configured.lower() in ("auto", "skip"): |
| 178 | + return configured.lower() |
| 179 | + return "auto" |
| 180 | + |
| 181 | + |
| 182 | +def ensure_runtime( |
| 183 | + target_python: str, |
| 184 | + target_abi: str, |
| 185 | + bundled_abi: str | None, |
| 186 | + roar_version: str, |
| 187 | + mode: str | None = None, |
| 188 | + start_dir: Path | None = None, |
| 189 | +) -> Path | None: |
| 190 | + """Return the site-packages path for an ABI-matched runtime, or ``None``. |
| 191 | +
|
| 192 | + Behavior: |
| 193 | + - No action when ``target_abi`` matches ``bundled_abi`` — bundled wins. |
| 194 | + - No action when mode is ``'skip'`` — gate handles whatever happens. |
| 195 | + - Cache hit: return the cached path. |
| 196 | + - Cache miss: install lazily and return the path on success. |
| 197 | + - Install failure: ``None`` (caller falls back to the gate). |
| 198 | + """ |
| 199 | + if not target_abi: |
| 200 | + return None |
| 201 | + if bundled_abi and target_abi == bundled_abi: |
| 202 | + return None |
| 203 | + |
| 204 | + resolved_mode = mode or runtime_install_mode(start_dir) |
| 205 | + if resolved_mode == "skip": |
| 206 | + return None |
| 207 | + |
| 208 | + if is_runtime_cached(target_abi, roar_version): |
| 209 | + return runtime_site_packages(target_abi) |
| 210 | + |
| 211 | + if install_runtime(target_abi, target_python, roar_version): |
| 212 | + return runtime_site_packages(target_abi) |
| 213 | + return None |
0 commit comments