Skip to content

Commit b54fbff

Browse files
committed
ubuntu: byte-compile Python with fixed flags and a stable source path
precompile_python inherited the build interpreter's -O level and PYTHONPYCACHEPREFIX, so the produced .pyc files could carry the wrong optimization tag or land outside the library tree. It also recorded the temporary build directory as the source path. Compile with optimize=0, no cache prefix and ddir=/usr/lib/<name>, and add tests that run the step in a subprocess with -O and with a cache prefix.
1 parent c21f2a9 commit b54fbff

2 files changed

Lines changed: 145 additions & 18 deletions

File tree

‎scripts/nvx_tools/ubuntu.py‎

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -776,34 +776,50 @@ def _validate_ubuntu_identity(root: Path) -> None:
776776

777777

778778
def precompile_python(root: Path) -> None:
779-
"""Byte-compiles the guest's Python standard library.
780-
781-
Maintainer scripts do not run, so the packages' own byte-compilation never
782-
happens. Sandboxed workloads run unprivileged on a root they cannot write
783-
to, so without these files every interpreter start recompiles the modules it
784-
imports. Unchecked-hash files carry no timestamp, so the output is
785-
deterministic. Bytecode is only valid for the interpreter's exact minor
786-
version, so this runs only on a matching build interpreter.
779+
"""Byte-compiles the Python standard library of the root, if it has one.
780+
781+
The build never runs maintainer scripts, so the packages' own byte-compilation
782+
does not happen. Workloads run unprivileged on a root they cannot write to,
783+
so without these files every interpreter start recompiles the modules it
784+
imports. Unchecked-hash files carry no timestamp and the recorded source
785+
path is the path inside the guest rather than the build directory, which
786+
keeps the output deterministic. Bytecode only fits the exact minor version
787+
of the interpreter that wrote it, so the build interpreter must match.
787788
"""
788789
libraries = sorted(
789790
path
790791
for path in (root / "usr" / "lib").glob("python3.[0-9]*")
791792
if path.is_dir() and not path.is_symlink()
792793
)
793794
for library in libraries:
794-
minor = tuple(int(part) for part in library.name.removeprefix("python").split("."))
795-
if sys.version_info[:2] != minor or sys.version_info.releaselevel != "final":
795+
major, minor = (int(part) for part in library.name[len("python") :].split("."))
796+
if (
797+
sys.version_info[:2] != (major, minor)
798+
or sys.version_info.releaselevel != "final"
799+
):
796800
raise ScriptError(
797801
f"byte-compiling {library.name} needs a final-release Python "
798-
f"{minor[0]}.{minor[1]} build interpreter; this is {sys.version.split()[0]}"
802+
f"{major}.{minor} build interpreter; this is {sys.version.split()[0]}"
799803
)
800-
if not compileall.compile_dir(
801-
str(library),
802-
quiet=1,
803-
force=True,
804-
workers=1,
805-
invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH,
806-
):
804+
# compileall follows the build interpreter's settings unless told
805+
# otherwise: -O would write only *.opt-1.pyc files, which the guest's
806+
# interpreter does not read, and a cache prefix would send the bytecode
807+
# to a host directory instead of the root.
808+
cache_prefix = sys.pycache_prefix
809+
sys.pycache_prefix = None
810+
try:
811+
compiled = compileall.compile_dir(
812+
str(library),
813+
ddir=f"/usr/lib/{library.name}",
814+
quiet=1,
815+
force=True,
816+
workers=1,
817+
optimize=0,
818+
invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH,
819+
)
820+
finally:
821+
sys.pycache_prefix = cache_prefix
822+
if not compiled:
807823
raise ScriptError(f"failed to byte-compile {library.name}")
808824
for path in (*library.rglob("__pycache__"), *library.rglob("*.pyc")):
809825
path.chmod(0o755 if path.is_dir() else 0o644)

‎scripts/test_nvx_tools.py‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16014,6 +16014,117 @@ def test_ubuntu_rootfs_digest_and_erofs_uuid_are_deterministic(self):
1601416014
ubuntu.erofs_uuid(second_digest),
1601516015
)
1601616016

16017+
@staticmethod
16018+
def _python_tree(root: Path, library_name: str) -> Path:
16019+
library = root / "usr" / "lib" / library_name
16020+
(library / "package").mkdir(parents=True)
16021+
(library / "os.py").write_text("PATH = 'os'\n", encoding="utf-8")
16022+
(library / "package" / "__init__.py").write_text(
16023+
"def value():\n return 1\n", encoding="utf-8"
16024+
)
16025+
return library
16026+
16027+
def test_python_precompile_is_deterministic_unchecked_hash_bytecode(self):
16028+
if sys.version_info.releaselevel != "final":
16029+
self.skipTest("byte-compiling needs a final-release interpreter")
16030+
name = f"python{sys.version_info.major}.{sys.version_info.minor}"
16031+
runs: list[dict[str, bytes]] = []
16032+
roots: list[str] = []
16033+
for _ in range(2):
16034+
with tempfile.TemporaryDirectory() as temporary:
16035+
root = Path(temporary)
16036+
roots.append(str(root))
16037+
library = self._python_tree(root, name)
16038+
ubuntu.precompile_python(root)
16039+
runs.append(
16040+
{
16041+
path.relative_to(library).as_posix(): path.read_bytes()
16042+
for path in sorted(library.rglob("*.pyc"))
16043+
}
16044+
)
16045+
self.assertEqual(len(runs[0]), 2)
16046+
self.assertEqual(runs[0], runs[1])
16047+
for relative, data in runs[0].items():
16048+
with self.subTest(relative=relative):
16049+
# Bytes 4..8 are the flags: 0b01 is a hash-based file that is
16050+
# not checked against its source.
16051+
self.assertEqual(int.from_bytes(data[4:8], "little"), 0b01)
16052+
# The recorded source path is the one inside the guest, never the
16053+
# build directory.
16054+
os_module = runs[0][f"__pycache__/os.{sys.implementation.cache_tag}.pyc"]
16055+
guest_path = os.path.join(f"/usr/lib/{name}", "os.py")
16056+
self.assertIn(guest_path.encode(), os_module)
16057+
for run, root in zip(runs, roots, strict=True):
16058+
for data in run.values():
16059+
self.assertNotIn(root.encode(), data)
16060+
16061+
def _precompile_in_subprocess(
16062+
self, root: Path, *interpreter_flags: str, env: Mapping[str, str] | None = None
16063+
) -> None:
16064+
code = (
16065+
"import sys; from pathlib import Path; "
16066+
"from nvx_tools import ubuntu; "
16067+
"ubuntu.precompile_python(Path(sys.argv[1]))"
16068+
)
16069+
scripts = Path(__file__).resolve().parent
16070+
environment = {**os.environ, "PYTHONPATH": str(scripts), **(env or {})}
16071+
subprocess.run(
16072+
[sys.executable, *interpreter_flags, "-c", code, str(root)],
16073+
check=True,
16074+
env=environment,
16075+
)
16076+
16077+
def test_python_precompile_ignores_the_build_optimization_level(self):
16078+
if sys.version_info.releaselevel != "final":
16079+
self.skipTest("byte-compiling needs a final-release interpreter")
16080+
name = f"python{sys.version_info.major}.{sys.version_info.minor}"
16081+
with tempfile.TemporaryDirectory() as temporary:
16082+
root = Path(temporary)
16083+
library = self._python_tree(root, name)
16084+
self._precompile_in_subprocess(root, "-O")
16085+
names = sorted(path.name for path in library.rglob("*.pyc"))
16086+
tag = sys.implementation.cache_tag
16087+
self.assertEqual(names, [f"__init__.{tag}.pyc", f"os.{tag}.pyc"])
16088+
16089+
def test_python_precompile_ignores_the_build_cache_prefix(self):
16090+
if sys.version_info.releaselevel != "final":
16091+
self.skipTest("byte-compiling needs a final-release interpreter")
16092+
name = f"python{sys.version_info.major}.{sys.version_info.minor}"
16093+
with tempfile.TemporaryDirectory() as temporary:
16094+
root = Path(temporary) / "root"
16095+
prefix = Path(temporary) / "host-cache"
16096+
library = self._python_tree(root, name)
16097+
self._precompile_in_subprocess(
16098+
root, env={"PYTHONPYCACHEPREFIX": str(prefix)}
16099+
)
16100+
self.assertEqual(len(list(library.rglob("*.pyc"))), 2)
16101+
# The interpreter that runs this build imports its own modules
16102+
# under the prefix; only the root's modules, which the prefix
16103+
# mirrors under the root's own path, must stay out of it.
16104+
leaked = [
16105+
p
16106+
for p in prefix.rglob("*.pyc")
16107+
if Path(temporary).name in p.relative_to(prefix).parts
16108+
]
16109+
self.assertEqual(leaked, [])
16110+
16111+
def test_python_precompile_needs_the_matching_interpreter(self):
16112+
with tempfile.TemporaryDirectory() as temporary:
16113+
root = Path(temporary)
16114+
self._python_tree(root, f"python3.{sys.version_info.minor + 1}")
16115+
with self.assertRaisesRegex(
16116+
common.ScriptError, "needs a final-release Python"
16117+
):
16118+
ubuntu.precompile_python(root)
16119+
16120+
def test_python_precompile_ignores_a_root_without_python(self):
16121+
with tempfile.TemporaryDirectory() as temporary:
16122+
root = Path(temporary)
16123+
ubuntu.precompile_python(root)
16124+
(root / "usr" / "lib").mkdir(parents=True)
16125+
ubuntu.precompile_python(root)
16126+
self.assertEqual(sorted(root.rglob("*.pyc")), [])
16127+
1601716128
def test_ubuntu_prepare_root_normalizes_root_directory_mode(self):
1601816129
with tempfile.TemporaryDirectory() as temporary:
1601916130
temporary_root = Path(temporary)

0 commit comments

Comments
 (0)