Debian Codegraph @

mypyc/test/librt_cache.py

raw
1 """Build and cache librt for use in tests.
2
3 This module provides a way to build librt extension modules once and cache
4 them across test runs, and across different test cases in a single run. The
5 cache is invalidated when source files or details of the build environment change.
6
7 Note: Tests must run in a subprocess to use the cached librt, since importing
8 this module also triggers the import of the regular installed librt.
9
10 Usage:
11 from mypyc.test.librt_cache import get_librt_path, run_with_librt
12
13 # Get path to built librt (builds if needed)
14 path = get_librt_path()
15
16 # Run a test file in subprocess with built librt
17 result = run_with_librt("test_librt.py")
18 """
19
20 from __future__ import annotations
21
22 import hashlib
23 import os
24 import shutil
25 import subprocess
26 import sys
27 import sysconfig
28 from typing import Any
29
30 import filelock
31
32 from mypyc.build import LIBRT_MODULES, get_cflags, include_dir
33 from mypyc.common import RUNTIME_C_FILES
34 from mypyc.test.config import PREFIX
35
36
37 def _librt_build_hash(experimental: bool, opt_level: str) -> str:
38 """Compute hash for librt build, including sources and build environment."""
39 # Import lazily to ensure mypyc.build has ensured that distutils is correctly set up
40 from distutils import ccompiler
41
42 h = hashlib.sha256()
43 # Include experimental flag
44 h.update(b"exp" if experimental else b"noexp")
45 h.update(f"opt={opt_level}".encode())
46 # Include full Python version string (includes git hash for dev builds)
47 h.update(sys.version.encode())
48 # Include debug build status (gettotalrefcount only exists in debug builds)
49 is_debug = hasattr(sys, "gettotalrefcount")
50 h.update(b"debug" if is_debug else b"release")
51 # Include free-threading status (Python 3.13+)
52 is_free_threaded = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
53 h.update(b"freethreaded" if is_free_threaded else b"gil")
54 # Include compiler type (e.g., "unix" or "msvc")
55 compiler: Any = ccompiler.new_compiler()
56 h.update(compiler.compiler_type.encode())
57 # Include environment variables that affect C compilation
58 for var in ("CC", "CXX", "CFLAGS", "CPPFLAGS", "LDFLAGS"):
59 val = os.environ.get(var, "")
60 h.update(f"{var}={val}".encode())
61 # Hash runtime files
62 for name in RUNTIME_C_FILES:
63 path = os.path.join(include_dir(), name)
64 h.update(name.encode() + b"|")
65 with open(path, "rb") as f:
66 h.update(f.read())
67 # Hash librt module files
68 for mod, files, extra, includes in LIBRT_MODULES:
69 for fname in files + extra:
70 path = os.path.join(include_dir(), fname)
71 h.update(fname.encode() + b"|")
72 with open(path, "rb") as f:
73 h.update(f.read())
74 return h.hexdigest()[:16]
75
76
77 def _generate_setup_py(build_dir: str, experimental: bool, opt_level: str) -> str:
78 """Generate setup.py content for building librt directly.
79
80 We inline LIBRT_MODULES/RUNTIME_C_FILES/include_dir/cflags values to avoid
81 importing mypyc.build, which recursively imports lots of things.
82 """
83 lib_rt_dir = include_dir()
84
85 # Get compiler flags using the shared helper
86 cflags = get_cflags(opt_level=opt_level, experimental_features=experimental)
87
88 # Serialize values to inline in generated setup.py
89 librt_modules_repr = repr(
90 [(m.module, m.c_files, m.other_files, m.include_dirs) for m in LIBRT_MODULES]
91 )
92 runtime_files_repr = repr(RUNTIME_C_FILES)
93 cflags_repr = repr(cflags)
94
95 return f"""\
96 import os
97 from setuptools import setup, Extension
98 import build_setup # noqa: F401 # Monkey-patches compiler for per-file SIMD flags
99
100 build_dir = {build_dir!r}
101 lib_rt_dir = {lib_rt_dir!r}
102
103 RUNTIME_C_FILES = {runtime_files_repr}
104 LIBRT_MODULES = {librt_modules_repr}
105 CFLAGS = {cflags_repr}
106
107 def write_file(path, contents):
108 os.makedirs(os.path.dirname(path), exist_ok=True)
109 with open(path, "wb") as f:
110 f.write(contents)
111
112 # Copy runtime C files
113 for name in RUNTIME_C_FILES:
114 src = os.path.join(lib_rt_dir, name)
115 dst = os.path.join(build_dir, name)
116 with open(src, "rb") as f:
117 write_file(dst, f.read())
118
119 # Build extensions for each librt module
120 extensions = []
121 for mod, file_names, extra_files, includes in LIBRT_MODULES:
122 # Copy source files
123 for fname in file_names + extra_files:
124 src = os.path.join(lib_rt_dir, fname)
125 dst = os.path.join(build_dir, fname)
126 with open(src, "rb") as f:
127 write_file(dst, f.read())
128
129 extensions.append(Extension(
130 mod,
131 sources=[os.path.join(build_dir, f) for f in file_names + RUNTIME_C_FILES],
132 include_dirs=[lib_rt_dir] + [os.path.join(lib_rt_dir, d) for d in includes],
133 extra_compile_args=CFLAGS,
134 ))
135
136 setup(name='librt_cached', ext_modules=extensions)
137 """
138
139
140 def get_librt_path(experimental: bool = True, opt_level: str = "0") -> str:
141 """Get path to librt built from the repository, building and caching if necessary.
142
143 Uses build/librt-cache/ under the repo root (gitignored). The cache is
144 keyed by a hash of sources and build environment, so it auto-invalidates
145 when relevant factors change.
146
147 Safe to call from multiple parallel pytest workers - uses file locking.
148
149 Args:
150 experimental: Whether to enable experimental features.
151 opt_level: Optimization level ("0".."3") used when building librt.
152
153 Returns:
154 Path to directory containing built librt modules.
155 """
156 # Use build/librt-cache/ under the repo root (gitignored)
157 cache_root = os.path.join(PREFIX, "build", "librt-cache")
158 build_hash = _librt_build_hash(experimental, opt_level)
159 build_dir = os.path.join(cache_root, f"librt-{build_hash}")
160 lock_file = os.path.join(cache_root, f"librt-{build_hash}.lock")
161 marker = os.path.join(build_dir, ".complete")
162
163 os.makedirs(cache_root, exist_ok=True)
164
165 with filelock.FileLock(lock_file, timeout=300): # 5 min timeout
166 if os.path.exists(marker):
167 return build_dir
168
169 # Clean up any partial build
170 if os.path.exists(build_dir):
171 shutil.rmtree(build_dir)
172
173 os.makedirs(build_dir)
174
175 # Create librt package directory for --inplace to copy .so files into
176 librt_pkg = os.path.join(build_dir, "librt")
177 os.makedirs(librt_pkg)
178 with open(os.path.join(librt_pkg, "__init__.py"), "w") as f:
179 pass
180
181 # Copy build_setup.py for per-file SIMD compiler flags
182 build_setup_src = os.path.join(
183 os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "build_setup.py"
184 )
185 build_setup_dst = os.path.join(build_dir, "build_setup.py")
186 shutil.copy(build_setup_src, build_setup_dst)
187
188 # Write setup.py
189 setup_py = os.path.join(build_dir, "setup.py")
190 with open(setup_py, "w") as f:
191 f.write(_generate_setup_py(build_dir, experimental, opt_level))
192
193 # Build (parallel builds don't work well because multiple extensions
194 # share the same runtime C files, causing race conditions)
195 result = subprocess.run(
196 [sys.executable, setup_py, "build_ext", "--inplace"],
197 cwd=build_dir,
198 capture_output=True,
199 text=True,
200 )
201 if result.returncode != 0:
202 raise RuntimeError(f"librt build failed:\n{result.stdout}\n{result.stderr}")
203
204 # Mark complete
205 with open(marker, "w") as f:
206 f.write("ok")
207
208 return build_dir
209
210
211 def run_with_librt(
212 file_path: str, experimental: bool = True, check: bool = True, opt_level: str = "0"
213 ) -> subprocess.CompletedProcess[str]:
214 """Run a Python file in a subprocess with built librt available.
215
216 This runs the file in a fresh Python process where the built librt
217 is at the front of sys.path, avoiding conflicts with any system librt.
218
219 Args:
220 file_path: Path to Python file to execute.
221 experimental: Whether to use experimental features.
222 check: If True, raise CalledProcessError on non-zero exit.
223 opt_level: Optimization level ("0".."3") used when building librt.
224
225 Returns:
226 CompletedProcess with stdout, stderr, and returncode.
227 """
228 librt_path = get_librt_path(experimental, opt_level=opt_level)
229 # Prepend librt path to PYTHONPATH
230 env = os.environ.copy()
231 existing = env.get("PYTHONPATH", "")
232 env["PYTHONPATH"] = librt_path + (os.pathsep + existing if existing else "")
233
234 return subprocess.run(
235 [sys.executable, file_path], capture_output=True, text=True, check=check, env=env
236 )