"""Prepare and publish the locked kernel project environment on an SSH host.""" from __future__ import annotations import fcntl import hashlib import json import os from pathlib import Path import shutil import site import subprocess import sys import tempfile from typing import Literal Source = Literal["host", "managed"] # The locked dependencies must load from the prepared environment. The # interpreter can otherwise start after its venv or installed files are lost. _CHECK = ( "from pathlib import Path; import sys, dill, pydantic; " "prefix = Path(sys.prefix).resolve(); " "assert prefix == Path(sys.argv[1]); " # uv may link a wheel from its cache. Check where Python found the module. "assert Path(dill.__file__).is_relative_to(prefix); " "assert Path(pydantic.__file__).is_relative_to(prefix)" ) def _check(env: Path) -> str | None: try: result = subprocess.run( [str(env / "bin/python"), "-E", "-P", "-c", _CHECK, str(env)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, errors="replace", ) except OSError as error: return str(error) return ( None if result.returncode == 0 else result.stderr.strip() or (f"Python exited with status {result.returncode}") ) def _current(selector: Path, source: Source, identity_root: Path) -> Path | None: try: env = selector.resolve(strict=True) if env.parent != identity_root: return None if (env / ".ready").read_text() != source or _check(env) is not None: return None except (OSError, RuntimeError, UnicodeError): return None return env / "bin/python" def _run_uv(uv: str, args: list[str], project: Path, env: Path) -> None: command = [uv, *args] result = subprocess.run( command, cwd=project, env={ **os.environ, "UV_PROJECT_ENVIRONMENT": str(env), "UV_PYTHON_DOWNLOADS": "never", }, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace", ) if result.returncode: detail = result.stdout.strip()[-1200:] raise RuntimeError( f"uv {args[0]} exited with status {result.returncode} using Python " f"{sys.version.split()[0]} at {sys.executable}\n{detail}" ) def _visible_sites() -> list[str]: sites = site.getsitepackages() if site.ENABLE_USER_SITE: sites.append(site.getusersitepackages()) # Nix wrappers can add separately installed packages via sitecustomize. return [ path for path in sys.path if path in sites or Path(path).name in ("site-packages", "dist-packages") ] def _build(uv: str, env: Path, visible_sites: list[str]) -> None: project = Path(__file__).resolve().parent _run_uv(uv, ["venv", "--python", sys.executable, str(env)], project, env) _run_uv( uv, [ "sync", "--locked", "--no-dev", "--project", str(project), "--python", sys.executable, ], project, env, ) # Private kernel launches ignore Python environment settings at startup. # Append project paths after the locked packages without removing # PYTHONPATH from the environment that commands inherit. purelib = subprocess.check_output( [ str(env / "bin/python"), "-I", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))", ], text=True, ).strip() load_host_paths = [ "import os, site, sys", 'pythonpath = os.environ.get("PYTHONPATH")', "sys.path.extend(map(os.path.abspath, pythonpath.split(os.pathsep))) " "if pythonpath and sys.flags.ignore_environment and not sys.flags.isolated else None", ] # Process the host's .pth files too, including editable installs. load_host_paths.extend( f"site.addsitedir({path!r}) if {path!r} not in sys.path else None" for path in visible_sites ) Path(purelib, "albedo_host.pth").write_text("; ".join(load_host_paths) + "\n") failure = _check(env) if failure is not None: raise RuntimeError(f"prepared Python failed its startup check\n{failure}") def prepare(selector: Path, source: Source, uv: str | None) -> Path | None: # The warm managed probe starts this script inside the selected venv. if source == "managed" and uv is None: env = Path(sys.prefix).resolve() if not env.is_relative_to(selector.parent.resolve()): return None try: if (env / ".ready").read_text() != source: return None except (OSError, UnicodeError): return None return env / "bin/python" if _check(env) is None else None visible_sites = _visible_sites() if source == "host" else [] stat = Path(sys.executable).stat() identity = [ source, sys.executable, sys.version, stat.st_dev, stat.st_ino, stat.st_mtime_ns, visible_sites, ] key = hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:24] root = selector.parent.resolve() identity_root = root / key selector = identity_root / "current" if source == "host" else root / selector.name if uv is None: return _current(selector, source, identity_root) root.mkdir(parents=True, exist_ok=True) with (root / ".lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX) current = _current(selector, source, identity_root) if current is not None: return current identity_root.mkdir(exist_ok=True) # Wheel entry points embed this path. Build in place and publish the # selector last. Kernels can still be running in earlier generations. # Host selections keep one link per interpreter identity so switching # interpreters does not invalidate a previously prepared environment. env = Path(tempfile.mkdtemp(prefix="env-", dir=identity_root)) try: _build(uv, env, visible_sites) (env / ".ready").write_text(source) with tempfile.TemporaryDirectory( dir=root, ignore_cleanup_errors=True ) as directory: link = Path(directory) / "current" link.symlink_to(env) os.replace(link, selector) except (OSError, RuntimeError, subprocess.SubprocessError): shutil.rmtree(env, ignore_errors=True) raise return env / "bin/python" if __name__ == "__main__": mode = sys.argv[2] if mode not in ("host", "managed"): raise ValueError(f"unknown interpreter source: {mode}") selector = Path(sys.argv[1]) try: uv = sys.argv[3] if len(sys.argv) > 3 else None print(prepare(selector, mode, uv) or "cold") except (OSError, RuntimeError, subprocess.SubprocessError) as error: sys.exit(str(error))