diff --git a/CHANGELOG.md b/CHANGELOG.md index 9105322..7e254e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ # Changelog -## Unreleased +## v2.3.0 + +### Added + +- At the end of a build, the python modules relying on external modules are imported and smoke tested in the built python: the build fails if one that the build compiled (or listed in the new `cpython-required-modules` setting) is absent, broken, or reports another library version than the one compiled. Modules relying on libraries found on the build host are reported with a warning. See [module checks](docs/concepts/module-checks.md) +- `inspect` smoke tests modules as well, and marks them in its report: ✅ passed, ❌ failed (module imports, but is broken), ⚠️ reports another library version than the one compiled. For a python built by portable-python, it fails if a module relying on an external module that was compiled (or a required module) is not working, as recorded in its `.manifest.yml` +- `.manifest.yml` records compiled sub-modules (such as `ncurses`, with `readline`) in `static`, and the new `required-modules` ### Changed diff --git a/docs/architecture/cpython.md b/docs/architecture/cpython.md index b0a8610..69f16aa 100644 --- a/docs/architecture/cpython.md +++ b/docs/architecture/cpython.md @@ -26,4 +26,4 @@ After `make install`, a portable build's interpreter still thinks it lives at th - **Trim** — remove tests / idle / 2to3 before byte-compiling, then prune seldom-used pycaches after (driven by the `cpython-clean-*` config). - **Byte-compile** the standard library. - **Relativize** — rewrite `bin/` shebangs and the absolute paths baked into `sysconfig` so everything resolves relative to the install's own location. -- **Verify** — sanity-check that `venv` works in the finished build. +- **Verify** — sanity-check that `venv` works in the finished build, and [check the python modules](/concepts/module-checks.md) relying on external modules. diff --git a/docs/cli/inspect.md b/docs/cli/inspect.md index ce20c80..e1a1728 100644 --- a/docs/cli/inspect.md +++ b/docs/cli/inspect.md @@ -3,7 +3,7 @@ type: CLI Command title: inspect description: Inspect a python installation for non-portable dynamic library usage, reporting any references that would break portability. tags: [cli, inspect, portability, command] -timestamp: 2026-06-23T00:00:00Z +timestamp: 2026-12-03T00:00:00Z --- # inspect @@ -17,6 +17,8 @@ portable-python inspect [OPTIONS] PATH Worth knowing (`--help` for the full flag list): - It **exits non-zero** when it finds a portability problem, so it works as a CI gate. +- Modules are [smoke tested](/concepts/module-checks.md): ✅ passed, ❌ failed, ⚠️ another library version than the one compiled, no marker when there's no smoke test. For a python built by portable-python (with a build-info manifest), modules relying on what the build compiled must work, otherwise `inspect` exits non-zero. +- `--modules/-m` **replaces** the list of modules to inspect (`-m tkinter` shows only `tkinter`, and skips the `.so` check), a leading `+` adds to the default list instead (`-m +tkinter`). - `PATH` can be the special value `invoker` to inspect the python running the CLI itself. - `--prefix` says the build was pinned to a prefix (not portable), relaxing the check; `--verbose/-v` shows the full `.so` report. diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 31c1c9c..87429ed 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -5,6 +5,7 @@ The domain ideas behind portable-python. Read these to understand *why* the buil * [Portability](/concepts/portability.md) - What "portable" means here, and how it is validated. * [Static linking](/concepts/static-linking.md) - Why dependencies are compiled statically and paths relativized. * [Telltale detection](/concepts/telltale-detection.md) - How the tool decides whether a library must be compiled or already exists. +* [Module checks](/concepts/module-checks.md) - How the python modules of a fresh build are checked: strictly for what the build provides, with a warning for the rest. * [Folder masking](/concepts/folder-masking.md) - The macOS `/usr/local` RAM-disk mask that prevents accidental dynamic linking. * [Build layout](/concepts/build-layout.md) - The `build/` and `dist/` folder structure shared by every component. * [ppp-marker prefix](/concepts/ppp-marker.md) - The placeholder install prefix that fills in for `--prefix` and is relativized for portable builds. diff --git a/docs/concepts/module-checks.md b/docs/concepts/module-checks.md new file mode 100644 index 0000000..b812533 --- /dev/null +++ b/docs/concepts/module-checks.md @@ -0,0 +1,39 @@ +--- +type: Concept +title: Module Checks +description: After a build, the python modules relying on external modules are imported and smoke tested in the freshly built python, strictly for what the build was asked to provide, with a warning for the rest. +tags: [concept, validation, modules, finalize] +timestamp: 2026-12-03T00:00:00Z +--- + +# Module Checks + +A C extension that fails to build or link doesn't fail the CPython build: `make` only mentions it in its output (such as "could not be imported"), and the module is silently missing from the result. To catch this, at the end of each build (during [`Cpython`](/architecture/cpython.md) finalization), the python modules relying on [external modules](/modules/index.md) are imported and smoke tested in the freshly built python. + +## What is checked, and how strictly + +Each external module declares which python modules rely on it, via its `m_provides` attribute (for example `openssl` provides `_ssl _hashlib`, `xz` provides `_lzma`). How strictly they're checked depends on how the build provided that external module (its outcome, as shown by [`build-report`](/cli/build-report.md)): + +| Outcome | Meaning | Check | +|---------|---------|-------| +| `static` | Compiled by this build (selected, or auto-selected) | **Strict**: the build fails if the module is absent, broken, or reports a different library version than the one compiled | +| `shared` | Found on the build host ([telltale](/concepts/telltale-detection.md) present) | **Warning** only: a header on the build host doesn't guarantee that CPython's `./configure` can use the library (for example, the macOS SDK has `tk.h`, but `_tkinter` doesn't get built with it) | +| `absent` | Neither | Not checked | + +Sub-modules (such as `ncurses`, under `readline`) share the outcome of their parent. + +Python modules listed in the `cpython-required-modules` [config](/configuration/portable-python-yml.md) setting are checked strictly as well, whatever their outcome. This lets a build state what it can't do without (for example `_uuid` or `readline`), even when provided by the build host. + +## What a check does + +For each checked module, inside the built python: + +- **Import** the module. +- **Smoke test** it, beyond importing: for example a compression round-trip for `zlib` / `_lzma` / `_bz2` / `_zstd`, `ssl.create_default_context()`, an in-memory `sqlite3` query, a `ctypes` callback (exercising libffi), a `dbm` write and read, a Tcl expression for `_tkinter`. Modules without a smoke test (such as `readline`, `_curses`, which need a terminal) are checked via import only. The smoke tests are in `SMOKE_TESTS` in `external/_inspect.py`. +- **Version**, for statically compiled modules that report the version of their C library (such as `_ssl`'s `OPENSSL_VERSION`): it must match the compiled version. A mismatch means the module got linked against another copy of the library (for example one from the build host). + +## With `inspect` + +The [`inspect`](/cli/inspect.md) command runs the same smoke tests on any python installation, and marks each module in its report: ✅ smoke test passed, ❌ failed (module imports, but is broken), ⚠️ reports another library version than the one compiled (with the expected version), no marker when the module has no smoke test (or is absent). + +When the inspected python was built by portable-python, its build-info [manifest](/configuration/portable-python-yml.md) (`.manifest.yml` by default) records what the build compiled (`static`: external modules with their versions, sub-modules included) and what it required (`required-modules`). `inspect` uses it to check the same modules strictly as the build did, and fails if one of them is not working. Other modules are only reported. Manifests written prior to v2.3.0 don't record sub-modules and required modules: modules relying on sub-modules are then checked without version comparison. diff --git a/docs/concepts/portability.md b/docs/concepts/portability.md index 3a847d4..497178c 100644 --- a/docs/concepts/portability.md +++ b/docs/concepts/portability.md @@ -32,4 +32,4 @@ See the [`build`](/cli/build.md) command for how to choose. ## Validation -Portability is not assumed — it is **verified**. The [`PythonInspector`](/architecture/python-inspector.md) walks every executable and `.so` file, parses their dynamic dependencies (`ldd` on Linux, `otool` on macOS), and classifies each reference as a system library, a relative reference, or a problem. The [`inspect`](/cli/inspect.md) command surfaces this report and fails if a non-portable reference is found. +Portability is not assumed — it is **verified**. The [`PythonInspector`](/architecture/python-inspector.md) walks every executable and `.so` file, parses their dynamic dependencies (`ldd` on Linux, `otool` on macOS), and classifies each reference as a system library, a relative reference, or a problem. The [`inspect`](/cli/inspect.md) command surfaces this report and fails if a non-portable reference is found. A build also [checks its python modules](/concepts/module-checks.md). diff --git a/docs/configuration/portable-python-yml.md b/docs/configuration/portable-python-yml.md index f72823f..5605ea7 100644 --- a/docs/configuration/portable-python-yml.md +++ b/docs/configuration/portable-python-yml.md @@ -28,6 +28,7 @@ portable-python is configured via a YAML file — by default `portable-python.ym | `cpython-clean` | list | Extra globs removed in the second cleanup pass, along with `cpython-clean-2nd-pass`. | | `cpython-symlink` | list | Files to ensure exist in the install (default: `bin/python`), symlinked to the matching main file (eg: `bin/python3.14`). | | `cpython-validate-script` | path | Python script run with the freshly built python before packaging, the build fails if it fails. Relative to the config file that sets it. | +| `cpython-required-modules` | CSV/list | Python modules that must import and pass their smoke test, whatever their outcome (see [module checks](/concepts/module-checks.md)). | | `cpython-check-venvs` | string | Check that the built python can create a venv: `venv` (default), `copies` (`--copies` venv), `all` (both), or `""` to skip. | | `cpython-pep668-externally-managed` | map | Mark the install as [externally managed](https://peps.python.org/pep-0668/): its keys are written to `EXTERNALLY-MANAGED` (an `Error` key is required), and `bin/pip*` are removed. | | `allowed-system-libs` | regex | Opt-in: fail a portable build (no `--prefix`, no `--enable-shared`) if its `.so` files link a system library whose path doesn't match. Also used by `inspect` (unless `--prefix`). | @@ -75,7 +76,7 @@ Files written in the install folder (relative paths), set a key to `""` to not w | Key | Default | Content | |-----|---------|---------| -| `build-info` | `.manifest.yml` | How the build was done: cpython version and source, selected modules, `./configure` args, compilation info (date, host, `compiled-by`), and `additional-info`. | +| `build-info` | `.manifest.yml` | How the build was done: cpython version and source, compiled external modules (`static`, with their versions, sub-modules included), `required-modules`, `./configure` args, compilation info (date, host, `compiled-by`), and `additional-info`. Used by [`inspect`](/cli/inspect.md) to check modules strictly. | | `inspection-report` | `.inspection-report.yml` | Report of the built python's modules and `.so` files (same as the `inspect` command). | | `additional-info` | | Map of extra info to record in `build-info`, a value of the form `$NAME` is expanded from env var `NAME`. | diff --git a/docs/guides/add-an-external-module.md b/docs/guides/add-an-external-module.md index ac0aa39..573619c 100644 --- a/docs/guides/add-an-external-module.md +++ b/docs/guides/add-an-external-module.md @@ -42,7 +42,7 @@ To statically link a new C library into CPython, add a [`ModuleBuilder`](/archit self.run_make("install") ``` -2. **Set the declarative attributes**: `m_telltale` (see [telltale detection](/concepts/telltale-detection.md)), `m_debian` with the right sigil, and `m_include`/`m_build_cwd` if needed. +2. **Set the declarative attributes**: `m_telltale` (see [telltale detection](/concepts/telltale-detection.md)), `m_debian` with the right sigil, `m_provides` (the python modules relying on it, see [module checks](/concepts/module-checks.md)), and `m_include`/`m_build_cwd` if needed. If those python modules can be exercised beyond importing them, add a smoke test to `SMOKE_TESTS` in `external/_inspect.py`. 3. **Implement source resolution**: `url` and `version` (using `cfg_url`/`cfg_version` so config overrides work). diff --git a/docs/log.md b/docs/log.md index c18dd28..6555ef7 100644 --- a/docs/log.md +++ b/docs/log.md @@ -2,6 +2,9 @@ ## 2026-12-03 +* **Update**: [Module checks](/concepts/module-checks.md) and [configuration](/configuration/portable-python-yml.md): the build-info manifest records compiled sub-modules and `required-modules`, used by `inspect`. +* **Update**: [Module checks](/concepts/module-checks.md) and [inspect](/cli/inspect.md): smoke test markers in the `inspect` report, strict checks for pythons built by portable-python (via their manifest), `-m` replaces the default module list. +* **Creation**: Added [module checks](/concepts/module-checks.md): python modules of a fresh build are smoke tested, strictly for what the build provides (`m_provides`, `cpython-required-modules`), with a warning for the rest. * **Update**: [Folder masking](/concepts/folder-masking.md): `isolate-usr-local` defaults to `auto` on macOS, which masks `/usr/local` only when Homebrew is installed there, and `none` turns isolation off. * **Update**: [Configuration](/configuration/portable-python-yml.md): documented the remaining config keys (`cpython-clean`, `cpython-symlink`, `cpython-validate-script`, `cpython-check-venvs`, `cpython-pep668-externally-managed`, `allowed-system-libs`, `isolate-usr-local`, `env`, `manifest`, `compiled-by`) and the `-{platform}` suffix of the cleanup globs. * **Update**: [Folder masking](/concepts/folder-masking.md): masking is opt-in via `isolate-usr-local`, and covers `/usr/local/{etc,include,lib,opt}`. diff --git a/src/portable_python/__init__.py b/src/portable_python/__init__.py index 294f406..c66038b 100644 --- a/src/portable_python/__init__.py +++ b/src/portable_python/__init__.py @@ -414,6 +414,7 @@ class ModuleBuilder: m_build_cwd: str | None = None # Optional: relative (to unpacked source) folder where to run configure/make from m_debian: str | None = None # Optional: debian package, prefixed with "!": required, "+": required if selected, "-": prevents static m_include: str | None = None # Optional: subfolder to automatically list in CPATH when this module is active + m_provides: str = "" # Optional: python modules relying on this external module (space separated), checked post-build m_telltale: str = "" # Optional: file(s) that, if present, indicate this module is installed (space separated) setup: BuildSetup diff --git a/src/portable_python/cli.py b/src/portable_python/cli.py index 35c23a6..c7be192 100644 --- a/src/portable_python/cli.py +++ b/src/portable_python/cli.py @@ -6,6 +6,7 @@ from runez.render import PrettyTable from portable_python import BuildSetup, PPG, required_python_spec +from portable_python.cpython import Cpython, ModuleExpectation from portable_python.inspector import LibAutoCorrect, PythonInspector LOG = logging.getLogger(__name__) @@ -78,12 +79,24 @@ def inspect(modules, verbose, prefix, skip_so, path): inspector = PythonInspector(path, modules=modules) runez.abort_if(inspector.python.problem, "%s: %s" % (runez.red(path), inspector.python.problem)) + # For a python built by portable-python: modules relying on external modules it compiled must work (and required ones) + expectations = Cpython.manifest_expectations(inspector.install_folder) + additional = sorted(x for x in expectations if x not in PythonInspector.default.split(",")) + if additional and not modules: + inspector = PythonInspector(path, modules="+%s" % ",".join(additional)) + + ModuleExpectation.annotate(expectations, inspector.module_info) print(runez.blue(inspector.python)) print(inspector.represented(verbose=verbose)) if not skip_so and (not modules or modules == "all"): problem = inspector.full_so_report.get_problem(portable=not prefix) runez.abort_if(problem) + if inspector.module_info: + expectations = {k: v for k, v in expectations.items() if k in inspector.module_info} + failed = ModuleExpectation.failures(expectations, inspector.module_info) + runez.abort_if(failed, "Modules not working as expected:\n %s" % "\n ".join(failed)) + @main.command(name="list") @click.option("--json", is_flag=True, help="Json output") diff --git a/src/portable_python/cpython.py b/src/portable_python/cpython.py index 4d0d00c..a1b09ef 100644 --- a/src/portable_python/cpython.py +++ b/src/portable_python/cpython.py @@ -7,10 +7,10 @@ import runez import yaml -from portable_python import LOG, patch_file, patch_folder, PPG, PythonBuilder +from portable_python import LinkerOutcome, LOG, ModuleBuilder, ModuleCollection, patch_file, patch_folder, PPG, PythonBuilder from portable_python.external.xcpython import Bdb, Bzip2, Gdbm, LibFFI, Mpdec, Openssl, Readline, Sqlite, Uuid, Xz, Zlib, Zstd from portable_python.external.xtkinter import TkInter -from portable_python.inspector import LibAutoCorrect, PythonInspector +from portable_python.inspector import LibAutoCorrect, ModuleInfo, PythonInspector # https://github.com/docker-library/python/issues/160 PGO_TESTS = """ @@ -24,6 +24,111 @@ RX_MAKEFILE_COMPILER = re.compile(r"^(CC|CXX|LDSHARED|LDCXXSHARED)=[ \t]*(.*?)[ \t]*$", flags=re.MULTILINE) # Compiler wrappers that may exist on the build host only, recording them in sysconfig is worth a warning RX_COMPILER_WRAPPER = re.compile(r"\b(ccache|sccache|distcc)\b") +RX_LIBRARY_VERSION = re.compile(r"\d+(\.\d+)+[a-z]?") + + +class ModuleExpectation: + """ + What is expected of a python module in the final build, depending on what the build was asked to provide: + - modules relying on an external module compiled by this build (static), or listed in `cpython-required-modules`, + must import and pass their smoke test (with the version that was compiled, when the module reports it) + - modules relying on a library found on the build host (shared) are reported with a warning if they don't work + """ + + def __init__(self, name: str, provider: str | None = None, outcome: LinkerOutcome | None = None, compiled: str | None = None): + """ + Parameters + ---------- + name : str + Name of python module + provider : str | None + Name of the external module this python module relies on (if any), eg: 'openssl' for '_ssl' + outcome : LinkerOutcome | None + How the build provided that external module + compiled : str | None + Version of the external module that was compiled (if known) + """ + self.name = name + self.provider = provider + self.outcome = outcome + self.compiled = compiled + self.is_required = False # Listed in `cpython-required-modules` + + def __repr__(self): + if self.provider and self.outcome: + return "%s (%s %s)" % (self.name, runez.joined(self.provider, self.compiled, delimiter=":"), self.outcome.name) + + return f"{self.name} (required)" + + @property + def is_strict(self) -> bool: + """Does this module have to work for the build to succeed?""" + return self.is_required or self.outcome is LinkerOutcome.static + + def problem(self, info: ModuleInfo | None) -> str | None: + if info is None or info.is_absent: + return runez.joined("absent", info and info.note and f"({info.note})") + + if info.problem: + return f"broken: {info.problem}" + + if self.is_version_mismatch(info): + return f"reports version '{info.library_version}', instead of compiled {self.compiled}" + + return None + + def is_version_mismatch(self, info: ModuleInfo) -> bool: + """Check whether `info` reports another version of the C library than the one that was compiled""" + if self.compiled and self.outcome is LinkerOutcome.static and info.library_version: + return not self.versions_match(self.compiled, info.library_version) + + return False + + @staticmethod + def annotate(expectations: dict[str, "ModuleExpectation"], module_info: dict[str, ModuleInfo] | None): + """Let reported modules show which version was expected, when another one is reported""" + if not module_info: + return + + for name, expectation in expectations.items(): + info = module_info.get(name) + if info and expectation.is_version_mismatch(info): + info.expected_version = expectation.compiled + + @staticmethod + def require(expectations: dict[str, "ModuleExpectation"], names: list[str]): + """Mark modules with given `names` as required (they must work, regardless of how they're provided)""" + for name in names: + expectation = expectations.get(name) + if expectation is None: + expectation = expectations[name] = ModuleExpectation(name) + + expectation.is_required = True + + @staticmethod + def failures(expectations: dict[str, "ModuleExpectation"], module_info: dict[str, ModuleInfo]) -> list[str]: + """Problems with strictly expected modules, other problems are logged as warnings""" + failed = [] + for name, expectation in sorted(expectations.items()): + problem = expectation.problem(module_info.get(name)) + if problem: + if expectation.is_strict: + failed.append(f"{expectation}: {problem}") + + else: + LOG.warning("Module %s: %s", expectation, problem) + + return failed + + @staticmethod + def versions_match(compiled: str, reported: str) -> bool: + """Modules may report a shorter version than the one compiled (eg: tcl '8.6' for 8.6.18), or a longer one""" + m = RX_LIBRARY_VERSION.search(reported) + if not m: + return True # Nothing to compare + + reported = m.group(0) + return compiled == reported or compiled.startswith(f"{reported}.") or reported.startswith(f"{compiled}.") def represented_yaml(key_value_pairs): @@ -68,7 +173,8 @@ def build_information(self): { "prefix": self.setup.prefix, "source": self.url, - "static": runez.joined(self.modules.selected) or None, + "static": runez.joined(self.compiled_modules) or None, + "required-modules": runez.joined(self.required_modules) or None, "target": PPG.target, "version": self.version, }, @@ -360,10 +466,87 @@ def _finalize(self): PPG.config.cleanup_configured_globs("Pass 2", self, "cpython-clean-2nd-pass", "cpython-clean") self._apply_pep668() - py_inspector = PythonInspector(self.install_folder) + expectations = self.module_expectations() + additional = sorted(x for x in expectations if x not in PythonInspector.default.split(",")) + py_inspector = PythonInspector(self.install_folder, modules=additional and "+%s" % ",".join(additional)) + ModuleExpectation.annotate(expectations, py_inspector.module_info) print(py_inspector.represented()) problem = py_inspector.full_so_report.get_problem(portable=not is_shared) runez.abort_if(problem and self.setup.x_debug != "direct-finalize", "Build failed: %s" % problem) + self.check_modules(py_inspector, expectations) + + @property + def compiled_modules(self) -> list[ModuleBuilder]: + """External modules compiled by this build, sub-modules included (eg: ncurses, for readline)""" + + def compiled(modules): + for module in modules.selected: + yield module + yield from compiled(module.modules) + + return list(compiled(self.modules)) + + @property + def required_modules(self) -> list[str]: + """Python modules that must work in the final build, as configured via `cpython-required-modules`""" + required = runez.flattened(PPG.config.get_value("cpython-required-modules"), split=True) + return runez.flattened(required, split=",", unique=True) + + def module_expectations(self) -> dict[str, ModuleExpectation]: + """Python modules to check in the final build, see `ModuleExpectation`""" + result = {} + for module in self.modules.candidates: + outcome, _ = module.linker_outcome(is_selected=module in self.modules.selected) + if outcome in (LinkerOutcome.static, LinkerOutcome.shared): + for provider in (module, *module.modules.candidates): # Sub-modules share the outcome of their parent + compiled = str(provider.version) if outcome is LinkerOutcome.static else None + for name in provider.m_provides.split(): + result[name] = ModuleExpectation(name, provider.m_name, outcome, compiled) + + ModuleExpectation.require(result, self.required_modules) + return result + + @classmethod + def manifest_expectations(cls, install_folder) -> dict[str, ModuleExpectation]: + """ + Get the expectations for an existing python installation that was built by portable-python, + from the external modules it compiled, as recorded in its build-info manifest (if any) + """ + info_path = PPG.config.get_value("manifest", "build-info") + path = install_folder and info_path and os.path.join(install_folder, info_path) + if not path or not os.path.exists(path): + return {} + + with open(path) as fh: + manifest = yaml.safe_load(fh) or {} + + cpython = manifest.get("cpython") or {} + static = runez.flattened(cpython.get("static"), split=True) + compiled = dict(x.partition(":")[::2] for x in static) # Of the form 'openssl:3.5.10' + result = {} + for module_class in cls.candidate_modules(): + if ModuleCollection.get_module_name(module_class) in compiled: + # Sub-modules are compiled along with their parent (manifests prior to v2.3.0 don't list them) + for provider_class in (module_class, *module_class.candidate_modules()): + provider = ModuleCollection.get_module_name(provider_class) + for name in provider_class.m_provides.split(): + result[name] = ModuleExpectation(name, provider, LinkerOutcome.static, compiled.get(provider) or None) + + ModuleExpectation.require(result, runez.flattened(cpython.get("required-modules"), split=True)) + return result + + def check_modules(self, py_inspector: PythonInspector, expectations: dict[str, ModuleExpectation]): + if self.setup.x_debug == "direct-finalize": + return + + module_info = py_inspector.module_info + if module_info is None: + runez.abort_if(not runez.DRYRUN, f"Can't check modules, inspection failed: {py_inspector.output}") + return + + failed = ModuleExpectation.failures(expectations, module_info) + if failed: + runez.abort("Build failed, modules not working as expected:\n %s" % "\n ".join(failed)) def _apply_pep668(self): """ diff --git a/src/portable_python/external/_inspect.py b/src/portable_python/external/_inspect.py index 563de65..3ccb4e6 100644 --- a/src/portable_python/external/_inspect.py +++ b/src/portable_python/external/_inspect.py @@ -1,11 +1,15 @@ import json import os import re +import shutil import sys import sysconfig +import tempfile RX_VERSION = re.compile(r"\d\.\d") INSIGHTS = { + "_curses": "ncurses_version", + "_decimal": "__libmpdec_version__", "_gdbm": "_GDBM_VERSION", "_tkinter": "TCL_VERSION TK_VERSION", "_sqlite3": "sqlite_version version", @@ -20,6 +24,97 @@ } +SAMPLE_DATA = b"portable-python " * 32 + + +def expect(condition, message): + if not condition: + raise RuntimeError(message) + + +def check_compression(module_name): + def check(pymodule): + mod = __import__(module_name, fromlist=["_"]) + expect(mod.decompress(mod.compress(SAMPLE_DATA)) == SAMPLE_DATA, "round-trip mismatch") + + return check + + +def check_ctypes(pymodule): + import ctypes + + callback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)(lambda x: x + 1) # Exercises libffi closures + expect(callback(41) == 42, "ctypes callback returned a wrong value") + + +def check_dbm(pymodule): + folder = tempfile.mkdtemp() + try: + db = pymodule.open(os.path.join(folder, "db"), "c") + db[b"key"] = b"value" + expect(db[b"key"] == b"value", "wrong value read back") + db.close() + + finally: + shutil.rmtree(folder) + + +def check_decimal(pymodule): + import decimal + + expect(decimal.Decimal("1.1") + decimal.Decimal("2.2") == decimal.Decimal("3.3"), "wrong sum") + + +def check_hashlib(pymodule): + expect(pymodule.new("sha256", SAMPLE_DATA).hexdigest(), "empty sha256 digest") + + +def check_pyexpat(pymodule): + pymodule.ParserCreate().Parse(b"", True) + + +def check_sqlite(pymodule): + import sqlite3 + + expect(sqlite3.connect(":memory:").execute("select 1").fetchone() == (1,), "wrong query result") + + +def check_ssl(pymodule): + import ssl + + ssl.create_default_context() + + +def check_tkinter(pymodule): + import tkinter + + expect(tkinter.Tcl().eval("expr {1 + 1}") == "2", "wrong tcl result") + + +def check_uuid(pymodule): + expect(pymodule.generate_time_safe(), "no uuid generated") + + +# Quick check that a module effectively works (beyond importing it), modules not listed here are checked via import only +SMOKE_TESTS = { + "_bz2": check_compression("bz2"), + "_ctypes": check_ctypes, + "_dbm": check_dbm, + "_decimal": check_decimal, + "_gdbm": check_dbm, + "_hashlib": check_hashlib, + "_lzma": check_compression("lzma"), + "_sqlite3": check_sqlite, + "_ssl": check_ssl, + "_tkinter": check_tkinter, + "_uuid": check_uuid, + "_zstd": check_compression("compression.zstd"), + "pyexpat": check_pyexpat, + "tkinter": check_tkinter, + "zlib": check_compression("zlib"), +} + + def get_version(text): if text: if isinstance(text, bytes): @@ -66,7 +161,8 @@ def pymodule_info(module_name, pymodule): def module_report(module_name): try: - return pymodule_info(module_name, __import__(module_name)) + pymodule = __import__(module_name) + result = pymodule_info(module_name, pymodule) except Exception as e: note = str(e) @@ -75,6 +171,18 @@ def module_report(module_name): return {"version": "*absent*", "note": note} + smoke_test = SMOKE_TESTS.get(module_name) + if smoke_test: + try: + smoke_test(pymodule) + result["smoke"] = "passed" + + except Exception as e: + result["smoke"] = "failed" + result["problem"] = "%s: %s" % (e.__class__.__name__, e) + + return result + def get_srcdir(): srcdir = sysconfig.get_config_var("srcdir") diff --git a/src/portable_python/external/xcpython.py b/src/portable_python/external/xcpython.py index 41941e0..93bfa20 100644 --- a/src/portable_python/external/xcpython.py +++ b/src/portable_python/external/xcpython.py @@ -16,6 +16,7 @@ class Bdb(ModuleBuilder): m_build_cwd = "build_unix" m_debian = "libgdbm-compat-dev" m_telltale = "{include}/dbm.h" + m_provides = "_dbm" xenv_CFLAGS = "-fPIC" @@ -51,6 +52,7 @@ class Bzip2(ModuleBuilder): """ m_telltale = "{include}/bzlib.h" + m_provides = "_bz2" def auto_select_reason(self): if PPG.target.is_macos and self.setup.python_spec.version < "3.8": @@ -81,6 +83,7 @@ class Gdbm(ModuleBuilder): m_debian = "libgdbm-dev" m_telltale = "{include}/gdbm.h" + m_provides = "_gdbm" @property def url(self): @@ -124,6 +127,7 @@ class LibFFI(ModuleBuilder): m_debian = "!libffi-dev" m_telltale = "{include}/ffi.h {include}/ffi/ffi.h" + m_provides = "_ctypes" xenv_CFLAGS = "-fPIC" @@ -164,6 +168,7 @@ class Openssl(ModuleBuilder): m_include = "openssl" m_telltale = "{include}/openssl/ssl.h" + m_provides = "_ssl _hashlib" def auto_select_reason(self): if PPG.target.is_macos: @@ -207,6 +212,7 @@ def _do_linux_compile(self): class Ncurses(ModuleBuilder): m_include = "ncursesw" + m_provides = "_curses" xenv_CFLAGS = "-fPIC" @@ -261,6 +267,7 @@ class Readline(ModuleBuilder): m_debian = "-libreadline-dev" m_include = "readline" m_telltale = "{include}/readline/readline.h" + m_provides = "readline" xenv_CFLAGS = "-fPIC" @@ -306,6 +313,7 @@ class Sqlite(ModuleBuilder): m_debian = "+libsqlite3-dev" m_telltale = "{include}/sqlite3.h" + m_provides = "_sqlite3" xenv_CFLAGS = "-fPIC" @@ -350,6 +358,7 @@ class Uuid(ModuleBuilder): m_debian = "+uuid-dev" m_include = "uuid" m_telltale = "{include}/uuid/uuid.h" + m_provides = "_uuid" xenv_CFLAGS = "-fPIC" @@ -380,6 +389,7 @@ def _do_linux_compile(self): class Xz(ModuleBuilder): m_telltale = "{include}/lzma.h" + m_provides = "_lzma" def auto_select_reason(self): if not self.resolved_telltale: @@ -423,6 +433,7 @@ class Zlib(ModuleBuilder): m_debian = "!zlib1g-dev" m_telltale = "{include}/zlib.h" + m_provides = "zlib" xenv_CFLAGS = "-fPIC" @@ -461,6 +472,7 @@ class Zstd(ModuleBuilder): m_debian = "!libzstd-dev" m_telltale = "{include}/zstd.h" + m_provides = "_zstd" xenv_CFLAGS = "-fPIC" @@ -501,6 +513,7 @@ class Mpdec(ModuleBuilder): m_debian = "!libmpdec-dev" m_telltale = "{include}/mpdecimal.h" + m_provides = "_decimal" xenv_CFLAGS = "-fPIC" diff --git a/src/portable_python/external/xtkinter.py b/src/portable_python/external/xtkinter.py index abe0dd4..e2e57df 100644 --- a/src/portable_python/external/xtkinter.py +++ b/src/portable_python/external/xtkinter.py @@ -109,6 +109,7 @@ class TkInter(ModuleBuilder): m_debian = "-tk-dev" m_telltale = "{include}/tk {include}/tk.h" + m_provides = "_tkinter" @classmethod def candidate_modules(cls): diff --git a/src/portable_python/inspector.py b/src/portable_python/inspector.py index 2b52739..68a1df5 100644 --- a/src/portable_python/inspector.py +++ b/src/portable_python/inspector.py @@ -4,7 +4,7 @@ import os import re from pathlib import Path -from typing import Any +from typing import Any, ClassVar import runez from runez.render import PrettyTable @@ -138,6 +138,7 @@ def _shared_ref_top_level(relative_path): class ModuleInfo: _regex = re.compile(r"^(.*?)\s*(\S+/(lib(64)?/.*))$") + SMOKE_MARKERS: ClassVar[dict[str | None, str]] = {"passed": "✅", "failed": "❌"} # Blank (2 chars wide) without smoke test def __init__(self, inspector: "PythonInspector", name: str, payload: dict[str, Any]): self.inspector = inspector @@ -146,12 +147,27 @@ def __init__(self, inspector: "PythonInspector", name: str, payload: dict[str, A path = payload.get("path") self.filepath = runez.to_path(path) if path else None self.note = payload.get("note") + self.problem = payload.get("problem") # Module imports, but its smoke test failed + self.smoke = payload.get("smoke") # Outcome of smoke test: 'passed', 'failed', or None if there is no smoke test + self.expected_version: str | None = None # Compiled version of the C library, when another one is reported self.version = payload.get("version") self.version_field = payload.get("version_field") def __repr__(self): return runez.short(self.filepath) + @property + def is_absent(self) -> bool: + return self.version == "*absent*" + + @property + def library_version(self) -> str | None: + """Version of the C library this module was built with (not the version of the python module itself), if reported""" + if self.version_field not in (None, "__version__", "version", "VERSION"): + return self.version + + return None + @runez.cached_property def additional_info(self) -> "SoInfo | str | None": path = self.filepath @@ -183,10 +199,18 @@ def report_rows(self): if isinstance(info, SoInfo): info = info.represented() - else: + elif info: info = runez.short(info) - yield self.name, runez.joined(version, info) + if self.problem: + info = runez.joined(runez.red("broken: %s" % self.problem), info) + + marker = self.SMOKE_MARKERS.get(self.smoke, " ") + if self.expected_version: + marker = "⚠️" + info = runez.joined(info, runez.orange(f"Expected {self.expected_version}")) + + yield self.name, runez.joined(marker, version, info) class CLibInfo(Trackable): @@ -383,7 +407,9 @@ def get_lib_type(install_folder, path, basename) -> LibType: class PythonInspector: - default = "_bz2,_ctypes,_curses,_decimal,_dbm,_gdbm,_lzma,_tkinter,_sqlite3,_ssl,_uuid,_zstd,pip,readline,pyexpat,setuptools,zlib" + default = ( + "_bz2,_ctypes,_curses,_decimal,_dbm,_gdbm,_hashlib,_lzma,_tkinter,_sqlite3,_ssl,_uuid,_zstd,pip,readline,pyexpat,setuptools,zlib" + ) additional = "_asyncio,_functools,_tracemalloc,dbm.gnu,ensurepip,ossaudiodev,spwd,sys,tkinter,venv,wheel" def __init__(self, spec, modules=None): diff --git a/tests/test_module_checks.py b/tests/test_module_checks.py new file mode 100644 index 0000000..cb79d13 --- /dev/null +++ b/tests/test_module_checks.py @@ -0,0 +1,189 @@ +from typing import cast +from unittest.mock import Mock, patch + +import pytest +import runez + +from portable_python import BuildSetup, LinkerOutcome, required_python_spec +from portable_python.cpython import Cpython, ModuleExpectation +from portable_python.external import _inspect +from portable_python.inspector import ModuleInfo, PythonInspector +from portable_python.versions import PPG + + +def module_info(name, **payload): + return ModuleInfo(Mock(spec=PythonInspector), name, payload) + + +def python_builder(modules=None) -> Cpython: + python_builder = BuildSetup(required_python_spec("3.14.6"), modules=modules).python_builder + assert isinstance(python_builder, Cpython) + return python_builder + + +def test_versions_match(): + assert ModuleExpectation.versions_match("3.5.10", "OpenSSL 3.5.10 1 Dec 2026") + assert ModuleExpectation.versions_match("1.1.1w", "OpenSSL 1.1.1w 11 Sep 2023") + assert ModuleExpectation.versions_match("8.6.18", "8.6") # tcl reports major.minor only + assert ModuleExpectation.versions_match("1.26", "1.26.0") # gdbm reports a tuple + assert ModuleExpectation.versions_match("6.6", "6.6.20251230") # ncurses patch level is a date + assert ModuleExpectation.versions_match("1.0", "no version here") # Nothing to compare + assert not ModuleExpectation.versions_match("3.5.10", "OpenSSL 3.5.1 1 Jul 2025") + assert not ModuleExpectation.versions_match("1.4", "1.2.12") + + +def test_expectations(temp_folder): + # macos: outcome of selected modules does not depend on what is installed on the host running the tests + runez.write("pp.yml", "cpython-required-modules: _uuid, pyexpat", logger=None) + PPG.grab_config("pp.yml", target="macos-arm64") + expectations = python_builder("readline").module_expectations() + + ssl = expectations["_ssl"] + assert ssl.is_strict + assert str(ssl) == "_ssl (openssl:3.5.10 static)" + assert expectations["_hashlib"].is_strict + assert str(expectations["_curses"]) == "_curses (ncurses:6.6 static)" # Sub-module shares the outcome of its parent + assert expectations["_zstd"].is_strict # Auto-selected for 3.14+ (as is mpdec) + assert expectations["_decimal"].is_strict + assert expectations["_ssl"].is_strict # Auto-selected on macos + + # Explicitly required modules must work, regardless of how they're provided + assert expectations["_uuid"].is_strict + assert str(expectations["pyexpat"]) == "pyexpat (required)" + + assert ssl.problem(None) == "absent" + assert ssl.problem(module_info("_ssl", version="*absent*", note="libssl.so: not found")) == "absent (libssl.so: not found)" + assert ssl.problem(module_info("_ssl", version="OpenSSL 3.5.10 1 Dec 2026", version_field="OPENSSL_VERSION")) is None + info = module_info("_ssl", version="OpenSSL 3.0.2 15 Mar 2022", version_field="OPENSSL_VERSION") + assert ssl.problem(info) == "reports version 'OpenSSL 3.0.2 15 Mar 2022', instead of compiled 3.5.10" + info = module_info("_ssl", version="OpenSSL 3.5.10 1 Dec 2026", version_field="OPENSSL_VERSION", problem="SSLError: oops") + assert ssl.problem(info) == "broken: SSLError: oops" + + # Generic version fields are not the version of the underlying C library + assert expectations["_hashlib"].problem(module_info("_hashlib", version="1.0", version_field="__version__")) is None + + +def test_check_modules(temp_folder, logged): + PPG.grab_config(target="macos-arm64") + builder = python_builder("xz") + lzma = ModuleExpectation("_lzma", "xz", LinkerOutcome.static, "5.8.5") + shared = ModuleExpectation("_tkinter", "tkinter", LinkerOutcome.shared) + expectations = {"_lzma": lzma, "_tkinter": shared} + inspector = Mock(spec=PythonInspector) + inspector.module_info = {"_lzma": module_info("_lzma", path="_lzma.so"), "_tkinter": module_info("_tkinter", version="*absent*")} + builder.check_modules(cast("PythonInspector", inspector), expectations) + assert "Module _tkinter (tkinter shared): absent" in logged.pop() # Not strict: warning only + + inspector.module_info["_lzma"] = module_info("_lzma", path="_lzma.so", problem="LZMAError: oops") + with pytest.raises(runez.system.AbortException): + builder.check_modules(cast("PythonInspector", inspector), expectations) + + assert "Build failed, modules not working as expected:\n _lzma (xz:5.8.5 static): broken: LZMAError: oops" in logged.pop() + + inspector.module_info = None # Inspection failed (outside of dryrun mode) + inspector.output = "exit code: 1" + with pytest.raises(runez.system.AbortException): + builder.check_modules(cast("PythonInspector", inspector), expectations) + + assert "Can't check modules, inspection failed: exit code: 1" in logged.pop() + + +def test_smoke_tests(): + for name in _inspect.SMOKE_TESTS: + report = _inspect.module_report(name) + if report.get("version") != "*absent*": # Not all modules are available in the python running the tests + assert "problem" not in report, name + + def broken(_): + _inspect.expect(False, "oops") + + with patch.dict(_inspect.SMOKE_TESTS, {"zlib": broken}): + assert _inspect.module_report("zlib")["problem"] == "RuntimeError: oops" + + +SAMPLE_MANIFEST = """ +cpython: + required-modules: _uuid _json + static: openssl:3.5.10 readline:8.3 ncurses:6.6 + version: 3.14.6 +""" + +# Manifests prior to v2.3.0 don't list sub-modules, nor required modules +SAMPLE_OLD_MANIFEST = """ +cpython: + static: readline:8.3 + version: 3.14.6 +""" + + +def test_manifest_expectations(temp_folder): + PPG.grab_config(target="macos-arm64") + assert Cpython.manifest_expectations(None) == {} + assert Cpython.manifest_expectations(".") == {} # No manifest: not built by portable-python + + runez.write(".manifest.yml", SAMPLE_MANIFEST, logger=None) + expectations = Cpython.manifest_expectations(".") + assert sorted(str(x) for x in expectations.values()) == [ + "_curses (ncurses:6.6 static)", + "_hashlib (openssl:3.5.10 static)", + "_json (required)", + "_ssl (openssl:3.5.10 static)", + "_uuid (required)", + "readline (readline:8.3 static)", + ] + + runez.write(".manifest.yml", SAMPLE_OLD_MANIFEST, logger=None) + expectations = Cpython.manifest_expectations(".") + assert sorted(str(x) for x in expectations.values()) == ["_curses (ncurses static)", "readline (readline:8.3 static)"] + + +def test_build_information(temp_folder): + runez.write("pp.yml", "cpython-required-modules: _uuid,pyexpat _uuid", logger=None) + PPG.grab_config("pp.yml", target="macos-arm64") + builder = python_builder("readline") + assert builder.required_modules == ["_uuid", "pyexpat"] + info = dict(builder.build_information())["cpython"] + assert isinstance(info, dict) + static = str(info["static"]).split() + assert static[:2] == ["readline:8.3", "ncurses:6.6"] # Sub-modules included, right after their parent + assert {"openssl:3.5.10", "zstd:1.6.0", "mpdec:4.0.1"} <= set(static) # Auto-selected (more depending on host) + assert info["required-modules"] == "_uuid pyexpat" + + +def test_inspect_strict(cli): + with patch("portable_python.cpython.Cpython.manifest_expectations") as manifest_expectations: + manifest_expectations.return_value = {"zlib": ModuleExpectation("zlib", "zlib", LinkerOutcome.static, "0.1")} + cli.run("inspect", "invoker", "-mzlib") + assert cli.failed + assert "Modules not working as expected:\n zlib (zlib:0.1 static): reports version" in cli.logged + + manifest_expectations.return_value = {"zlib": ModuleExpectation("zlib", "zlib", LinkerOutcome.static)} + cli.run("inspect", "invoker", "-mzlib") + assert cli.succeeded + assert "✅" in cli.logged + + # Required modules not inspected by default get inspected too + manifest_expectations.return_value = {"_json": ModuleExpectation("_json"), "zlib": ModuleExpectation("zlib")} + manifest_expectations.return_value["_json"].is_required = True + cli.run("inspect", "invoker", "-s") + assert cli.succeeded + assert " _json " in cli.logged + + +def test_smoke_markers(): + assert list(module_info("zlib", version="1.3", smoke="passed").report_rows()) == [("zlib", "✅ 1.3")] + rows = list(module_info("zlib", version="1.3", smoke="failed", problem="oops").report_rows()) + assert rows == [("zlib", "❌ 1.3 broken: oops")] + assert list(module_info("pip", version="26.0").report_rows()) == [("pip", " 26.0")] # No smoke test + + +def test_version_mismatch_marker(): + info = module_info("_zstd", version="1.6.0", version_field="zstd_version", smoke="passed") + expectations = {"_zstd": ModuleExpectation("_zstd", "zstd", LinkerOutcome.static, "1.6.1")} + ModuleExpectation.annotate(expectations, {"_zstd": info}) + assert list(info.report_rows()) == [("_zstd", "⚠️ 1.6.0 Expected 1.6.1")] + + ModuleExpectation.annotate(expectations, None) # No-op when inspection failed (or in dryrun mode) + info = module_info("_zstd", version="1.6.1", version_field="zstd_version", smoke="passed") + ModuleExpectation.annotate(expectations, {"_zstd": info}) + assert list(info.report_rows()) == [("_zstd", "✅ 1.6.1")]