package_terminal: the import probe writes no bytecode into the bundle

The probe that imports the runtime packages with the bundled interpreter ran with
the caller's environment, so unless the caller had set PYTHONDONTWRITEBYTECODE a
__pycache__ folder appeared beside every module it loaded and went into the archive:
the archive's file set depended on who built it. The probe now runs through
run_probe(), which sets PYTHONDONTWRITEBYTECODE=1 for the child and starts it with -B.

Tests: the probe leaves no __pycache__ or .pyc in the folder it runs in, with the
variable unset or set to empty by the caller; a plain import in the same setup does
leave one, so the check can see it. With the fix taken out, the two probe tests fail.
This commit is contained in:
Niko1221 committed 2026-11-12 09:43:13 +01:00
1 parent 46b3013f96
commit ab38d9298a
2 files changed
+59 -4

No files matched your search

+14 -4
View File
@@ -141,6 +141,19 @@ INSTALLER_METAL_TOOLS = ("metal_repack", "stream_experts")
PROBE = "import jinja2, yaml, regex, psutil, requests, numpy, PIL, tqdm; print('deps ok')"
def run_probe(py: Path, root: Path, code: str = PROBE) -> "subprocess.CompletedProcess[str]":
"""Run the import probe with the bundled interpreter, from the bundle folder, without leaving anything in it.
The probe imports the runtime packages, which would write a __pycache__ folder next to every module it loads; those compiled files
would then be in the archive whenever the caller had not set PYTHONDONTWRITEBYTECODE itself, so the archive's file set depended on who
built it. The probe turns bytecode writing off for itself (the variable and -B).
"""
env = {**os.environ, "PYTHONNOUSERSITE": "1", "PYTHONDONTWRITEBYTECODE": "1"}
for k in ("PYTHONHOME", "PYTHONPATH"):
env.pop(k, None)
return subprocess.run([str(py), "-B", "-c", code], capture_output=True, text=True, cwd=str(root), env=env)
def host_target() -> str:
machine = platform.machine().lower()
if sys.platform == "win32" and machine in ("amd64", "x86_64"):
@@ -444,10 +457,7 @@ def main() -> int:
for cache_dir in list(root.rglob("__pycache__")):
shutil.rmtree(cache_dir, ignore_errors=True)
env = {**os.environ, "PYTHONNOUSERSITE": "1"}
for k in ("PYTHONHOME", "PYTHONPATH"):
env.pop(k, None)
probe = subprocess.run([str(py), "-c", PROBE], capture_output=True, text=True, cwd=str(root), env=env)
probe = run_probe(py, root)
print(" " + (probe.stdout.strip() or probe.stderr.strip()[:200]))
if not args.skip_deps and probe.returncode != 0:
raise SystemExit("the bundled interpreter cannot import the runtime packages")
+45
View File
@@ -114,5 +114,50 @@ class BundleImports(unittest.TestCase):
self.assertIn("calibrate", pt.setup_tool_imports(ROOT)) # and the scan finds it anyway
class ProbeLeavesNoBytecode(unittest.TestCase):
"""The import probe of package_terminal.py must not write compiled files into the bundle, whoever runs the build."""
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="strata-probe-")
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / "bundle"
self.root.mkdir()
(self.root / "probe_mod.py").write_text("VALUE = 7\n", encoding="utf-8")
self.code = "import probe_mod; print('probe ok', probe_mod.VALUE)"
self.saved = {k: os.environ.pop(k, None) for k in ("PYTHONDONTWRITEBYTECODE", "PYTHONPYCACHEPREFIX")}
self.addCleanup(self.restore)
def restore(self):
for key, value in self.saved.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def leftovers(self, folder: Path):
return sorted(str(p.relative_to(folder)) for p in list(folder.rglob("__pycache__")) + list(folder.rglob("*.pyc")))
def test_the_check_itself_can_see_bytecode(self):
# without the protection the same import does leave a compiled file, so the test below proves something
plain = Path(self.temp.name) / "plain"
plain.mkdir()
(plain / "probe_mod.py").write_text("VALUE = 7\n", encoding="utf-8")
done = subprocess.run([sys.executable, "-c", self.code], cwd=str(plain), capture_output=True, text=True, timeout=60)
self.assertEqual(done.returncode, 0, done.stderr)
self.assertTrue(self.leftovers(plain))
def test_the_probe_writes_no_bytecode_when_the_caller_did_not_ask_for_that(self):
done = pt.run_probe(Path(sys.executable), self.root, code=self.code)
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("probe ok 7", done.stdout)
self.assertEqual(self.leftovers(self.root), [])
def test_the_probe_writes_no_bytecode_when_the_caller_asked_for_it(self):
os.environ["PYTHONDONTWRITEBYTECODE"] = "" # an empty value means "write"
done = pt.run_probe(Path(sys.executable), self.root, code=self.code)
self.assertEqual(done.returncode, 0, done.stderr)
self.assertEqual(self.leftovers(self.root), [])
if __name__ == "__main__":
unittest.main()