Skip to content

Commit 24b32f8

Browse files
authored
relocatable.py test: check that every stdlib extension module loads from the moved tree (#38)
The `stdlib.*` checks import seven modules and use each one briefly, but they don't check where the extension module came from, and most extension modules (`_zstd`, `_decimal`, `readline`, ...) aren't covered at all. This adds a `stdlib.extensions` check. It imports every stdlib extension module (found through `sys.stdlib_module_names`, so there's no list to maintain), first with the build directory's interpreter and then with the moved one. It fails if a module that imports in the build directory is missing after the move, fails to import, or is loaded from outside the moved tree. Modules that already fail in the build directory are left out, like the existing `stdlib.*` checks do. Which shared libraries those modules link against is a separate question, covered by `loader.paths` in #36. Tested on macOS 14 arm64 against today's CPython `main`, with both `--strategy patch` and `--strategy origin`: `PASS stdlib.extensions: 57 extension modules load from the relocated tree`.
1 parent a7e3488 commit 24b32f8

2 files changed

Lines changed: 79 additions & 8 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ Either way, `gather` runs CPython's top-level `make install ENSUREPIP=no` into a
5252
- A shared build loads libpython from inside the moved tree, not from the original install
5353
- No installed file still mentions the old prefix
5454
- A few stdlib extension modules still work (ones that already fail in the build directory are skipped)
55+
- Every stdlib extension module that imports in the build directory still imports, from inside the moved tree
5556
- Those paths are still right when Python is run through a symlink
5657
- A venv created from it works
5758
- `build-details.json` and `python-config` give paths inside the moved tree

‎relocatability.py‎

Lines changed: 78 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,33 @@ class DlInfo(ctypes.Structure):
6666
print(json.dumps({"path": os.path.realpath(os.fsdecode(info.dli_fname))}))
6767
"""
6868

69+
# Imports every stdlib extension module and reports where each was loaded
70+
# from.
71+
EXTENSIONS_PROBE = r"""
72+
import importlib
73+
import importlib.machinery
74+
import importlib.util
75+
import json
76+
import sys
77+
78+
results = {}
79+
for name in sorted(sys.stdlib_module_names):
80+
try:
81+
spec = importlib.util.find_spec(name)
82+
except Exception:
83+
continue
84+
origin = getattr(spec, "origin", None) or ""
85+
if not origin.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):
86+
continue
87+
try:
88+
module = importlib.import_module(name)
89+
except Exception as exc:
90+
results[name] = {"error": f"{type(exc).__name__}: {exc}"}
91+
else:
92+
results[name] = {"file": module.__file__}
93+
print(json.dumps(results, sort_keys=True))
94+
"""
95+
6996
# Seconds to wait for each probe.
7097
TIMEOUT = 30
7198

@@ -338,6 +365,7 @@ def run(self) -> list[CheckResult]:
338365
f"stdlib.{module}",
339366
lambda module=module: self._check_stdlib(module),
340367
)
368+
self._check("stdlib.extensions", self._check_extensions)
341369
self._check("runtime.symlink", self._check_symlink)
342370
self._check("runtime.venv", self._check_venv)
343371
self._check("developer.c-extension", self._check_c_extension)
@@ -393,14 +421,15 @@ def _run(
393421
command: list[str | os.PathLike[str]],
394422
*,
395423
cwd: pathlib.Path | None = None,
424+
env: dict[str, str] | None = None,
396425
timeout: int = TIMEOUT,
397426
) -> subprocess.CompletedProcess[str]:
398427
args = [os.fspath(part) for part in command]
399428
try:
400429
return subprocess.run(
401430
args,
402431
cwd=cwd or self.work_dir,
403-
env=self.env,
432+
env=env or self.env,
404433
text=True,
405434
stdout=subprocess.PIPE,
406435
stderr=subprocess.PIPE,
@@ -550,7 +579,9 @@ def _check_prefix_leaks(self) -> str:
550579
leaking.add(candidate)
551580
continue
552581
needles = binary_needles if b"\0" in contents[:8192] else text_needles
553-
found = [label for needle, label in needles.items() if needle in contents]
582+
found = [
583+
label for needle, label in needles.items() if needle in contents
584+
]
554585
if found == ["configured prefix"] and self._is_verbatim_source_copy(
555586
candidate
556587
):
@@ -580,9 +611,8 @@ def _check_build_details(self) -> str:
580611
failures.append(f"{path}: {exc}")
581612
continue
582613
failures.extend(
583-
f"{path}: {problem}" for problem in build_details_problems(
584-
data, path.parent, self.root
585-
)
614+
f"{path}: {problem}"
615+
for problem in build_details_problems(data, path.parent, self.root)
586616
)
587617
if failures:
588618
raise CheckFailed(
@@ -650,6 +680,48 @@ def _check_stdlib(self, module: str) -> str:
650680
self._require_success(completed, f"{module} failed after relocation")
651681
return f"{module} works after relocation"
652682

683+
def _extension_modules(
684+
self, python: pathlib.Path, env: dict[str, str] | None = None
685+
) -> dict[str, dict[str, str]]:
686+
"""Run EXTENSIONS_PROBE with *python* and return its output."""
687+
completed = self._run([python, "-I", "-c", EXTENSIONS_PROBE], env=env)
688+
self._require_success(completed, "the extension module probe failed")
689+
try:
690+
return json.loads(completed.stdout)
691+
except json.JSONDecodeError as exc:
692+
raise CheckFailed(
693+
"the extension module probe did not produce valid JSON",
694+
[completed.stdout.rstrip(), completed.stderr.rstrip()],
695+
) from exc
696+
697+
def _check_extensions(self) -> str:
698+
if self.python is None:
699+
raise CheckSkipped("the relocated interpreter did not start")
700+
before = self._extension_modules(
701+
find_build_interpreter(self.build_dir), build_environment(self.build_dir)
702+
)
703+
after = self._extension_modules(self.python)
704+
working = sorted(name for name, result in before.items() if "file" in result)
705+
failures = []
706+
for name in working:
707+
result = after.get(name)
708+
if result is None:
709+
failures.append(f"{name}: not found after the move")
710+
elif "error" in result:
711+
failures.append(f"{name}: {result['error']}")
712+
elif not path_is_within(result["file"], self.root):
713+
failures.append(f"{name}: loaded from {result['file']}")
714+
if failures:
715+
raise CheckFailed(
716+
f"{len(failures)} of {len(working)} extension module(s) "
717+
"failed after the move",
718+
failures,
719+
)
720+
summary = f"{len(working)} extension modules load from the relocated tree"
721+
if broken := len(before) - len(working):
722+
summary += f" ({broken} already fail in the build directory)"
723+
return summary
724+
653725
def _check_symlink(self) -> str:
654726
if self.snapshot is None:
655727
raise CheckSkipped("the startup probe did not complete")
@@ -818,9 +890,7 @@ def _check_loader_paths(self) -> str:
818890
continue
819891
failures.append(f"{path}: loader metadata references {value}")
820892
if failures:
821-
raise CheckFailed(
822-
"loader metadata contains stale paths", failures[:50]
823-
)
893+
raise CheckFailed("loader metadata contains stale paths", failures[:50])
824894
if not inspected:
825895
raise CheckSkipped("no binaries could be inspected")
826896
interpreter = self.python.resolve() if self.python is not None else None

0 commit comments

Comments
 (0)