From 2b4e589ab6f40389a22466e37cf1a0b74d1cbd01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:33:33 -0500 Subject: [PATCH 01/23] BUG: Stop the Linux module build when the cache download fails The Linux module script ignored the exit status of the cache download: when the ITKPythonBuilds tarball was missing, dockcross-manylinux- download-cache.sh exited 1, and the script went on to run ITKPythonPackage/scripts/dockcross-manylinux-build-module-wheels.sh, which the missing tarball should have provided. The job then failed with exit 127, "No such file or directory", instead of the download error. Fetching the download script with plain curl -L likewise kept an HTTP error page as the script. Exit when either the download script cannot be fetched (curl -f) or it fails. --- ...kcross-manylinux-download-cache-and-build-module-wheels.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh b/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh index 79c28441..8a33c1bd 100755 --- a/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh +++ b/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh @@ -116,7 +116,7 @@ ITKPYTHONPACKAGE_TAG=${ITKPYTHONPACKAGE_TAG:-main} # Download and extract cache echo "Fetching https://raw.githubusercontent.com/${ITKPYTHONPACKAGE_ORG}/ITKPythonPackage/${ITKPYTHONPACKAGE_TAG}/scripts/dockcross-manylinux-download-cache.sh" -curl -L "https://raw.githubusercontent.com/${ITKPYTHONPACKAGE_ORG}/ITKPythonPackage/${ITKPYTHONPACKAGE_TAG}/scripts/dockcross-manylinux-download-cache.sh" -O +curl -fL "https://raw.githubusercontent.com/${ITKPYTHONPACKAGE_ORG}/ITKPythonPackage/${ITKPYTHONPACKAGE_TAG}/scripts/dockcross-manylinux-download-cache.sh" -O || exit 1 chmod u+x dockcross-manylinux-download-cache.sh _download_cmd="ITK_GIT_TAG=${ITK_GIT_TAG} \ ITK_PACKAGE_VERSION=${ITK_PACKAGE_VERSION} \ @@ -127,7 +127,7 @@ _download_cmd="ITK_GIT_TAG=${ITK_GIT_TAG} \ bash -x \ ${download_script_dir}/dockcross-manylinux-download-cache.sh $1" echo "Running: ${_download_cmd}" -eval "${_download_cmd}" +eval "${_download_cmd}" || exit 1 #NOTE: in this scenario, untarred_ipp_dir is extracted from tarball # during ${download_script_dir}/dockcross-manylinux-download-cache.sh From 1dee1390a2882377f49dc85a2ca10c0d5570c3e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:33:51 -0500 Subject: [PATCH 02/23] BUG: Reject manylinux versions other than _2_28 in the Linux module build Workflows that still list 2014-x64 in manylinux-platforms, such as ITKANTsWasm and ITKGenericLabelInterpolator, ran the Linux module script with MANYLINUX_VERSION=2014. It tried to download ITKPythonBuilds-manylinux2014-x64.tar.zst, which is no longer built, and then a container image and a pixi environment that do not exist. Say that only manylinux_2_28 is built, before downloading anything. --- ...cross-manylinux-download-cache-and-build-module-wheels.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh b/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh index 8a33c1bd..56d63bbd 100755 --- a/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh +++ b/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh @@ -108,6 +108,11 @@ ITK_GIT_TAG=${ITK_GIT_TAG:=${ITK_PACKAGE_VERSION}} # Set default values MANYLINUX_VERSION=${MANYLINUX_VERSION:-_2_28} TARGET_ARCH=${TARGET_ARCH:-x64} +# ITKPythonBuilds has caches for manylinux_2_28 only; manylinux2014 is no longer built. +if [ "${MANYLINUX_VERSION}" != "_2_28" ]; then + echo "ERROR: MANYLINUX_VERSION=${MANYLINUX_VERSION} is not built; module wheels are manylinux_2_28 only." + exit 1 +fi ITKPYTHONPACKAGE_ORG=${ITKPYTHONPACKAGE_ORG:-InsightSoftwareConsortium} ITKPYTHONPACKAGE_TAG=${ITKPYTHONPACKAGE_TAG:-main} From f7308ef58e10723c5346293234ed3c6f88cc527d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:34:37 -0500 Subject: [PATCH 03/23] BUG: Repair Windows module wheels with --lib-paths and oneTBB fixup_module_wheel called fixup_wheel without library paths, so a remote module's wheel was repaired with delvewheel --add-path "": the --lib-paths directories given to build_wheels.py (for instance -setup_options "--lib-paths C:\CUDA\bin", as windows-download-cache-and-build-module-wheels.ps1 documents) and oneTBB-prefix\bin were searched only for itk-core. A module that needs a DLL from one of them failed to repair, or bundled whatever copy was on PATH. The previous windows_build_module_wheels.py added both. Search the same directories for module wheels as for itk-core. --- scripts/windows_build_python_instance.py | 11 ++++++++--- tests/test_platform_builders.py | 3 ++- tests/test_windows_wheel_builder.py | 11 +++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/scripts/windows_build_python_instance.py b/scripts/windows_build_python_instance.py index 8bebf34f..a04a7101 100644 --- a/scripts/windows_build_python_instance.py +++ b/scripts/windows_build_python_instance.py @@ -81,6 +81,10 @@ def python_build_generator_args(self) -> list[str]: def post_build_fixup(self) -> None: """Repair wheels with ``delvewheel``, including oneTBB library paths.""" + self.fixup_wheels(self._delvewheel_lib_paths()) + + def _delvewheel_lib_paths(self) -> str: + """Return the ``--lib-paths`` directories and oneTBB's, semicolon-delimited.""" # append the oneTBB-prefix\\bin directory for fixing wheels built with local oneTBB search_lib_paths = ( [ @@ -92,8 +96,7 @@ def post_build_fixup(self) -> None: else [] ) search_lib_paths.append(str(self._tbb_prefix / "bin")) - search_lib_paths_str: str = ";".join(map(str, search_lib_paths)) - self.fixup_wheels(search_lib_paths_str) + return ";".join(map(str, search_lib_paths)) def fixup_wheels(self, lib_paths: str = "") -> None: """Repair the ``itk_core`` wheels, which link oneTBB.""" @@ -104,7 +107,9 @@ def fixup_wheels(self, lib_paths: str = "") -> None: def fixup_module_wheel(self, filepath: str) -> None: """Repair a remote module's wheel into the module's ``dist/``.""" - self.fixup_wheel(filepath, remote_module_wheel=True) + self.fixup_wheel( + filepath, self._delvewheel_lib_paths(), remote_module_wheel=True + ) def fixup_wheel( self, filepath: str, lib_paths: str = "", remote_module_wheel: bool = False diff --git a/tests/test_platform_builders.py b/tests/test_platform_builders.py index 9c94c52f..d7677888 100644 --- a/tests/test_platform_builders.py +++ b/tests/test_platform_builders.py @@ -757,7 +757,8 @@ def test_module_wheels_are_repaired_into_the_module_dist( for builder in (linux_builder, windows_builder): with patch.object(builder, "fixup_wheel") as fixed: builder.fixup_module_wheel("mod.whl") - fixed.assert_called_once_with("mod.whl", remote_module_wheel=True) + assert fixed.call_args.args[0] == "mod.whl" + assert fixed.call_args.kwargs == {"remote_module_wheel": True} def test_macos_repairs_module_wheels_in_place( diff --git a/tests/test_windows_wheel_builder.py b/tests/test_windows_wheel_builder.py index f063b7a7..5c678de0 100644 --- a/tests/test_windows_wheel_builder.py +++ b/tests/test_windows_wheel_builder.py @@ -118,6 +118,17 @@ def test_a_module_wheel_never_ships_itk_init( assert "itk/__init_biocell__.py," in record +def test_a_module_wheel_is_repaired_with_lib_paths_and_onetbb( + windows_builder: WindowsBuildPythonInstance, +) -> None: + """delvewheel looks for a module's DLLs where it looks for itk-core's.""" + windows_builder.windows_extra_lib_paths = ["C:/CUDA/bin"] + with patch.object(windows_builder, "fixup_wheel") as fixup: + windows_builder.fixup_module_wheel("module.whl") + tbb_bin = str(windows_builder.build_dir_root / "build" / "oneTBB-prefix" / "bin") + assert fixup.call_args.args[1] == f"C:/CUDA/bin;{tbb_bin}" + + def test_non_remote_repaired_wheel_lands_in_the_build_dist( tmp_path: Path, windows_builder: WindowsBuildPythonInstance ) -> None: From d706d83c5610d9d60f542f802f47f0b237fbb02f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:35:22 -0500 Subject: [PATCH 04/23] BUG: Strip the quotes around Windows module CMake options ITKRemoteModuleBuildTestPackageAction puts each Windows CMake option in double quotes and passes them as one string: -cmake_options '"-DA:BOOL=ON" "-DB=2"' The previous script ran its command line through Invoke-Expression, which removed those quotes. The new one splits the string on spaces and passes the pieces to pixi, so build_wheels.py received "-DA:BOOL=ON" with its quotes, did not take it for a -D definition, and stopped with "CMake option '\"-DA:BOOL=ON\"' is not a -D= definition". Drop the quotes from each option, and skip empty pieces from repeated spaces. Checked with PowerShell 7.6 and Windows PowerShell 5.1. --- scripts/windows-download-cache-and-build-module-wheels.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/windows-download-cache-and-build-module-wheels.ps1 b/scripts/windows-download-cache-and-build-module-wheels.ps1 index b09a317c..7f6f1660 100644 --- a/scripts/windows-download-cache-and-build-module-wheels.ps1 +++ b/scripts/windows-download-cache-and-build-module-wheels.ps1 @@ -293,7 +293,8 @@ if ($setup_options.Length -gt 0) { if ($cmake_options.Length -gt 0) { $buildArgs += @("--") - $buildArgs += $cmake_options.Split(" ") + # The CI action quotes each option ("-DA=1" "-DB=2"); the quotes are not part of it. + $buildArgs += $cmake_options.Split(" ", [StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object { $_.Trim('"') } } echo "Building target module..." From 45540dedc024d2d95f1b77c742a0df520cc3c43c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:35:53 -0500 Subject: [PATCH 05/23] BUG: Fail the macOS module build on a bad option or a failed build ITKRemoteModuleBuildTestPackageAction runs ./macpython-download-cache-and-build-module-wheels.sh $CMAKE_OPTIONS 3.11 with CMAKE_OPTIONS="--cmake_options -DA=1 -DB=2" unquoted. The script took -DA=1 as the CMake options and -DB=2 as a Python version, built the module without -DB=2, failed to find a "macosx-py-DB=2" pixi environment, and still exited 0, because only the last build's status counted. Reject an unknown option, as the Linux module script does, and stop at the first build that fails. --- scripts/macpython-download-cache-and-build-module-wheels.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/macpython-download-cache-and-build-module-wheels.sh b/scripts/macpython-download-cache-and-build-module-wheels.sh index 52a36302..39df56a5 100755 --- a/scripts/macpython-download-cache-and-build-module-wheels.sh +++ b/scripts/macpython-download-cache-and-build-module-wheels.sh @@ -51,6 +51,10 @@ while [ $# -gt 0 ]; do shift break ;; + -*) + echo "Unexpected option: $1." + usage + ;; *) break ;; @@ -185,5 +189,5 @@ for py_indicator in "$@"; do --no-use-ccache \ --skip-itk-build \ --skip-itk-wheel-build \ - ${CMAKE_OPTIONS:+-- ${CMAKE_OPTIONS}} + ${CMAKE_OPTIONS:+-- ${CMAKE_OPTIONS}} || exit done From 8db4fc5830e3c4656e9a2f6073028ddbd7236304 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:37:33 -0500 Subject: [PATCH 06/23] BUG: Exclude --exclude_libs libraries from Linux module wheels The Linux module script accepted -x/--exclude_libs only to print that it was ignored, and build_wheels.py applied --exclude-libs on Windows alone. A module that links the CUDA driver or runtime, such as RTK with RTK_USE_CUDA, therefore had libcuda.so.1 and the other CUDA libraries grafted into its manylinux wheel by auditwheel, as the previous scripts prevented with auditwheel --exclude. Pass -x on to build_wheels.py as --exclude-libs, and give auditwheel an --exclude for each library it names. --- scripts/build_wheels.py | 7 +++++-- ...ux-download-cache-and-build-module-wheels.sh | 6 +++--- scripts/linux_build_python_instance.py | 15 +++++++++++++++ tests/test_platform_builders.py | 17 +++++++++++++++++ 4 files changed, 40 insertions(+), 5 deletions(-) diff --git a/scripts/build_wheels.py b/scripts/build_wheels.py index 0a1cf4fb..e3bdaac1 100755 --- a/scripts/build_wheels.py +++ b/scripts/build_wheels.py @@ -346,7 +346,8 @@ def build_argument_parser(os_name: OS, ipp_dir: Path) -> argparse.ArgumentParser nargs=1, default="", help=( - 'Windows only: semicolon-delimited DLL names delvewheel must not bundle, e.g. "nvcuda.dll"' + "Windows and Linux: semicolon-delimited library names delvewheel or " + 'auditwheel must not bundle, e.g. "nvcuda.dll" or "libcuda.so.1"' ), ) _cmake_options_default = remote_module_build_dict["CMAKE_OPTIONS"] @@ -751,7 +752,9 @@ def make_builder( else: from linux_build_python_instance import LinuxBuildPythonInstance - builder_cls = LinuxBuildPythonInstance + builder_cls = functools.partial( + LinuxBuildPythonInstance, exclude_libs=args.exclude_libs + ) return builder_cls( platform_env=args.platform_env, build_dir_root=args.build_dir_root, diff --git a/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh b/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh index 56d63bbd..b5ffb18a 100755 --- a/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh +++ b/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh @@ -42,7 +42,7 @@ usage() { dockcross-manylinux-download-cache-and-build-module-wheels [ -h | --help ] show usage [ -c | --cmake_options ] space-delimited string containing CMake options to forward to the module (e.g. \"-DBUILD_TESTING=OFF\") - [ -x | --exclude_libs ] accepted for compatibility and ignored; nothing excludes libraries from the repair + [ -x | --exclude_libs ] semicolon-delimited library names auditwheel must not bundle (e.g. \"libcuda.so.1\") [ python_version ] build wheel for a specific python version. (e.g. cp311)" exit 2 } @@ -73,11 +73,11 @@ while [ $# -gt 0 ]; do ;; -x | --exclude_libs | -exclude_libs) option_value "$@" - echo "WARNING: --exclude_libs '$2' is ignored; no library is excluded from the wheel repair." + export BUILD_WHEELS_EXTRA_FLAGS="${BUILD_WHEELS_EXTRA_FLAGS} --exclude-libs $2" shift 2 ;; --exclude_libs=* | -exclude_libs=*) - echo "WARNING: --exclude_libs '${1#*=}' is ignored; no library is excluded from the wheel repair." + export BUILD_WHEELS_EXTRA_FLAGS="${BUILD_WHEELS_EXTRA_FLAGS} --exclude-libs ${1#*=}" shift ;; --) diff --git a/scripts/linux_build_python_instance.py b/scripts/linux_build_python_instance.py index d95e8e7e..f26a12b5 100644 --- a/scripts/linux_build_python_instance.py +++ b/scripts/linux_build_python_instance.py @@ -2,6 +2,7 @@ import os import shutil from pathlib import Path +from typing import Any from posix_build_python_instance import PosixBuildPythonInstance from wheel_builder_utils import ( @@ -16,6 +17,14 @@ class LinuxBuildPythonInstance(PosixBuildPythonInstance): Linux-specific compiler/target triple configuration. """ + #: ``--exclude-libs``: libraries ``auditwheel`` must not bundle. + exclude_libs: list[str] | str = "" + + def __init__(self, *, exclude_libs: list[str] | str = "", **kwargs: Any) -> None: + """Take ``--exclude-libs``; the rest are the base's.""" + super().__init__(**kwargs) + self.exclude_libs = exclude_libs + def builds_manylinux(self) -> bool: """True when the wheels are repaired and tagged for manylinux.""" return bool(self.target.manylinux_version) @@ -157,6 +166,12 @@ def fixup_wheel(self, filepath: str, remote_module_wheel: bool = False) -> None: "--plat", self.target.wheel_plat_tag, ] + excludes = self.exclude_libs + if isinstance(excludes, list): + excludes = ";".join(excludes) + for lib in excludes.split(";"): + if lib: + cmd += ["--exclude", lib] cmd += [str(filepath), "-w", str(output_dir)] # Provide LD_LIBRARY_PATH for oneTBB and common system paths extra_lib = str(self._tbb_prefix / "lib") diff --git a/tests/test_platform_builders.py b/tests/test_platform_builders.py index d7677888..387dc977 100644 --- a/tests/test_platform_builders.py +++ b/tests/test_platform_builders.py @@ -254,6 +254,23 @@ def fake_repair(cmd: Sequence[str | Path], env: Mapping[str, str]) -> int: return captured_env +def test_excluded_libraries_go_to_auditwheel_exclude( + tmp_path: Path, linux_builder: LinuxBuildPythonInstance +) -> None: + linux_builder.exclude_libs = ["libcuda.so.1;libnvrtc.so.12"] + wheel, repaired = _prepare_linux_fixup(linux_builder, tmp_path) + commands: list[list[str]] = [] + + def fake_repair(cmd: Sequence[str | Path], env: Mapping[str, str]) -> int: + commands.append([str(c) for c in cmd]) + repaired.touch() + return 0 + + with patch.object(linux_builder, "echo_check_call", side_effect=fake_repair): + linux_builder.fixup_wheel(str(wheel)) + assert " --exclude libcuda.so.1 --exclude libnvrtc.so.12 " in " ".join(commands[0]) + + def test_fixup_wheel_ld_library_path_starts_with_the_build_env_lib_dir( tmp_path: Path, linux_builder: LinuxBuildPythonInstance, From eb67898ec9970dc455c0bdd09f5f1d1b2f7825a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:38:52 -0500 Subject: [PATCH 07/23] BUG: Pass LD_LIBRARY_PATH to the Linux module build container dockcross-manylinux-build-module-wheels.sh mounts each LD_LIBRARY_PATH directory at /usr/lib64/ and sets LD_LIBRARY_PATH to those mount points, but no longer passes the variable into the container; the previous script added -e LD_LIBRARY_PATH to the docker arguments. auditwheel in the container therefore did not look in the mounted directories, and a module whose libraries come from there failed to repair. Pass the rewritten LD_LIBRARY_PATH to the container when it is set. --- .../dockcross-manylinux-build-module-wheels.sh | 4 ++++ tests/test_module_script_docker_args.py | 17 +++++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/scripts/dockcross-manylinux-build-module-wheels.sh b/scripts/dockcross-manylinux-build-module-wheels.sh index 6f57de0b..7d93266b 100755 --- a/scripts/dockcross-manylinux-build-module-wheels.sh +++ b/scripts/dockcross-manylinux-build-module-wheels.sh @@ -163,6 +163,10 @@ if [[ -n ${LD_LIBRARY_PATH} ]]; then done fi export LD_LIBRARY_PATH="${DOCKER_LD_LIBRARY_PATH}" +# auditwheel in the container finds the libraries of mounted directories here. +if [[ -n ${LD_LIBRARY_PATH} ]]; then + DOCKER_ARGS+=" -e LD_LIBRARY_PATH=${LD_LIBRARY_PATH} " +fi # To build tarballs in manylinux, use 'export BUILD_WHEELS_EXTRA_FLAGS=" --build-itk-tarball-cache "' BUILD_WHEELS_EXTRA_FLAGS=${BUILD_WHEELS_EXTRA_FLAGS:=""} # No tarball by default diff --git a/tests/test_module_script_docker_args.py b/tests/test_module_script_docker_args.py index 66d2ff0a..28d91a01 100644 --- a/tests/test_module_script_docker_args.py +++ b/tests/test_module_script_docker_args.py @@ -42,8 +42,9 @@ def _run(tmp_path: Path, arch: str, cmake_options: str) -> list[str]: "MODULE_DEPS_DIR": str(tmp_path / "deps"), "CMAKE_OPTIONS": cmake_options, } - if "CONTAINER_DNS" in os.environ: - env["CONTAINER_DNS"] = os.environ["CONTAINER_DNS"] + for name in ("CONTAINER_DNS", "LD_LIBRARY_PATH"): + if name in os.environ: + env[name] = os.environ[name] result = subprocess.run( ["bash", str(ipp / "scripts" / "dockcross-manylinux-build-module-wheels.sh")], env=env, @@ -83,3 +84,15 @@ def test_host_networking_without_container_dns(tmp_path: Path, arch: str) -> Non args = " ".join(_run(tmp_path, arch, "")) assert "--network=host" in args assert "--dns" not in args + + +@pytest.mark.skipif(os.name == "nt", reason="a drive letter's colon splits the path") +@pytest.mark.parametrize("arch", ["x64", "aarch64"]) +def test_ld_library_path_reaches_the_container( + tmp_path: Path, arch: str, monkeypatch: pytest.MonkeyPatch +) -> None: + libs = tmp_path / "cuda-lib64" + libs.mkdir() + monkeypatch.setenv("LD_LIBRARY_PATH", str(libs)) + args = " ".join(_run(tmp_path, arch, "")) + assert "-e LD_LIBRARY_PATH=/usr/lib64/cuda-lib64:" in args From f956d63fe8baddd80bf5b95ce1c2880109c1e1dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:39:50 -0500 Subject: [PATCH 08/23] BUG: Run the shell script tests with Git's bash on Windows On Windows, subprocess.run(["bash", ...]) starts C:\Windows\System32\bash.exe, the WSL launcher, even when Git's bash comes first on PATH, because process creation searches System32 before PATH. Without a WSL distribution it fails, so 14 tests of the module scripts and require_env_vars.sh failed on Windows. Take bash from Git for Windows there, next to git, and skip the tests when there is none. --- tests/bash.py | 28 +++++++++++++++++++++++++ tests/test_download_cache_archive.py | 6 ++++-- tests/test_module_script_arguments.py | 7 ++++--- tests/test_module_script_docker_args.py | 6 ++++-- tests/test_require_env_vars.py | 9 ++++---- 5 files changed, 45 insertions(+), 11 deletions(-) create mode 100644 tests/bash.py diff --git a/tests/bash.py b/tests/bash.py new file mode 100644 index 00000000..e5707283 --- /dev/null +++ b/tests/bash.py @@ -0,0 +1,28 @@ +"""The bash that runs the shell script tests.""" + +import os +import shutil +from pathlib import Path + + +def find_bash() -> str: + """Return the path of bash, or an empty string when there is none. + + On Windows, System32\\bash.exe starts WSL, which fails without an + installed distribution, and process creation finds it before PATH; + use the bash that comes with Git for Windows instead. + """ + if os.name != "nt": + return shutil.which("bash") or "" + git = shutil.which("git") + if git is None: + return "" + # git.exe is in cmd/, bin/, or mingw64/bin/ of the Git installation. + for root in Path(git).resolve().parents[1:3]: + bash = root / "bin" / "bash.exe" + if bash.is_file(): + return str(bash) + return "" + + +BASH = find_bash() diff --git a/tests/test_download_cache_archive.py b/tests/test_download_cache_archive.py index 4a86ea44..70bc702b 100644 --- a/tests/test_download_cache_archive.py +++ b/tests/test_download_cache_archive.py @@ -8,6 +8,8 @@ import pytest +from tests.bash import BASH + SCRIPT = ( Path(__file__).resolve().parent.parent / "scripts" @@ -24,7 +26,7 @@ """ pytestmark = pytest.mark.skipif( - shutil.which("bash") is None + not BASH or shutil.which("zstd") is None or shutil.which("unzstd") is None or shutil.which("rsync") is None, @@ -63,7 +65,7 @@ def test_a_local_archive_is_extracted(tmp_path: Path, symlinked: bool) -> None: "TARGET_ARCH": "x64", } result = subprocess.run( - ["bash", str(SCRIPT)], + [BASH, str(SCRIPT)], cwd=work, env=env, capture_output=True, diff --git a/tests/test_module_script_arguments.py b/tests/test_module_script_arguments.py index 38b9a841..3d77115b 100644 --- a/tests/test_module_script_arguments.py +++ b/tests/test_module_script_arguments.py @@ -1,19 +1,20 @@ """Argument parsing of the Linux module script, which also runs on macOS.""" import os -import shutil import subprocess from pathlib import Path import pytest +from tests.bash import BASH + SCRIPT = ( Path(__file__).resolve().parent.parent / "scripts" / "dockcross-manylinux-download-cache-and-build-module-wheels.sh" ) -pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +pytestmark = pytest.mark.skipif(not BASH, reason="needs bash") def _run(tmp_path: Path, *args: str) -> subprocess.CompletedProcess[str]: @@ -28,7 +29,7 @@ def _run(tmp_path: Path, *args: str) -> subprocess.CompletedProcess[str]: "MODULE_DEPS_DIR": str(tmp_path / "deps"), } return subprocess.run( - ["bash", str(SCRIPT), *args], + [BASH, str(SCRIPT), *args], env=env, capture_output=True, text=True, diff --git a/tests/test_module_script_docker_args.py b/tests/test_module_script_docker_args.py index 28d91a01..bd028a72 100644 --- a/tests/test_module_script_docker_args.py +++ b/tests/test_module_script_docker_args.py @@ -7,9 +7,11 @@ import pytest +from tests.bash import BASH + SCRIPTS = Path(__file__).resolve().parent.parent / "scripts" -pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +pytestmark = pytest.mark.skipif(not BASH, reason="needs bash") # Records each argument on its own line. Asked for the dockcross runner # (``run --rm ``), it prints a runner that records its arguments too. @@ -46,7 +48,7 @@ def _run(tmp_path: Path, arch: str, cmake_options: str) -> list[str]: if name in os.environ: env[name] = os.environ[name] result = subprocess.run( - ["bash", str(ipp / "scripts" / "dockcross-manylinux-build-module-wheels.sh")], + [BASH, str(ipp / "scripts" / "dockcross-manylinux-build-module-wheels.sh")], env=env, capture_output=True, text=True, diff --git a/tests/test_require_env_vars.py b/tests/test_require_env_vars.py index 5051d0ee..c8d4f003 100644 --- a/tests/test_require_env_vars.py +++ b/tests/test_require_env_vars.py @@ -1,16 +1,17 @@ -import shutil import subprocess from pathlib import Path import pytest +from tests.bash import BASH + HELPER = Path(__file__).resolve().parent.parent / "scripts" / "require_env_vars.sh" def _run(env: dict[str, str], *names: str) -> subprocess.CompletedProcess[str]: script = f'source "{HELPER}"; require_env_vars {" ".join(names)}; echo reached' return subprocess.run( - ["bash", "-c", script], + [BASH, "-c", script], env={"PATH": "/usr/bin:/bin", **env}, capture_output=True, text=True, @@ -18,7 +19,7 @@ def _run(env: dict[str, str], *names: str) -> subprocess.CompletedProcess[str]: ) -@pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +@pytest.mark.skipif(not BASH, reason="needs bash") def test_every_missing_variable_is_reported_before_exiting() -> None: result = _run({"SET": "1", "EMPTY": ""}, "SET", "EMPTY", "UNSET") assert result.returncode == 1 @@ -29,7 +30,7 @@ def test_every_missing_variable_is_reported_before_exiting() -> None: ] -@pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +@pytest.mark.skipif(not BASH, reason="needs bash") def test_set_variables_pass() -> None: result = _run({"A": "1", "B": "2"}, "A", "B") assert result.returncode == 0 From 945100d131b70b170522c9e2bccd8085171c860e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:40:20 -0500 Subject: [PATCH 09/23] BUG: Compare paths in the config and cgroup tests as Windows writes them On Windows str(Path("/bdr/ITK")) is "\bdr\ITK", so four BuildConfig environment tests, which expected "/bdr/ITK", failed there, and the fake cgroup files of test_cgroup_v2_limit_caps_reported_memory, looked up by str(path), were never found. Expect the paths as the host renders them, and look the fake cgroup files up by their POSIX form. --- tests/test_build_config.py | 23 ++++++++++++++--------- tests/test_build_jobs.py | 2 +- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/tests/test_build_config.py b/tests/test_build_config.py index 842d1a7b..fbe49fcc 100644 --- a/tests/test_build_config.py +++ b/tests/test_build_config.py @@ -50,28 +50,33 @@ def _config( return _build(target, env or {}, _args(**overrides)) +def _host_path(path: str) -> str: + """*path* as the host writes it: with backslashes on Windows.""" + return str(Path(path)) + + COMMON_TAIL = [ ("ITK_MODULE_PREQ", ""), ("ITK_MODULE_NO_CLEANUP", "1"), ("USE_CCACHE", "OFF"), ("DEAD_STRIP", "ON"), - ("PIXI_EXECUTABLE", "/px/pixi"), - ("CMAKE_EXECUTABLE", "/env/bin/cmake"), - ("NINJA_EXECUTABLE", "/env/bin/ninja"), - ("DOXYGEN_EXECUTABLE", "/env/bin/doxygen"), - ("GIT_EXECUTABLE", "/env/bin/git"), - ("PYTHON_EXECUTABLE", "/env/bin/python"), + ("PIXI_EXECUTABLE", _host_path("/px/pixi")), + ("CMAKE_EXECUTABLE", _host_path("/env/bin/cmake")), + ("NINJA_EXECUTABLE", _host_path("/env/bin/ninja")), + ("DOXYGEN_EXECUTABLE", _host_path("/env/bin/doxygen")), + ("GIT_EXECUTABLE", _host_path("/env/bin/git")), + ("PYTHON_EXECUTABLE", _host_path("/env/bin/python")), ("OCI_EXE", "docker"), ] def _head(os_name: str, arch: str) -> list[tuple[str, str]]: return [ - ("ITK_SOURCE_DIR", "/bdr/ITK"), - ("IPP_SUPERBUILD_BINARY_DIR", "/bdr/build/ITK-support-bld"), + ("ITK_SOURCE_DIR", _host_path("/bdr/ITK")), + ("IPP_SUPERBUILD_BINARY_DIR", _host_path("/bdr/build/ITK-support-bld")), ("OS_NAME", os_name), ("ARCH", arch), - ("BUILD_DIR_ROOT", "/bdr"), + ("BUILD_DIR_ROOT", _host_path("/bdr")), ("ITK_GIT_TAG", "v6.0b02"), ("ITK_PACKAGE_VERSION", "6.0.0b2"), ] diff --git a/tests/test_build_jobs.py b/tests/test_build_jobs.py index bec6bba2..977675a7 100644 --- a/tests/test_build_jobs.py +++ b/tests/test_build_jobs.py @@ -92,7 +92,7 @@ def _fake_open(mapping: Mapping[str, str]) -> Callable[..., IO[str]]: real_open = Path.open def fake(path: Path, *args: Any, **kwargs: Any) -> IO[str]: - key = str(path) + key = path.as_posix() if key in mapping: import io From bb386e01d93d2cbbee2d08908d42c6b28c1747ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:40:46 -0500 Subject: [PATCH 10/23] STYLE: Write the 7-Zip candidate paths with single backslashes In a raw string "\\" is two backslashes, so r"C:\Program Files\7-Zip" named a path with doubled separators. pathlib collapses them, which is why 7-Zip was still found; write the paths as they are. --- scripts/windows_build_python_instance.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/windows_build_python_instance.py b/scripts/windows_build_python_instance.py index a04a7101..80d2eddf 100644 --- a/scripts/windows_build_python_instance.py +++ b/scripts/windows_build_python_instance.py @@ -192,9 +192,9 @@ def build_tarball(self) -> None: ] seven_zip_candidates = [ - Path(r"C:\\7-Zip\\7z.exe"), - Path(r"C:\\Program Files\\7-Zip\\7z.exe"), - Path(r"C:\\Program Files (x86)\\7-Zip\\7z.exe"), + Path(r"C:\7-Zip\7z.exe"), + Path(r"C:\Program Files\7-Zip\7z.exe"), + Path(r"C:\Program Files (x86)\7-Zip\7z.exe"), ] seven_zip = None From 7f443a0674580cb678742ad5697653b90c652cd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:41:15 -0500 Subject: [PATCH 11/23] BUG: Keep an installed 7-Zip out of the zip fallback test test_zip_fallback_archives_the_seven_zip_roots hid 7-Zip by patching shutil.which, but build_tarball checks C:\Program Files\7-Zip\7z.exe and two other fixed paths first. On a Windows host with 7-Zip installed, the test ran 7-Zip and failed. Name the fixed paths in a module constant, which the test empties. --- scripts/windows_build_python_instance.py | 15 ++++++++------- tests/test_windows_wheel_builder.py | 1 + 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/scripts/windows_build_python_instance.py b/scripts/windows_build_python_instance.py index 80d2eddf..aac6dabb 100644 --- a/scripts/windows_build_python_instance.py +++ b/scripts/windows_build_python_instance.py @@ -28,6 +28,13 @@ "*.pdb", ) +#: Where ``build_tarball`` looks for 7-Zip before ``PATH``. +SEVEN_ZIP_CANDIDATES = ( + Path(r"C:\7-Zip\7z.exe"), + Path(r"C:\Program Files\7-Zip\7z.exe"), + Path(r"C:\Program Files (x86)\7-Zip\7z.exe"), +) + def _archive_excluded(relative: PurePath) -> bool: """Return True when *relative* matches an ``ARCHIVE_EXCLUDES`` pattern.""" @@ -191,14 +198,8 @@ def build_tarball(self) -> None: self.ipp_dir, ] - seven_zip_candidates = [ - Path(r"C:\7-Zip\7z.exe"), - Path(r"C:\Program Files\7-Zip\7z.exe"), - Path(r"C:\Program Files (x86)\7-Zip\7z.exe"), - ] - seven_zip = None - for cand in seven_zip_candidates: + for cand in SEVEN_ZIP_CANDIDATES: if cand.exists(): seven_zip = cand break diff --git a/tests/test_windows_wheel_builder.py b/tests/test_windows_wheel_builder.py index 5c678de0..ff19a17e 100644 --- a/tests/test_windows_wheel_builder.py +++ b/tests/test_windows_wheel_builder.py @@ -285,6 +285,7 @@ def test_zip_fallback_archives_the_seven_zip_roots( path.write_text("x") with ( + patch("windows_build_python_instance.SEVEN_ZIP_CANDIDATES", ()), patch("windows_build_python_instance.shutil.which", return_value=None), patch.object(windows_builder, "echo_check_call") as call, ): From 5985d102f8e94a5110345d6ae1add0dc4d617693 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:41:35 -0500 Subject: [PATCH 12/23] BUG: Start a new Windows cache archive instead of adding to one build_tarball ran "7z a" on ITKPythonBuilds-windows.zip, which updates an existing archive: files deleted from the build tree since the last --build-itk-tarball-cache run stayed in the cache, and a module build extracting it got them back. Only the zip fallback removed the old archive first. Remove it before running 7-Zip too. --- scripts/windows_build_python_instance.py | 2 ++ tests/test_windows_wheel_builder.py | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/scripts/windows_build_python_instance.py b/scripts/windows_build_python_instance.py index aac6dabb..2c8241e0 100644 --- a/scripts/windows_build_python_instance.py +++ b/scripts/windows_build_python_instance.py @@ -210,6 +210,8 @@ def build_tarball(self) -> None: seven_zip = Path(found) if seven_zip is not None: + # "7z a" adds to an existing archive, keeping files since deleted. + out_zip.unlink(missing_ok=True) # No -r: it would match build/ recursively and sweep in a module's tree. cmd = [ str(seven_zip), diff --git a/tests/test_windows_wheel_builder.py b/tests/test_windows_wheel_builder.py index ff19a17e..d99541be 100644 --- a/tests/test_windows_wheel_builder.py +++ b/tests/test_windows_wheel_builder.py @@ -263,6 +263,15 @@ def test_seven_zip_archives_absolute_roots_not_bare_names( assert str(windows_builder.ipp_dir) in cmd +def test_seven_zip_starts_a_new_archive( + tmp_path: Path, windows_builder: WindowsBuildPythonInstance +) -> None: + stale = windows_builder.build_dir_root / "ITKPythonBuilds-windows.zip" + stale.write_text("an archive from an earlier build") + _run_build_tarball(windows_builder, tmp_path) + assert not stale.exists() + + def test_zip_fallback_archives_the_seven_zip_roots( tmp_path: Path, windows_builder: WindowsBuildPythonInstance ) -> None: From f2b826bd26e1770936b64b022e875c21c253f91c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:42:51 -0500 Subject: [PATCH 13/23] BUG: Keep each module build's step report apart from the ITK build's A remote module build wrote its steps to the same dist/build_log_.json as the ITK build. Its inputs carry a module state the ITK build's lack, so each run found the inputs changed and replaced the ITK build's records with its own skipped steps: the next ITK build reran every step, and dependency modules, built into the same report, did the same to each other. Name a module build's report build_log__.json. --- docs/Build_ITK_Python_packages.rst | 3 ++- scripts/build_python_instance_base.py | 9 ++++++++- tests/test_build_steps.py | 13 +++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/docs/Build_ITK_Python_packages.rst b/docs/Build_ITK_Python_packages.rst index c16468cd..23c887a2 100644 --- a/docs/Build_ITK_Python_packages.rst +++ b/docs/Build_ITK_Python_packages.rst @@ -32,7 +32,8 @@ seven sequential steps: 6. *(optional)* Build a remote module against the ITK build 7. *(optional)* Create a reusable ITK build tarball cache -Step state is persisted to ``/dist/build_log_.json`` so that a +Step state is persisted to ``/dist/build_log_.json``, or +``build_log__.json`` for a remote module, so that a build interrupted part-way through can be resumed by re-running the same command. The log also records the build's inputs: the ITK commit, the package version, a fingerprint of the build scripts, CMake settings, and ``pixi.lock``, and for a diff --git a/scripts/build_python_instance_base.py b/scripts/build_python_instance_base.py index df49a977..45a52ed3 100644 --- a/scripts/build_python_instance_base.py +++ b/scripts/build_python_instance_base.py @@ -406,7 +406,7 @@ def run(self) -> None: python_package_build_steps = self.build_step_table() self.dist_dir.mkdir(parents=True, exist_ok=True) - build_report_fn: Path = self.dist_dir / f"build_log_{self.platform_env}.json" + build_report_fn: Path = self.build_report_path() build_manager: BuildManager = BuildManager( build_report_fn, list(python_package_build_steps.keys()), @@ -430,6 +430,13 @@ def run(self) -> None: for cmd in cache_after: self.echo_check_call(cmd, use_pixi_env=False) + def build_report_path(self) -> Path: + """Return the step report; each module's is apart from the ITK build's.""" + name = f"build_log_{self.platform_env}" + if self.module_source_dir is not None: + name += f"_{Path(self.module_source_dir).name}" + return self.dist_dir / f"{name}.json" + def build_dependency_module(self, module_source_dir: Path) -> None: """Build the wheel of a dependency module with a copy of this builder.""" dependency_build = self.clone() diff --git a/tests/test_build_steps.py b/tests/test_build_steps.py index 1627ecc1..1c2b9229 100644 --- a/tests/test_build_steps.py +++ b/tests/test_build_steps.py @@ -150,3 +150,16 @@ def second() -> object: assert list(skipped) == ["01_a", "02_b_skipped"] assert skipped["01_a"] is first assert skipped["02_b_skipped"]() is None + + +def test_a_module_build_keeps_its_own_step_report( + linux_builder: LinuxBuildPythonInstance, +) -> None: + """A module's inputs differ from ITK's, so a shared report reran every step.""" + builder = _configure(linux_builder) + builder.dist_dir = Path("dist") + assert builder.build_report_path().name == "build_log_manylinux228-py311.json" + builder.module_source_dir = Path("modules") / "BioCell" + assert ( + builder.build_report_path().name == "build_log_manylinux228-py311_BioCell.json" + ) From 358f879f864f34a5c79e521509108423974e9ecd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:44:13 -0500 Subject: [PATCH 14/23] BUG: Rebuild when the ITK source has uncommitted changes The step report recorded the ITK commit, HEAD, as the build's ITK input. Editing ITK sources, or adding a file, without committing left it unchanged, so a rerun skipped the ITK build and wheel steps and packaged the previous build: the local edits never reached the wheels. Record "+" when the ITK tree has changes to tracked files or untracked files git does not ignore, as the module state already does for changes to a module's tracked files. --- docs/Build_ITK_Python_packages.rst | 5 ++-- scripts/build_inputs.py | 48 +++++++++++++++++++++++++++++- tests/test_build_inputs.py | 15 ++++++++++ 3 files changed, 65 insertions(+), 3 deletions(-) diff --git a/docs/Build_ITK_Python_packages.rst b/docs/Build_ITK_Python_packages.rst index 23c887a2..c2191dab 100644 --- a/docs/Build_ITK_Python_packages.rst +++ b/docs/Build_ITK_Python_packages.rst @@ -35,8 +35,9 @@ seven sequential steps: Step state is persisted to ``/dist/build_log_.json``, or ``build_log__.json`` for a remote module, so that a build interrupted part-way through can be resumed by re-running the same command. -The log also records the build's inputs: the ITK commit, the package version, -a fingerprint of the build scripts, CMake settings, and ``pixi.lock``, and for a +The log also records the build's inputs: the ITK commit and its uncommitted +changes, the package version, a fingerprint of the build scripts, CMake +settings, and ``pixi.lock``, and for a remote module its git commit and uncommitted changes. When any of them differs from the recorded run, every step runs again. ``CFLAGS`` and ``CXXFLAGS`` (and ``LDFLAGS`` on Linux and macOS) reach CMake as ``CMAKE_*_FLAGS`` diff --git a/scripts/build_inputs.py b/scripts/build_inputs.py index 146718ba..77c4fc41 100644 --- a/scripts/build_inputs.py +++ b/scripts/build_inputs.py @@ -51,11 +51,50 @@ def build_fingerprint(ipp_dir: Path, settings: Mapping[str, str]) -> str: return digest.hexdigest() +#: What `uncommitted_changes` returns for a tree without changes. +NO_CHANGES: str = hashlib.sha256().hexdigest() + + +def uncommitted_changes( + directory: Path, + git: str, + env: Mapping[str, str], + skip: frozenset[str] = frozenset(), +) -> str: + """Return a hash of the uncommitted changes in the repository at *directory*. + + It covers the changes to tracked files and the untracked files git does + not ignore, except those under a top-level name in *skip*. + """ + diff = subprocess.run( + [git, "diff", "HEAD", "--binary"], + cwd=directory, + env=env, + capture_output=True, + check=True, + ) + digest = hashlib.sha256(diff.stdout) + untracked = subprocess.run( + [git, "ls-files", "--others", "--exclude-standard", "-z"], + cwd=directory, + env=env, + capture_output=True, + check=True, + ) + for name in sorted(untracked.stdout.decode().split("\0")): + if name and name.split("/")[0] not in skip: + digest.update(name.encode() + b"\0") + with (Path(directory) / name).open("rb") as f: + digest.update(hashlib.file_digest(f, "sha256").digest()) + return digest.hexdigest() + + def resolved_itk_commit(itk_source_dir: Path, fallback: str, git: str = "git") -> str: """Return the commit checked out in *itk_source_dir*, else *fallback*. A branch name is not enough: the same name builds a new commit each day. A tree restored from a build cache has no repository, hence the fallback. + Uncommitted changes add ``+``, as they change what is built. """ env = os.environ.copy() # A cache-restored tree must not report an enclosing repository's commit. @@ -71,7 +110,14 @@ def resolved_itk_commit(itk_source_dir: Path, fallback: str, git: str = "git") - ) except OSError: return fallback - return result.stdout.strip() if result.returncode == 0 else fallback + if result.returncode != 0: + return fallback + commit = result.stdout.strip() + try: + changes = uncommitted_changes(itk_source_dir, git, env) + except (OSError, subprocess.CalledProcessError): + return commit + return commit if changes == NO_CHANGES else f"{commit}+{changes}" #: Names a module build writes into, or that hold caches, inside a module tree. diff --git a/tests/test_build_inputs.py b/tests/test_build_inputs.py index 057d4db7..b1e11f83 100644 --- a/tests/test_build_inputs.py +++ b/tests/test_build_inputs.py @@ -53,6 +53,21 @@ def test_a_branch_name_resolves_to_the_commit_it_builds(itk_source: Path) -> Non assert resolved_itk_commit(itk_source, "main") == after != before +def test_uncommitted_itk_changes_change_the_commit(itk_source: Path) -> None: + """A build of edited sources must not reuse the build of the commit.""" + commit = resolved_itk_commit(itk_source, "main") + new_file = itk_source / "itkNew.h" + new_file.write_text("// new\n") + untracked = resolved_itk_commit(itk_source, "main") + _git(itk_source, "add", "itkNew.h") + staged = resolved_itk_commit(itk_source, "main") + new_file.write_text("// edited\n") + edited = resolved_itk_commit(itk_source, "main") + assert "+" not in commit + assert len({commit, untracked, staged, edited}) == 4 + assert all(r.startswith(f"{commit}+") for r in (untracked, staged, edited)) + + def test_a_tree_without_a_repository_reports_the_requested_revision( tmp_path: Path, ) -> None: From 90c985785bf1e6105c1f43a6f9ac559f059b0e6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:45:27 -0500 Subject: [PATCH 15/23] BUG: Count untracked files in a remote module's state module_source_state hashed "git diff HEAD", which leaves out untracked files. Adding a new header, source, or .wrap file to a module without committing it left the state unchanged, so a rerun skipped the module wheel step and kept the wheel built without it. Hash the untracked files git does not ignore too, except the build outputs and caches MODULE_STATE_SKIP already leaves out of a module without a repository. --- scripts/build_inputs.py | 9 +-------- tests/test_build_inputs.py | 7 +++++++ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/scripts/build_inputs.py b/scripts/build_inputs.py index 77c4fc41..c84ab415 100644 --- a/scripts/build_inputs.py +++ b/scripts/build_inputs.py @@ -151,14 +151,7 @@ def module_source_state(module_dir: Path, git: str = "git") -> str: check=False, ) if head.returncode == 0: - diff = subprocess.run( - [git, "diff", "HEAD", "--binary"], - cwd=module_dir, - env=env, - capture_output=True, - check=True, - ) - changes = hashlib.sha256(diff.stdout).hexdigest() + changes = uncommitted_changes(module_dir, git, env, MODULE_STATE_SKIP) return f"{head.stdout.decode().strip()}+{changes}" except (OSError, subprocess.CalledProcessError): pass diff --git a/tests/test_build_inputs.py b/tests/test_build_inputs.py index b1e11f83..30d6ee02 100644 --- a/tests/test_build_inputs.py +++ b/tests/test_build_inputs.py @@ -212,6 +212,13 @@ def test_module_state_follows_commits_and_uncommitted_edits( assert committed not in (first, edited) +def test_a_new_module_file_changes_the_module_state(module_source: Path) -> None: + before = module_source_state(module_source) + (module_source / "include").mkdir() + (module_source / "include" / "itkNew.h").write_text("int a;\n") + assert module_source_state(module_source) != before + + def test_module_state_ignores_what_the_module_build_writes(module_source: Path) -> None: before = module_source_state(module_source) (module_source / "dist").mkdir() From 175c91a222c9fa86de53f43828d96457dd1c1973 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:48:06 -0500 Subject: [PATCH 16/23] BUG: Rerun the build when the wheel repair or module ITK tree changes The build inputs left out --lib-paths, --exclude-libs, and, for a remote module, --module-itk-dir. Rerunning with a different value found every step done and kept wheels repaired with the old library paths and exclusions, or a module built against the other ITK tree. Add them to the settings the fingerprint covers. --- scripts/build_python_instance_base.py | 8 ++++++++ tests/test_build_inputs.py | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/scripts/build_python_instance_base.py b/scripts/build_python_instance_base.py index 45a52ed3..d48d0579 100644 --- a/scripts/build_python_instance_base.py +++ b/scripts/build_python_instance_base.py @@ -456,10 +456,18 @@ def build_inputs(self) -> dict[str, str]: settings.update({f"{group}:{k}": str(v) for k, v in definitions.items()}) for key in ("USE_CCACHE", "MANYLINUX_VERSION", "CONTAINER_SOURCE"): settings[key] = cfg.get(key, "") + # The platform builders' wheel repair options. + for option in ( + "windows_extra_lib_paths", + "windows_exclude_libs", + "exclude_libs", + ): + settings[option] = str(getattr(self, option, "")) git = str(self.config.git_executable) module_state = None if self.module_source_dir is not None: settings["itk_module_deps"] = str(self.itk_module_deps or "") + settings["module_itk_dir"] = self.module_itk_dir module_state = module_source_state(Path(self.module_source_dir), git) return build_inputs( itk_commit=resolved_itk_commit( diff --git a/tests/test_build_inputs.py b/tests/test_build_inputs.py index 30d6ee02..a2e06c80 100644 --- a/tests/test_build_inputs.py +++ b/tests/test_build_inputs.py @@ -187,6 +187,21 @@ def test_a_new_package_version_runs_every_step_again( assert ran == ["01_superbuild", "02_build_itk", "03_build_wheels"] +def test_new_wheel_repair_options_run_every_step_again( + monkeypatch: pytest.MonkeyPatch, + linux_builder: LinuxBuildPythonInstance, + tmp_path: Path, + ipp_dir: Path, + itk_source: Path, +) -> None: + _wire_run(monkeypatch, linux_builder, tmp_path, ipp_dir, itk_source) + linux_builder.run() + linux_builder.exclude_libs = ["libcuda.so.1"] + ran = _wire_run(monkeypatch, linux_builder, tmp_path, ipp_dir, itk_source) + linux_builder.run() + assert ran == ["01_superbuild", "02_build_itk", "03_build_wheels"] + + @pytest.fixture def module_source(tmp_path: Path) -> Path: module = tmp_path / "ITKFoo" From 03afff9b711a04f89e6919f0f85f3e2e466d649f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:48:41 -0500 Subject: [PATCH 17/23] BUG: Keep dist/ when --cleanup runs with a build root in the checkout post_build_cleanup removes the checkout's build/ directory. With --build-dir-root /build, that is the build root itself, so --cleanup deleted dist/ and the wheels just built. Leave a directory that holds the build root in place. --- scripts/wheel_packaging.py | 4 +++- tests/test_wheel_packaging.py | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/scripts/wheel_packaging.py b/scripts/wheel_packaging.py index 944040fd..84264cf7 100644 --- a/scripts/wheel_packaging.py +++ b/scripts/wheel_packaging.py @@ -82,7 +82,9 @@ def rm(tree_path: Path) -> None: # 2) standard build directories for rel in ("ITKPythonPackage", "tools", "_skbuild", "build"): - rm(base / rel) + # A build root inside the checkout, such as /build, holds dist/. + if not build_dir_root.resolve().is_relative_to((base / rel).resolve()): + rm(base / rel) # 3) egg-info folders at top-level for p in base.glob("*.egg-info"): diff --git a/tests/test_wheel_packaging.py b/tests/test_wheel_packaging.py index 0eb370db..3b1cfea9 100644 --- a/tests/test_wheel_packaging.py +++ b/tests/test_wheel_packaging.py @@ -37,6 +37,15 @@ def _run_cleanup(build_root: Path, arch: str) -> set[str]: return survivors +def test_cleanup_keeps_a_build_root_inside_the_checkout(tmp_path: Path) -> None: + """--build-dir-root /build must not lose its wheels.""" + build_root = tmp_path / "build" + (build_root / "dist").mkdir(parents=True) + (build_root / "dist" / "itk_core-6.0.0-cp311-abi3.whl").touch() + post_build_cleanup(build_root, "x64", tmp_path, "") + assert (build_root / "dist" / "itk_core-6.0.0-cp311-abi3.whl").exists() + + def test_cleanup_selects_build_dirs_and_archives(tmp_path: Path) -> None: (tmp_path / "build").mkdir() (tmp_path / "dist").mkdir() From 690fd2823b2f3c736e38d9fb2bf4068d5cfb039e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:49:23 -0500 Subject: [PATCH 18/23] BUG: Derive the ITK version without looking past the ITK tree sync_itk_source runs git with GIT_CEILING_DIRECTORIES set to the ITK tree's parent, so a tree restored from a cache, whose .git is empty, is used as it is. compute_itk_package_version then ran git with the plain environment: inside another checkout, such as a module or ITKPythonPackage clone, git found that repository, fetched its tags, checked out the ITK tag there, and named the wheels after its "git describe" if that worked. Give the version derivation the same environment, so such a tree gets the error that asks for --itk-package-version. --- scripts/build_wheels.py | 2 +- tests/test_itk_source_without_git.py | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/scripts/build_wheels.py b/scripts/build_wheels.py index e3bdaac1..94a66eae 100755 --- a/scripts/build_wheels.py +++ b/scripts/build_wheels.py @@ -623,7 +623,7 @@ def sync_itk_source_tree(args: argparse.Namespace, ipp_dir: Path) -> None: # any other value is used as given, as a cache-restored tree has no repository. if derives_package_version(args.itk_package_version): args.itk_package_version = compute_itk_package_version( - args.itk_source_dir, args.itk_git_tag, os.environ + args.itk_source_dir, args.itk_git_tag, itk_git_env(args.itk_source_dir) ) diff --git a/tests/test_itk_source_without_git.py b/tests/test_itk_source_without_git.py index 2b91eb70..7ca78822 100644 --- a/tests/test_itk_source_without_git.py +++ b/tests/test_itk_source_without_git.py @@ -1,5 +1,6 @@ """A cache-restored ITK tree has no .git and must not abort the build.""" +import argparse import subprocess from collections.abc import Mapping, Sequence from pathlib import Path @@ -175,3 +176,15 @@ def not_a_repository( monkeypatch.setattr(wheel_builder_utils, "run_command", not_a_repository) with pytest.raises(RuntimeError, match="Pass --itk-package-version"): wheel_builder_utils.compute_itk_package_version(tmp_path, "v6.0.0", {}) + + +def test_version_derivation_ignores_an_enclosing_repository(tmp_path: Path) -> None: + """A cache-restored tree inside another checkout must not take its version.""" + subprocess.run(["git", "init", "--quiet", str(tmp_path)], check=True) + itk = tmp_path / "restored" / "ITK" + itk.mkdir(parents=True) + args = argparse.Namespace( + itk_source_dir=itk, itk_git_tag="v6.0.0", itk_package_version="gitauto" + ) + with pytest.raises(RuntimeError, match="Pass --itk-package-version"): + build_wheels.sync_itk_source_tree(args, tmp_path) From 5b3a5d531932db15941446c03f66041544ca001a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:50:15 -0500 Subject: [PATCH 19/23] BUG: Derive the ITK version from local tags when fetching fails sync_itk_source lets a build go on without network access when the requested ITK revision is already present, but compute_itk_package_version then ran "git fetch --tags" again and stopped the build when it failed. An offline build with the default --itk-package-version gitauto could therefore never start. Warn and describe the revision with the local tags instead. --- scripts/wheel_builder_utils.py | 7 +++++-- tests/test_wheel_builder_utils.py | 19 ++++++++++--------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/scripts/wheel_builder_utils.py b/scripts/wheel_builder_utils.py index abf460ed..2f96f3e9 100644 --- a/scripts/wheel_builder_utils.py +++ b/scripts/wheel_builder_utils.py @@ -435,8 +435,11 @@ def compute_itk_package_version( env=env, ) if fetch_result.returncode != 0: - msg = f"git fetch --tags failed in {itk_dir}: {fetch_result.stderr}" - raise RuntimeError(msg) + # Offline, the local tags still describe the revision sync_itk_source found. + print( + f"WARNING: git fetch --tags failed in {itk_dir}; describing the " + f"version with the local tags: {fetch_result.stderr}" + ) checkout_result = run_command( ["git", "checkout", itk_git_tag], cwd=itk_dir, diff --git a/tests/test_wheel_builder_utils.py b/tests/test_wheel_builder_utils.py index b7fc3a47..eee93a6f 100644 --- a/tests/test_wheel_builder_utils.py +++ b/tests/test_wheel_builder_utils.py @@ -113,22 +113,23 @@ def fake_run( assert version.startswith("6.0") -def test_compute_itk_package_version_raises_when_fetch_fails(tmp_path: Path) -> None: +def test_compute_itk_package_version_works_offline(tmp_path: Path) -> None: + """sync_itk_source accepts a failed fetch when the revision is present.""" + def fake_run( cmd: Sequence[str | Path], cwd: Path | None = None, env: Mapping[str, str] | None = None, check: bool = False, ) -> subprocess.CompletedProcess[str]: - if str(cmd[1]) == "rev-parse" and "--git-dir" in [str(c) for c in cmd]: - return _completed(0, ".git") - return _completed(1, "", "network down") + if str(cmd[1]) == "fetch": + return _completed(1, "", "network down") + if str(cmd[1]) == "describe": + return _completed(0, "v6.0.0-0-gabc1234") + return _completed(0, ".git") - with ( - patch.object(wheel_builder_utils, "run_command", fake_run), - pytest.raises(RuntimeError, match="git fetch"), - ): - compute_itk_package_version(tmp_path, "v6.0.0", {}) + with patch.object(wheel_builder_utils, "run_command", fake_run): + assert compute_itk_package_version(tmp_path, "v6.0.0", {}) == "6.0.0" def test_streamed_output_is_also_returned(capsys: pytest.CaptureFixture[str]) -> None: From fc4033824c5663d2bb4c37da906cf37ddf205834 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:52:03 -0500 Subject: [PATCH 20/23] BUG: Drop the compiler launcher when rebuilding ITK without the cache --use-compiler-cache sets CMAKE_C_COMPILER_LAUNCHER and CMAKE_CXX_COMPILER_LAUNCHER, and CMake keeps them in the build tree's cache. Rebuilding that tree with --no-use-compiler-cache set nothing, so the compiles still went through ccache or sccache. When the ITK build runs without the cache, set both launchers to empty and ITK_USE_CCACHE to OFF. A module build on a cached tree, which skips the ITK build, leaves them as they are: clearing them would only make the superbuild rebuild oneTBB, which gets the launcher too. --- scripts/build_python_instance_base.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/scripts/build_python_instance_base.py b/scripts/build_python_instance_base.py index d48d0579..c7091ed3 100644 --- a/scripts/build_python_instance_base.py +++ b/scripts/build_python_instance_base.py @@ -291,6 +291,11 @@ def __init__( cache_exe, compiler_cache_max_size(cache_tool, os.environ), ) + elif not self.skip_itk_build: + # A reused ITK build tree keeps the launcher an earlier build cached. + self.cmake_compiler_configurations.update( + compiler_cache_definitions("", "") + ) user_defs = self.cmake_cmdline_definitions flag_defs = self.compiler_flag_definitions(user_defs, compile_roots) From ee4822e4d8cba722d2f5b6e2933ad21593b82bd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:53:22 -0500 Subject: [PATCH 21/23] BUG: Default --platform-env to the active manylinux pixi environment Without --platform-env, build_wheels.py used get_default_platform_build(), which spells the manylinux228-py311 environment manylinux_2_28-py311, the form the tarball names need. The environment guard then compared that with PIXI_ENVIRONMENT_NAME and aborted the build with "WRONG ENVIRONMENT" inside the very environment it asks for. Default to the active environment's own name when one is active. --- scripts/build_wheels.py | 7 ++++++- tests/test_cmake_define_args.py | 13 ++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/scripts/build_wheels.py b/scripts/build_wheels.py index 94a66eae..af5be74a 100755 --- a/scripts/build_wheels.py +++ b/scripts/build_wheels.py @@ -310,9 +310,14 @@ def build_argument_parser(os_name: OS, ipp_dir: Path) -> argparse.ArgumentParser parser = argparse.ArgumentParser( description="Driver script to build ITK Python wheels." ) + # The environment guard requires the active pixi environment itself, which + # get_default_platform_build renames for manylinux. + default_env = os.environ.get("PIXI_ENVIRONMENT_NAME", "") + if "-" not in default_env: + default_env = get_default_platform_build("py311") parser.add_argument( "--platform-env", - default=get_default_platform_build("py311"), + default=default_env, help=( """A platform environment name or path: linux-py311, diff --git a/tests/test_cmake_define_args.py b/tests/test_cmake_define_args.py index 0ed8fc4a..708bf80e 100644 --- a/tests/test_cmake_define_args.py +++ b/tests/test_cmake_define_args.py @@ -1,9 +1,11 @@ import argparse from collections.abc import Sequence +from pathlib import Path import pytest -from build_wheels import parse_args_with_cmake_defines +from build_wheels import build_argument_parser, parse_args_with_cmake_defines from cmake_argument_builder import definitions_from_cmake_options +from target_platform import OS def _parser(default: Sequence[str] = ()) -> argparse.ArgumentParser: @@ -78,3 +80,12 @@ def test_options_that_are_not_definitions_are_refused(option: str) -> None: """Anything but a ``-D=`` definition is an error.""" with pytest.raises(ValueError, match="not a -D= definition"): definitions_from_cmake_options(["-DA:BOOL=ON", option]) + + +def test_the_default_platform_env_is_the_active_manylinux_environment( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The environment guard requires exactly the active environment.""" + monkeypatch.setenv("PIXI_ENVIRONMENT_NAME", "manylinux228-py311") + args = build_argument_parser(OS.LINUX, Path("IPP")).parse_args([]) + assert args.platform_env == "manylinux228-py311" From 23db78b681ac618066c3b3950e192c10a5aa538a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 11:54:02 -0500 Subject: [PATCH 22/23] BUG: Keep the backslashes of Windows paths in CMAKE_OPTIONS The CMAKE_OPTIONS environment variable is split with shlex, which takes a backslash outside quotes for an escape character, so on Windows CMAKE_OPTIONS="-DFOO_DIR=C:\deps\foo" reached CMake as -DFOO_DIR=C:depsfoo. On Windows, double each backslash before splitting, so that the split keeps it. --- scripts/build_wheels.py | 3 +++ tests/test_cmake_define_args.py | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/scripts/build_wheels.py b/scripts/build_wheels.py index af5be74a..c09ebb79 100755 --- a/scripts/build_wheels.py +++ b/scripts/build_wheels.py @@ -356,6 +356,9 @@ def build_argument_parser(os_name: OS, ipp_dir: Path) -> argparse.ArgumentParser ), ) _cmake_options_default = remote_module_build_dict["CMAKE_OPTIONS"] + if os_name is OS.WINDOWS: + # shlex takes a backslash for an escape; keep those of Windows paths. + _cmake_options_default = _cmake_options_default.replace("\\", "\\\\") parser.add_argument( "cmake_options", nargs="*", diff --git a/tests/test_cmake_define_args.py b/tests/test_cmake_define_args.py index 708bf80e..d9b5ce7f 100644 --- a/tests/test_cmake_define_args.py +++ b/tests/test_cmake_define_args.py @@ -89,3 +89,11 @@ def test_the_default_platform_env_is_the_active_manylinux_environment( monkeypatch.setenv("PIXI_ENVIRONMENT_NAME", "manylinux228-py311") args = build_argument_parser(OS.LINUX, Path("IPP")).parse_args([]) assert args.platform_env == "manylinux228-py311" + + +def test_windows_cmake_options_keep_their_backslashes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("CMAKE_OPTIONS", r'-DA_DIR=C:\deps\a "-DB_DIR=C:\b c"') + args = build_argument_parser(OS.WINDOWS, Path("IPP")).parse_args([]) + assert args.cmake_options == [r"-DA_DIR=C:\deps\a", r"-DB_DIR=C:\b c"] From b53f9e0da76070f7817ae4ae3c73cd16bf5a3670 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C5=BEenan=20Zuki=C4=87?= Date: Tue, 24 Nov 2026 15:33:50 -0500 Subject: [PATCH 23/23] BUG: Name a module wheel's init file after its wrapped module ITK loads itk/__init___.py using the module name from itk/Configuration/Config.py, which need not match the distribution name: itk-vkfft wraps VkFFTBackend. Deriving the name from the distribution gave __init_vkfft__.py, so ITK never ran the DLL search setup delvewheel adds on Windows. Take the name from the wheel's Configuration member, keeping the distribution name as a fallback. --- scripts/module_wheel_init.py | 8 +++++++- tests/test_module_wheel_init.py | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/module_wheel_init.py b/scripts/module_wheel_init.py index 7918ed30..10cc078e 100644 --- a/scripts/module_wheel_init.py +++ b/scripts/module_wheel_init.py @@ -9,6 +9,7 @@ from __future__ import annotations import email.parser +import re import zipfile from typing import TYPE_CHECKING @@ -16,12 +17,17 @@ from pathlib import Path ITK_INIT = "itk/__init__.py" +_CONFIG = re.compile(r"^itk/Configuration/(?P[^/]+)Config\.py$") def module_init_name(wheel: Path) -> str: """Return the ``itk/__init___.py`` member ITK runs for *wheel*.""" with zipfile.ZipFile(wheel) as zf: - metadata = next(n for n in zf.namelist() if n.endswith(".dist-info/METADATA")) + names = zf.namelist() + modules = sorted(m["module"] for n in names if (m := _CONFIG.match(n))) + if modules: + return f"itk/__init_{modules[0].lower()}__.py" + metadata = next(n for n in names if n.endswith(".dist-info/METADATA")) name = email.parser.Parser().parsestr(zf.read(metadata).decode())["Name"] module = name.lower().removeprefix("itk-").split("-")[0] return f"itk/__init_{module}__.py" diff --git a/tests/test_module_wheel_init.py b/tests/test_module_wheel_init.py index 12bda623..1aa8d979 100644 --- a/tests/test_module_wheel_init.py +++ b/tests/test_module_wheel_init.py @@ -20,13 +20,19 @@ def _wheel(path: Path, name: str, members: dict[str, str]) -> Path: return path -def test_the_init_name_comes_from_the_distribution_name(tmp_path: Path) -> None: +def test_the_init_name_falls_back_to_the_distribution_name(tmp_path: Path) -> None: wheel = _wheel(tmp_path / "w.whl", "itk-RTK", {}) assert module_init_name(wheel) == "itk/__init_rtk__.py" wheel = _wheel(tmp_path / "x.whl", "itk-foo-bar", {}) assert module_init_name(wheel) == "itk/__init_foo__.py" +def test_the_init_name_comes_from_the_wrapped_module(tmp_path: Path) -> None: + config = {"itk/Configuration/VkFFTBackendConfig.py": "depends = ()\n"} + wheel = _wheel(tmp_path / "w.whl", "itk-vkfft", config) + assert module_init_name(wheel) == "itk/__init_vkfftbackend__.py" + + def test_a_rename_moves_the_member_and_its_record_line(tmp_path: Path) -> None: wheel = _wheel(tmp_path / "w.whl", "itk-a", {"itk/__init__.py": "x = 1\n"}) assert rename_wheel_member(wheel, "itk/__init__.py", "itk/__init_a__.py")