diff --git a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/load_nvidia_dynamic_lib.py b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/load_nvidia_dynamic_lib.py index 02184a07cd4..049d44d5a96 100644 --- a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/load_nvidia_dynamic_lib.py +++ b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/load_nvidia_dynamic_lib.py @@ -18,6 +18,7 @@ load_dependencies, ) from cuda.pathfinder._dynamic_libs.platform_loader import LOADER +from cuda.pathfinder._dynamic_libs.search_platform import search_context from cuda.pathfinder._dynamic_libs.search_steps import ( EARLY_FIND_STEPS, LATE_FIND_STEPS, @@ -163,7 +164,7 @@ def _load_lib_no_cache(libname: str) -> LoadedDL: if libname in _DRIVER_ONLY_LIBNAMES: return _load_driver_lib_no_cache(desc) - ctx = SearchContext(desc) + ctx = search_context(desc) # An already-loaded library bypasses the wheel and conda search. loaded = LOADER.check_if_already_loaded_from_elsewhere(desc) diff --git a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py index 6c73ffc136c..8ac3643c790 100644 --- a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py +++ b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py @@ -1,11 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Platform abstraction for filesystem search steps. +"""Platform-specific rules for filesystem search steps. The goal is to keep :mod:`search_steps` platform-agnostic: it should not branch -on OS flags like ``IS_WINDOWS``. Instead, it calls through the single -``PLATFORM`` instance exported here. +on OS flags like ``IS_WINDOWS``. Instead, it works on a :class:`SearchContext` +that this module resolves for the target platform. """ from __future__ import annotations @@ -14,9 +14,10 @@ from collections.abc import Sequence from dataclasses import dataclass, field from pathlib import PurePath -from typing import Protocol, cast +from typing import NoReturn from cuda.pathfinder._dynamic_libs.lib_descriptor import LibDescriptor +from cuda.pathfinder._dynamic_libs.load_dl_common import DynamicLibNotFoundError from cuda.pathfinder._dynamic_libs.supported_nvidia_libs import is_suppressed_dll_file from cuda.pathfinder._utils.find_sub_dirs import find_sub_dirs_all_sitepackages from cuda.pathfinder._utils.platform_aware import IS_WINDOWS @@ -52,6 +53,17 @@ class SearchContext: def conda_anchor_point(self, conda_prefix: str) -> str: return os.path.join(conda_prefix, *self.conda_anchor_parts) + def program_files_root_globs(self) -> tuple[str, ...]: + program_files = os.environ.get("PROGRAMW6432") or os.environ.get("PROGRAMFILES") + if not program_files: + return () + return tuple(os.path.join(program_files, rel_glob) for rel_glob in self.program_files_rel_globs) + + def raise_not_found(self) -> NoReturn: + err = ", ".join(self.error_messages) + att = "\n".join(self.attachments) + raise DynamicLibNotFoundError(f'Failure finding "{self.lib_searched_for}": {err}\n{att}') + def linux_search_context(desc: LibDescriptor) -> SearchContext: return SearchContext( @@ -111,26 +123,6 @@ def _find_descriptor_so_under_dir(dirpath: str, desc: LibDescriptor) -> str | No return None -def _find_so_in_rel_dirs( - rel_dirs: tuple[str, ...], - desc: LibDescriptor, - file_description: str, - error_messages: list[str], - attachments: list[str], -) -> str | None: - sub_dirs_searched: list[tuple[str, ...]] = [] - for rel_dir in rel_dirs: - sub_dir = PurePath(rel_dir).parts - for abs_dir in find_sub_dirs_all_sitepackages(sub_dir): - so_path = _find_descriptor_so_under_dir(abs_dir, desc) - if so_path is not None: - return so_path - sub_dirs_searched.append(sub_dir) - for sub_dir in sub_dirs_searched: - _no_such_file_in_sub_dirs(sub_dir, file_description, error_messages, attachments) - return None - - def _find_descriptor_dll_under_dir( dirpath: str, desc: LibDescriptor, @@ -150,190 +142,39 @@ def candidate_is_usable(path: str) -> bool: return None -def _find_dll_in_rel_dirs( - rel_dirs: tuple[str, ...], - desc: LibDescriptor, - target_arch: str, - lib_searched_for: str, - error_messages: list[str], - attachments: list[str], -) -> str | None: +def _find_lib_file(ctx: SearchContext, dirpath: str) -> str | None: + """Return the first library file under *dirpath* that the target platform accepts.""" + if ctx.windows_arch is None: + return _find_descriptor_so_under_dir(dirpath, ctx.desc) + return _find_descriptor_dll_under_dir(dirpath, ctx.desc, ctx.pe_arch_to_check) + + +def find_lib_in_site_packages(ctx: SearchContext) -> str | None: sub_dirs_searched: list[tuple[str, ...]] = [] - checked_arch = target_arch if desc.requires_windows_binary_arch_check else None - for rel_dir in rel_dirs: + for rel_dir in ctx.site_packages_rel_dirs: sub_dir = PurePath(rel_dir).parts for abs_dir in find_sub_dirs_all_sitepackages(sub_dir): - dll_name = _find_descriptor_dll_under_dir(abs_dir, desc, checked_arch) - if dll_name is not None: - return dll_name + lib_path = _find_lib_file(ctx, abs_dir) + if lib_path is not None: + return lib_path sub_dirs_searched.append(sub_dir) for sub_dir in sub_dirs_searched: - _no_such_file_in_sub_dirs(sub_dir, lib_searched_for, error_messages, attachments) + _no_such_file_in_sub_dirs(sub_dir, ctx.lib_searched_for, ctx.error_messages, ctx.attachments) return None -class SearchPlatform(Protocol): - def lib_searched_for(self, desc: LibDescriptor) -> str: ... - - def site_packages_rel_dirs(self, desc: LibDescriptor) -> tuple[str, ...]: ... - - def conda_anchor_point(self, conda_prefix: str) -> str: ... - - def anchor_rel_dirs(self, desc: LibDescriptor) -> tuple[str, ...]: ... - - def install_root_env_vars(self, desc: LibDescriptor) -> tuple[str, ...]: ... - - def install_root_env_rel_dirs(self, desc: LibDescriptor) -> tuple[str, ...]: ... - - def program_files_root_globs(self, desc: LibDescriptor) -> tuple[str, ...]: ... - - def find_in_site_packages( - self, - rel_dirs: tuple[str, ...], - desc: LibDescriptor, - error_messages: list[str], - attachments: list[str], - ) -> str | None: ... - - def find_in_lib_dir( - self, - lib_dir: str, - desc: LibDescriptor, - error_messages: list[str], - attachments: list[str], - ) -> str | None: ... - - -@dataclass(frozen=True, slots=True) -class LinuxSearchPlatform: - def lib_searched_for(self, desc: LibDescriptor) -> str: - return " or ".join(desc.linux_sonames) - - def site_packages_rel_dirs(self, desc: LibDescriptor) -> tuple[str, ...]: - return cast(tuple[str, ...], desc.site_packages_linux) - - def conda_anchor_point(self, conda_prefix: str) -> str: - return conda_prefix - - def anchor_rel_dirs(self, desc: LibDescriptor) -> tuple[str, ...]: - return cast(tuple[str, ...], desc.anchor_rel_dirs_linux) - - def install_root_env_vars(self, desc: LibDescriptor) -> tuple[str, ...]: - return cast(tuple[str, ...], desc.install_root_env_vars_linux) - - def install_root_env_rel_dirs(self, desc: LibDescriptor) -> tuple[str, ...]: - return cast(tuple[str, ...], desc.install_root_env_rel_dirs_linux) - - def program_files_root_globs(self, _desc: LibDescriptor) -> tuple[str, ...]: - return () - - def find_in_site_packages( - self, - rel_dirs: tuple[str, ...], - desc: LibDescriptor, - error_messages: list[str], - attachments: list[str], - ) -> str | None: - return _find_so_in_rel_dirs(rel_dirs, desc, self.lib_searched_for(desc), error_messages, attachments) - - def find_in_lib_dir( - self, - lib_dir: str, - desc: LibDescriptor, - error_messages: list[str], - attachments: list[str], - ) -> str | None: - so_path = _find_descriptor_so_under_dir(lib_dir, desc) - if so_path is not None: - return so_path - error_messages.append(f"No such file: {self.lib_searched_for(desc)}") - attachments.append(f' listdir("{lib_dir}"):') - if not os.path.isdir(lib_dir): - attachments.append(" DIRECTORY DOES NOT EXIST") - else: - for node in sorted(os.listdir(lib_dir)): - attachments.append(f" {node}") - return None - - -@dataclass(frozen=True, slots=True) -class WindowsSearchPlatform: - target_arch: str - - def lib_searched_for(self, desc: LibDescriptor) -> str: - return f"known {desc.name} DLL" - - def site_packages_rel_dirs(self, desc: LibDescriptor) -> tuple[str, ...]: - return cast(tuple[str, ...], desc.site_packages_windows.for_arch(self.target_arch)) - - def conda_anchor_point(self, conda_prefix: str) -> str: - return os.path.join(conda_prefix, "Library") - - def anchor_rel_dirs(self, desc: LibDescriptor) -> tuple[str, ...]: - return cast(tuple[str, ...], desc.anchor_rel_dirs_windows.for_arch(self.target_arch)) - - def install_root_env_vars(self, desc: LibDescriptor) -> tuple[str, ...]: - if self.target_arch not in desc.supported_windows_arch: - return () - return cast(tuple[str, ...], desc.install_root_env_vars_windows) - - def install_root_env_rel_dirs(self, desc: LibDescriptor) -> tuple[str, ...]: - if self.target_arch not in desc.supported_windows_arch: - return () - return cast(tuple[str, ...], desc.install_root_env_rel_dirs_windows.for_arch(self.target_arch)) - - def program_files_root_globs(self, desc: LibDescriptor) -> tuple[str, ...]: - program_files = os.environ.get("PROGRAMW6432") or os.environ.get("PROGRAMFILES") - if not program_files: - return () - rel_globs = desc.program_files_root_globs_windows.for_arch(self.target_arch) - return tuple(os.path.join(program_files, rel_glob) for rel_glob in rel_globs) - - def find_in_site_packages( - self, - rel_dirs: tuple[str, ...], - desc: LibDescriptor, - error_messages: list[str], - attachments: list[str], - ) -> str | None: - return _find_dll_in_rel_dirs( - rel_dirs, - desc, - self.target_arch, - self.lib_searched_for(desc), - error_messages, - attachments, - ) - - def find_in_lib_dir( - self, - lib_dir: str, - desc: LibDescriptor, - error_messages: list[str], - attachments: list[str], - ) -> str | None: - target_arch = self.target_arch if desc.requires_windows_binary_arch_check else None - dll_name = _find_descriptor_dll_under_dir(lib_dir, desc, target_arch) - if dll_name is not None: - return dll_name - lib_searched_for = self.lib_searched_for(desc) - if target_arch is None: - error_messages.append(f"No such file: {lib_searched_for}") - else: - error_messages.append(f"No {target_arch}-compatible PE file: {lib_searched_for}") - attachments.append(f' listdir("{lib_dir}"):') - if not os.path.isdir(lib_dir): - attachments.append(" DIRECTORY DOES NOT EXIST") - else: - for node in sorted(os.listdir(lib_dir)): - attachments.append(f" {node}") - return None - - -def _platform_for_current_system() -> SearchPlatform: - if IS_WINDOWS: - return WindowsSearchPlatform(target_arch=windows_python_arch()) - return LinuxSearchPlatform() - - -PLATFORM = _platform_for_current_system() +def find_lib_in_dir(ctx: SearchContext, lib_dir: str) -> str | None: + lib_path = _find_lib_file(ctx, lib_dir) + if lib_path is not None: + return lib_path + if ctx.pe_arch_to_check is None: + ctx.error_messages.append(f"No such file: {ctx.lib_searched_for}") + else: + ctx.error_messages.append(f"No {ctx.pe_arch_to_check}-compatible PE file: {ctx.lib_searched_for}") + ctx.attachments.append(f' listdir("{lib_dir}"):') + if not os.path.isdir(lib_dir): + ctx.attachments.append(" DIRECTORY DOES NOT EXIST") + else: + for node in sorted(os.listdir(lib_dir)): + ctx.attachments.append(f" {node}") + return None diff --git a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py index 4e8c7a93b9d..ba412274cbb 100644 --- a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py +++ b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py @@ -15,19 +15,20 @@ step or strategy only requires adding a function and a tuple entry. This module is intentionally platform-agnostic: it does not branch on the -current operating system. Platform differences are routed through the -:data:`~cuda.pathfinder._dynamic_libs.search_platform.PLATFORM` instance. +current operating system. Platform differences are resolved up front into the +:class:`~cuda.pathfinder._dynamic_libs.search_platform.SearchContext`. """ import glob import os from collections.abc import Callable, Iterator -from dataclasses import dataclass, field -from typing import NoReturn, cast +from dataclasses import dataclass -from cuda.pathfinder._dynamic_libs.lib_descriptor import LibDescriptor -from cuda.pathfinder._dynamic_libs.load_dl_common import DynamicLibNotFoundError -from cuda.pathfinder._dynamic_libs.search_platform import PLATFORM, SearchPlatform +from cuda.pathfinder._dynamic_libs.search_platform import ( + SearchContext, + find_lib_in_dir, + find_lib_in_site_packages, +) from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home from cuda.pathfinder._utils.path_sort import numeric_aware_path_sort_key @@ -46,25 +47,6 @@ class FindResult: found_via: str -@dataclass -class SearchContext: - """Mutable state accumulated during the search cascade.""" - - desc: LibDescriptor - platform: SearchPlatform = PLATFORM - error_messages: list[str] = field(default_factory=list) - attachments: list[str] = field(default_factory=list) - - @property - def lib_searched_for(self) -> str: - return cast(str, self.platform.lib_searched_for(self.desc)) - - def raise_not_found(self) -> NoReturn: - err = ", ".join(self.error_messages) - att = "\n".join(self.attachments) - raise DynamicLibNotFoundError(f'Failure finding "{self.lib_searched_for}": {err}\n{att}') - - #: Type alias for a find step callable. FindStep = Callable[[SearchContext], FindResult | None] @@ -77,21 +59,6 @@ def _iter_lib_dirs(root: str, rel_dirs: tuple[str, ...]) -> Iterator[str]: yield str(resolve_path(dirname)) -def _find_using_lib_dir(ctx: SearchContext, lib_dir: str | None) -> str | None: - """Find a library file in a resolved lib directory.""" - if lib_dir is None: - return None - return cast( - str | None, - ctx.platform.find_in_lib_dir( - lib_dir, - ctx.desc, - ctx.error_messages, - ctx.attachments, - ), - ) - - def _find_under_root( ctx: SearchContext, root: str, @@ -100,7 +67,7 @@ def _find_under_root( ) -> FindResult | None: """Resolve *rel_dirs* under *root*, then find the requested library.""" for lib_dir in _iter_lib_dirs(root, rel_dirs): - abs_path = _find_using_lib_dir(ctx, lib_dir) + abs_path = find_lib_in_dir(ctx, lib_dir) if abs_path is not None: return FindResult(abs_path, found_via) return None @@ -108,7 +75,7 @@ def _find_under_root( def _find_under_anchor_root(ctx: SearchContext, root: str, found_via: str) -> FindResult | None: """Resolve the descriptor's general anchors under *root*.""" - return _find_under_root(ctx, root, ctx.platform.anchor_rel_dirs(ctx.desc), found_via) + return _find_under_root(ctx, root, ctx.anchor_rel_dirs, found_via) def _derive_ctk_root_linux(resolved_lib_path: str) -> str | None: @@ -172,15 +139,9 @@ def find_via_ctk_root(ctx: SearchContext, ctk_root: str) -> FindResult | None: def find_in_site_packages(ctx: SearchContext) -> FindResult | None: """Search pip wheel install locations.""" - rel_dirs = ctx.platform.site_packages_rel_dirs(ctx.desc) - if not rel_dirs: + if not ctx.site_packages_rel_dirs: return None - abs_path = ctx.platform.find_in_site_packages( - rel_dirs, - ctx.desc, - ctx.error_messages, - ctx.attachments, - ) + abs_path = find_lib_in_site_packages(ctx) if abs_path is not None: return FindResult(abs_path, "site-packages") return None @@ -191,14 +152,14 @@ def find_in_conda(ctx: SearchContext) -> FindResult | None: conda_prefix = os.environ.get("CONDA_PREFIX") if not conda_prefix: return None - anchor = ctx.platform.conda_anchor_point(conda_prefix) + anchor = ctx.conda_anchor_point(conda_prefix) return _find_under_anchor_root(ctx, anchor, "conda") def find_in_install_root_env_vars(ctx: SearchContext) -> FindResult | None: """Search installation roots named by descriptor-specific environment variables.""" - rel_dirs = ctx.platform.install_root_env_rel_dirs(ctx.desc) - for env_var in ctx.platform.install_root_env_vars(ctx.desc): + rel_dirs = ctx.install_root_env_rel_dirs + for env_var in ctx.install_root_env_vars: root = os.environ.get(env_var) if not root: continue @@ -227,7 +188,7 @@ def find_in_cuda_path(ctx: SearchContext) -> FindResult | None: def find_in_program_files_roots(ctx: SearchContext) -> FindResult | None: """Search descriptor-configured installation roots under Program Files.""" - for root_glob in ctx.platform.program_files_root_globs(ctx.desc): + for root_glob in ctx.program_files_root_globs(): for root in sorted(glob.glob(root_glob), key=numeric_aware_path_sort_key, reverse=True): if not os.path.isdir(root): continue diff --git a/cuda_pathfinder/tests/test_ctk_root_discovery.py b/cuda_pathfinder/tests/test_ctk_root_discovery.py index cac4343e3cb..2e96bebade2 100644 --- a/cuda_pathfinder/tests/test_ctk_root_discovery.py +++ b/cuda_pathfinder/tests/test_ctk_root_discovery.py @@ -20,7 +20,11 @@ _try_ctk_root_canary, resolve_ctk_root_via_canary, ) -from cuda.pathfinder._dynamic_libs.search_platform import WindowsSearchPlatform +from cuda.pathfinder._dynamic_libs.search_platform import ( + linux_search_context, + search_context, + windows_search_context, +) from cuda.pathfinder._dynamic_libs.search_steps import ( SearchContext, _derive_ctk_root_linux, @@ -42,7 +46,7 @@ def _ctx(libname: str = "nvvm") -> SearchContext: - return SearchContext(LIB_DESCRIPTORS[libname]) + return search_context(LIB_DESCRIPTORS[libname]) @pytest.fixture(autouse=True) @@ -221,7 +225,7 @@ def test_try_via_ctk_root_windows_arm64_prefers_arch_dir(tmp_path): arm64_lib = arm64_dir / "cudart64_13.dll" arm64_lib.write_bytes(b"fake") - ctx = SearchContext(LIB_DESCRIPTORS["cudart"], platform=WindowsSearchPlatform(target_arch="arm64")) + ctx = windows_search_context(LIB_DESCRIPTORS["cudart"], "arm64") result = find_via_ctk_root(ctx, str(ctk_root)) assert result is not None assert result.abs_path == str(arm64_lib) @@ -536,3 +540,53 @@ def test_non_discoverable_lib_skips_canary_probe(mocker): _load_lib_no_cache("cublas") canary_probe.assert_not_called() + + +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_not_found_error_lists_every_miss_in_search_order(tmp_path, mocker): + """Pin the whole error text: early steps, then late steps, then the canary root.""" + desc = LIB_DESCRIPTORS["nvvm"] + searched = " or ".join(desc.linux_sonames) + + def searched_dir(root, rel_dir): + lib_dir = root.joinpath(*rel_dir.split("/")) + lib_dir.mkdir(parents=True) + (lib_dir / "unrelated.txt").touch() + return lib_dir + + wheel_root = tmp_path / "site-packages" + wheel_dir = searched_dir(wheel_root, desc.site_packages_linux[0]) + conda_dir = searched_dir(tmp_path / "conda", desc.anchor_rel_dirs_linux[0]) + cuda_dir = searched_dir(tmp_path / "cuda", desc.anchor_rel_dirs_linux[0]) + canary_root = tmp_path / "cuda-system" + canary_dir = searched_dir(canary_root, desc.anchor_rel_dirs_linux[0]) + + def find_wheel_dirs(sub_dirs): + path = wheel_root.joinpath(*sub_dirs) + return [str(path)] if path.is_dir() else [] + + mocker.patch( + "cuda.pathfinder._dynamic_libs.search_platform.find_sub_dirs_all_sitepackages", + side_effect=find_wheel_dirs, + ) + mocker.patch(f"{_MODULE}.search_context", return_value=linux_search_context(desc)) + mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path / "conda")}) + mocker.patch(f"{_STEPS_MODULE}.get_cuda_path_or_home", return_value=str(tmp_path / "cuda")) + mocker.patch.object(load_mod.LOADER, "check_if_already_loaded_from_elsewhere", return_value=None) + mocker.patch(f"{_MODULE}.load_dependencies") + mocker.patch.object(load_mod.LOADER, "load_with_system_search", return_value=None) + mocker.patch( + f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", + return_value=str(canary_root / "lib64" / "libcudart.so.13"), + ) + + with pytest.raises(DynamicLibNotFoundError) as exc_info: + _load_lib_no_cache("nvvm") + + # One message per site-packages directory tried, then one per directory searched after that. + messages = [f"No such file: {searched}"] * (len(desc.site_packages_linux) + 3) + listings = [ + f' listdir("{searched_in}"):\n unrelated.txt' + for searched_in in (wheel_dir, conda_dir.resolve(), cuda_dir.resolve(), canary_dir.resolve()) + ] + assert str(exc_info.value) == f'Failure finding "{searched}": ' + ", ".join(messages) + "\n" + "\n".join(listings) diff --git a/cuda_pathfinder/tests/test_load_nvidia_dynamic_lib_using_mocker.py b/cuda_pathfinder/tests/test_load_nvidia_dynamic_lib_using_mocker.py index 91c15533bfb..801e770497a 100644 --- a/cuda_pathfinder/tests/test_load_nvidia_dynamic_lib_using_mocker.py +++ b/cuda_pathfinder/tests/test_load_nvidia_dynamic_lib_using_mocker.py @@ -12,8 +12,8 @@ _load_lib_no_cache, _resolve_system_loaded_abs_path_in_subprocess, ) -from cuda.pathfinder._dynamic_libs.search_platform import WindowsSearchPlatform -from cuda.pathfinder._dynamic_libs.search_steps import EARLY_FIND_STEPS, SearchContext +from cuda.pathfinder._dynamic_libs.search_platform import search_context, windows_search_context +from cuda.pathfinder._dynamic_libs.search_steps import EARLY_FIND_STEPS from cuda.pathfinder._utils.platform_aware import IS_WINDOWS _MODULE = "cuda.pathfinder._dynamic_libs.load_nvidia_dynamic_lib" @@ -65,8 +65,8 @@ def test_cudnn_arm64_archive_layout_reaches_loader(tmp_path, mocker, monkeypatch mocker.patch("cuda.pathfinder._dynamic_libs.search_platform.windows_pe_matches_arch", return_value=True) desc = load_mod.LIB_DESCRIPTORS["cudnn"] - ctx = SearchContext(desc, platform=WindowsSearchPlatform(target_arch="arm64")) - mocker.patch(f"{_MODULE}.SearchContext", return_value=ctx) + ctx = windows_search_context(desc, "arm64") + mocker.patch(f"{_MODULE}.search_context", return_value=ctx) mocker.patch.object(load_mod.LOADER, "check_if_already_loaded_from_elsewhere", return_value=None) def _load_dependency(name): @@ -175,7 +175,7 @@ def _run_find_steps_disabled(ctx, steps): @pytest.mark.agent_authored(model="gpt-6.1-sol") def test_cuda_path_is_a_fallback_to_environment_and_native_search(tmp_path, mocker, monkeypatch, preferred_source): desc = load_mod.LIB_DESCRIPTORS["cublasLt"] - platform = steps_mod.PLATFORM + search_inputs = search_context(desc) filename = desc.windows_dlls[0] if IS_WINDOWS else desc.linux_sonames[0] def create_library(root, relative_dir): @@ -185,19 +185,19 @@ def create_library(root, relative_dir): return path cuda_root = tmp_path / "toolkit" - create_library(cuda_root, platform.anchor_rel_dirs(desc)[0]) + create_library(cuda_root, search_inputs.anchor_rel_dirs[0]) mocker.patch(f"{_STEPS_MODULE}.get_cuda_path_or_home", return_value=str(cuda_root)) conda_root = tmp_path / "conda" - conda_anchor = Path(platform.conda_anchor_point(str(conda_root))) - conda_path = create_library(conda_anchor, platform.anchor_rel_dirs(desc)[0]) + conda_anchor = Path(search_inputs.conda_anchor_point(str(conda_root))) + conda_path = create_library(conda_anchor, search_inputs.anchor_rel_dirs[0]) if preferred_source == "system-search": monkeypatch.delenv("CONDA_PREFIX", raising=False) else: monkeypatch.setenv("CONDA_PREFIX", str(conda_root)) wheel_root = tmp_path / "wheels" - wheel_path = create_library(wheel_root, platform.site_packages_rel_dirs(desc)[0]) + wheel_path = create_library(wheel_root, search_inputs.site_packages_rel_dirs[0]) def find_wheel_dirs(sub_dirs): directory = wheel_root.joinpath(*sub_dirs) diff --git a/cuda_pathfinder/tests/test_search_steps.py b/cuda_pathfinder/tests/test_search_steps.py index fe90c61d48f..379e5fe64c0 100644 --- a/cuda_pathfinder/tests/test_search_steps.py +++ b/cuda_pathfinder/tests/test_search_steps.py @@ -17,8 +17,6 @@ from cuda.pathfinder._dynamic_libs.lib_descriptor import LIB_DESCRIPTORS, LibDescriptor from cuda.pathfinder._dynamic_libs.load_dl_common import DynamicLibNotFoundError from cuda.pathfinder._dynamic_libs.search_platform import ( - LinuxSearchPlatform, - WindowsSearchPlatform, _find_descriptor_dll_under_dir, linux_search_context, windows_search_context, @@ -62,10 +60,11 @@ def _make_desc(name: str = "cudart", **overrides) -> LibDescriptor: return LibDescriptor(**defaults) -def _ctx(desc: LibDescriptor | None = None, *, platform=None) -> SearchContext: - if platform is None: - platform = LinuxSearchPlatform() - return SearchContext(desc or _make_desc(), platform=platform) +def _ctx(desc: LibDescriptor | None = None, *, windows_arch: str | None = None) -> SearchContext: + desc = desc or _make_desc() + if windows_arch is None: + return linux_search_context(desc) + return windows_search_context(desc, windows_arch) def _patch_site_packages_search(mocker, root): @@ -92,11 +91,11 @@ def _write_pe(path, machine): class TestSearchContext: def test_lib_searched_for_linux(self): - ctx = SearchContext(LIB_DESCRIPTORS["cublas"], platform=LinuxSearchPlatform()) + ctx = linux_search_context(LIB_DESCRIPTORS["cublas"]) assert ctx.lib_searched_for == "libcublas.so.13 or libcublas.so.12" def test_lib_searched_for_windows(self): - ctx = SearchContext(_make_desc(name="cublas"), platform=WindowsSearchPlatform(target_arch="x64")) + ctx = windows_search_context(_make_desc(name="cublas"), "x64") assert ctx.lib_searched_for == "known cublas DLL" def test_raise_not_found_includes_messages(self): @@ -123,9 +122,9 @@ def test_linux_platform_does_not_detect_windows_arch(self, mocker): mocker.patch.object(search_platform_mod, "IS_WINDOWS", False) get_windows_arch = mocker.patch.object(search_platform_mod, "windows_python_arch") - platform = search_platform_mod._platform_for_current_system() + ctx = search_platform_mod.search_context(_make_desc()) - assert isinstance(platform, LinuxSearchPlatform) + assert ctx.windows_arch is None get_windows_arch.assert_not_called() @pytest.mark.agent_authored(model="gpt-5") @@ -281,7 +280,7 @@ def test_found_linux(self, mocker, tmp_path): desc = _make_desc( site_packages_linux=(os.path.join("nvidia", "cuda_runtime", "lib"),), ) - result = find_in_site_packages(_ctx(desc, platform=LinuxSearchPlatform())) + result = find_in_site_packages(_ctx(desc)) assert result is not None assert result.abs_path == str(so_file) assert result.found_via == "site-packages" @@ -298,7 +297,7 @@ def test_nvvm_linux_wheel_accepts_declared_unversioned_filename(self, mocker, tm return_value=[str(lib_dir)], ) - result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["nvvm"], platform=LinuxSearchPlatform())) + result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["nvvm"])) assert result is not None assert result.abs_path == str(so_file) @@ -323,7 +322,7 @@ def test_found_windows(self, mocker, tmp_path): arm64=(os.path.join("nvidia", "cuda_runtime", "bin"),), ), ) - result = find_in_site_packages(_ctx(desc, platform=WindowsSearchPlatform(target_arch="x64"))) + result = find_in_site_packages(_ctx(desc, windows_arch="x64")) assert result is not None assert result.abs_path == str(dll) assert result.found_via == "site-packages" @@ -339,9 +338,7 @@ def test_windows_exact_names_reject_cudnn_sidecar(self, mocker, tmp_path): return_value=[str(bin_dir)], ) - result = find_in_site_packages( - _ctx(LIB_DESCRIPTORS["cudnn"], platform=WindowsSearchPlatform(target_arch="x64")) - ) + result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch="x64")) assert result is None @@ -356,9 +353,7 @@ def test_windows_matching_rejects_unlisted_cupti_name(self, mocker, tmp_path): return_value=[str(bin_dir)], ) - result = find_in_site_packages( - _ctx(LIB_DESCRIPTORS["cupti"], platform=WindowsSearchPlatform(target_arch="x64")) - ) + result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["cupti"], windows_arch="x64")) assert result is None @@ -408,7 +403,7 @@ def test_found_windows_arm64_prefers_cuda13_arch_dir_to_cuda12(self, mocker, tmp mocker.patch(f"{_PLAT_MOD}.is_suppressed_dll_file", return_value=False) desc = LIB_DESCRIPTORS["cudart"] - result = find_in_site_packages(_ctx(desc, platform=WindowsSearchPlatform(target_arch="arm64"))) + result = find_in_site_packages(_ctx(desc, windows_arch="arm64")) assert result is not None assert result.abs_path == str(arm64_dll) assert result.found_via == "site-packages" @@ -430,7 +425,7 @@ def test_found_windows_x64_prefers_cuda13_arch_dir_to_cuda12(self, mocker, tmp_p mocker.patch(f"{_PLAT_MOD}.is_suppressed_dll_file", return_value=False) desc = LIB_DESCRIPTORS["cudart"] - result = find_in_site_packages(_ctx(desc, platform=WindowsSearchPlatform(target_arch="x64"))) + result = find_in_site_packages(_ctx(desc, windows_arch="x64")) assert result is not None assert result.abs_path == str(x86_64_dll) assert result.found_via == "site-packages" @@ -446,7 +441,7 @@ def test_found_windows_x64_uses_cuda12_when_cuda13_is_absent(self, mocker, tmp_p mocker.patch(f"{_PLAT_MOD}.is_suppressed_dll_file", return_value=False) desc = LIB_DESCRIPTORS["cudart"] - result = find_in_site_packages(_ctx(desc, platform=WindowsSearchPlatform(target_arch="x64"))) + result = find_in_site_packages(_ctx(desc, windows_arch="x64")) assert result is not None assert result.abs_path == str(cuda12_dll) assert result.found_via == "site-packages" @@ -461,10 +456,10 @@ def test_found_windows_arm64_skips_cuda12_when_cuda13_is_absent(self, mocker, tm mocker.patch(f"{_PLAT_MOD}.is_suppressed_dll_file", return_value=False) desc = LIB_DESCRIPTORS["cudart"] - platform = WindowsSearchPlatform(target_arch="arm64") - assert platform.site_packages_rel_dirs(desc) == ("nvidia/cu13/bin/arm64",) + ctx = _ctx(desc, windows_arch="arm64") + assert ctx.site_packages_rel_dirs == ("nvidia/cu13/bin/arm64",) - result = find_in_site_packages(_ctx(desc, platform=platform)) + result = find_in_site_packages(ctx) assert result is None @@ -496,7 +491,7 @@ def test_cudnn_wheel_architecture_and_archive_fallback( desc = LIB_DESCRIPTORS["cudnn"] result = run_find_steps( - _ctx(desc, platform=WindowsSearchPlatform(target_arch=target_arch)), + _ctx(desc, windows_arch=target_arch), (find_in_site_packages, find_in_install_root_env_vars), ) @@ -512,7 +507,7 @@ def test_not_found_appends_error(self, mocker, tmp_path): return_value=[str(empty_dir)], ) - ctx = _ctx(platform=LinuxSearchPlatform()) + ctx = _ctx() result = find_in_site_packages(ctx) assert result is None assert any("No such file" in m for m in ctx.error_messages) @@ -530,7 +525,7 @@ def test_linux_declared_versioned_soname_does_not_need_unversioned_link(self, mo ) desc = _make_desc(linux_sonames=("libcudart.so.13", "libcudart.so.12")) - result = find_in_site_packages(_ctx(desc, platform=LinuxSearchPlatform())) + result = find_in_site_packages(_ctx(desc)) assert result is not None assert result.abs_path == str(versioned) assert result.found_via == "site-packages" @@ -550,7 +545,7 @@ def test_linux_declared_sonames_follow_preference_order(self, mocker, tmp_path): ) desc = _make_desc(linux_sonames=("libcudart.so.13", "libcudart.so.12")) - result = find_in_site_packages(_ctx(desc, platform=LinuxSearchPlatform())) + result = find_in_site_packages(_ctx(desc)) assert result is not None assert result.abs_path == str(preferred) assert result.found_via == "site-packages" @@ -571,7 +566,7 @@ def test_linux_rejects_undeclared_filename(self, mocker, tmp_path, undeclared_fi ) desc = _make_desc(linux_sonames=("libcudart.so.13", "libcudart.so.12")) - ctx = _ctx(desc, platform=LinuxSearchPlatform()) + ctx = _ctx(desc) result = find_in_site_packages(ctx) assert result is None assert ctx.error_messages @@ -600,7 +595,7 @@ def test_found_linux(self, mocker, tmp_path): mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path)}) - result = find_in_conda(_ctx(platform=LinuxSearchPlatform())) + result = find_in_conda(_ctx()) assert result is not None assert result.abs_path == str(so_file) assert result.found_via == "conda" @@ -613,7 +608,7 @@ def test_found_windows(self, mocker, tmp_path): mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path)}) - result = find_in_conda(_ctx(platform=WindowsSearchPlatform(target_arch="x64"))) + result = find_in_conda(_ctx(windows_arch="x64")) assert result is not None assert result.abs_path == str(dll) assert result.found_via == "conda" @@ -630,7 +625,7 @@ def test_found_windows_arm64_prefers_arch_dir(self, mocker, tmp_path): mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path)}) - result = find_in_conda(_ctx(platform=WindowsSearchPlatform(target_arch="arm64"))) + result = find_in_conda(_ctx(windows_arch="arm64")) assert result is not None assert result.abs_path == str(arm64_dll) assert result.found_via == "conda" @@ -645,7 +640,7 @@ def test_linux_declared_versioned_soname_found_in_lib_dir(self, mocker, tmp_path mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path)}) desc = _make_desc(linux_sonames=("libcudart.so.13", "libcudart.so.12")) - result = find_in_conda(_ctx(desc, platform=LinuxSearchPlatform())) + result = find_in_conda(_ctx(desc)) assert result is not None assert result.abs_path == str(versioned) assert result.found_via == "conda" @@ -663,7 +658,7 @@ def test_linux_rejects_undeclared_filename_in_lib_dir(self, mocker, tmp_path, un mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path)}) desc = _make_desc(linux_sonames=("libcudart.so.13", "libcudart.so.12")) - ctx = _ctx(desc, platform=LinuxSearchPlatform()) + ctx = _ctx(desc) result = find_in_conda(ctx) assert result is None assert ctx.error_messages @@ -678,7 +673,7 @@ def test_linux_rejects_undeclared_filename_in_lib_dir(self, mocker, tmp_path, un class TestFindInCudaHome: def test_returns_none_without_env_var(self, mocker): mocker.patch(f"{_STEPS_MOD}.get_cuda_path_or_home", return_value=None) - assert find_in_cuda_path(_ctx(platform=LinuxSearchPlatform())) is None + assert find_in_cuda_path(_ctx()) is None def test_found_linux(self, mocker, tmp_path): lib_dir = tmp_path / "lib64" @@ -688,7 +683,7 @@ def test_found_linux(self, mocker, tmp_path): mocker.patch(f"{_STEPS_MOD}.get_cuda_path_or_home", return_value=str(tmp_path)) - result = find_in_cuda_path(_ctx(platform=LinuxSearchPlatform())) + result = find_in_cuda_path(_ctx()) assert result is not None assert result.abs_path == str(so_file) assert result.found_via == "CUDA_PATH" @@ -710,7 +705,7 @@ def test_symlink_parent_root_selects_correct_library(self, mocker, tmp_path): (wrong_lib_dir / "libcudart.so").touch() mocker.patch(f"{_STEPS_MOD}.get_cuda_path_or_home", return_value=str(alias / "..")) - result = find_in_cuda_path(_ctx(platform=LinuxSearchPlatform())) + result = find_in_cuda_path(_ctx()) assert result is not None assert result.found_via == "CUDA_PATH" @@ -724,7 +719,7 @@ def test_found_windows(self, mocker, tmp_path): mocker.patch(f"{_STEPS_MOD}.get_cuda_path_or_home", return_value=str(tmp_path)) - result = find_in_cuda_path(_ctx(platform=WindowsSearchPlatform(target_arch="x64"))) + result = find_in_cuda_path(_ctx(windows_arch="x64")) assert result is not None assert result.abs_path == str(dll) assert result.found_via == "CUDA_PATH" @@ -741,7 +736,7 @@ def test_found_windows_arm64_prefers_arch_dir(self, mocker, tmp_path): mocker.patch(f"{_STEPS_MOD}.get_cuda_path_or_home", return_value=str(tmp_path)) - result = find_in_cuda_path(_ctx(platform=WindowsSearchPlatform(target_arch="arm64"))) + result = find_in_cuda_path(_ctx(windows_arch="arm64")) assert result is not None assert result.abs_path == str(arm64_dll) assert result.found_via == "CUDA_PATH" @@ -764,7 +759,7 @@ def test_nvvm_windows_checks_binary_arch(self, mocker, tmp_path, target_arch, ma mocker.patch(f"{_STEPS_MOD}.get_cuda_path_or_home", return_value=str(tmp_path)) - ctx = _ctx(LIB_DESCRIPTORS["nvvm"], platform=WindowsSearchPlatform(target_arch=target_arch)) + ctx = _ctx(LIB_DESCRIPTORS["nvvm"], windows_arch=target_arch) result = find_in_cuda_path(ctx) assert (result is not None) is expected_found @@ -803,7 +798,7 @@ def test_product_root_finds_supported_layouts(self, mocker, tmp_path, libname, e env[env_var] = str(root) mocker.patch.dict(os.environ, env) - result = find_in_install_root_env_vars(_ctx(LIB_DESCRIPTORS[libname], platform=LinuxSearchPlatform())) + result = find_in_install_root_env_vars(_ctx(LIB_DESCRIPTORS[libname])) assert result == FindResult(str(library), env_var) @@ -818,7 +813,7 @@ def test_nccl_home_prefers_canonical_installed_layout(self, mocker, tmp_path): libraries.append(library) mocker.patch.dict(os.environ, {"CUDNN_PATH": "", "NCCL_HOME": str(tmp_path)}) - result = find_in_install_root_env_vars(_ctx(LIB_DESCRIPTORS["nccl"], platform=LinuxSearchPlatform())) + result = find_in_install_root_env_vars(_ctx(LIB_DESCRIPTORS["nccl"])) assert result == FindResult(str(libraries[0]), "NCCL_HOME") @@ -845,9 +840,7 @@ def test_cudnn_path_finds_supported_archive_layouts(self, mocker, tmp_path, targ _write_pe(dll, windows_arch_mod.WINDOWS_PE_MACHINE_BY_ARCH[target_arch]) mocker.patch.dict(os.environ, {"CUDNN_PATH": str(tmp_path)}) - result = find_in_install_root_env_vars( - _ctx(LIB_DESCRIPTORS["cudnn"], platform=WindowsSearchPlatform(target_arch=target_arch)) - ) + result = find_in_install_root_env_vars(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch=target_arch)) assert result == FindResult(str(dll), "CUDNN_PATH") @@ -866,9 +859,7 @@ def test_cudnn_path_does_not_cross_architectures(self, mocker, tmp_path, target_ _write_pe(bin_dir / "cudnn64_9.dll", windows_arch_mod.WINDOWS_PE_MACHINE_BY_ARCH[target_arch]) mocker.patch.dict(os.environ, {"CUDNN_PATH": str(tmp_path)}) - result = find_in_install_root_env_vars( - _ctx(LIB_DESCRIPTORS["cudnn"], platform=WindowsSearchPlatform(target_arch=target_arch)) - ) + result = find_in_install_root_env_vars(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch=target_arch)) assert result is None @@ -882,9 +873,7 @@ def test_program_files_finds_versioned_cudnn_install(self, mocker, tmp_path): _write_pe(dll, windows_arch_mod.WINDOWS_PE_MACHINE_BY_ARCH["x64"]) mocker.patch.dict(os.environ, {"PROGRAMFILES": str(tmp_path), "PROGRAMW6432": ""}) - result = find_in_program_files_roots( - _ctx(LIB_DESCRIPTORS["cudnn"], platform=WindowsSearchPlatform(target_arch="x64")) - ) + result = find_in_program_files_roots(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch="x64")) assert result == FindResult(str(dll), "ProgramFiles") @@ -899,9 +888,7 @@ def test_program_files_prefers_newest_numeric_cudnn_version_across_layouts(self, _write_pe(newer_dll, windows_arch_mod.WINDOWS_PE_MACHINE_BY_ARCH["x64"]) mocker.patch.dict(os.environ, {"PROGRAMFILES": str(tmp_path), "PROGRAMW6432": ""}) - result = find_in_program_files_roots( - _ctx(LIB_DESCRIPTORS["cudnn"], platform=WindowsSearchPlatform(target_arch="x64")) - ) + result = find_in_program_files_roots(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch="x64")) assert result == FindResult(str(newer_dll), "ProgramFiles") @@ -926,12 +913,12 @@ def test_cudnn_arm64_archive_layout_is_not_assumed_for_other_roots(self, mocker, }, ) mocker.patch(f"{_STEPS_MOD}.get_cuda_path_or_home", return_value=str(cuda_root)) - ctx = _ctx(LIB_DESCRIPTORS["cudnn"], platform=WindowsSearchPlatform(target_arch="arm64")) + ctx = _ctx(LIB_DESCRIPTORS["cudnn"], windows_arch="arm64") assert find_in_conda(ctx) is None assert find_in_cuda_path(ctx) is None assert find_in_program_files_roots(ctx) is None - assert ctx.platform.site_packages_rel_dirs(ctx.desc) == ("nvidia/cudnn/bin",) + assert ctx.site_packages_rel_dirs == ("nvidia/cudnn/bin",) # --------------------------------------------------------------------------- @@ -1046,7 +1033,7 @@ def test_windows_anchor_dirs_select_arm64(self): arm64=("bin/arm64", "bin"), ) ) - assert WindowsSearchPlatform(target_arch="arm64").anchor_rel_dirs(desc) == ("bin/arm64", "bin") + assert windows_search_context(desc, "arm64").anchor_rel_dirs == ("bin/arm64", "bin") @pytest.mark.agent_authored(model="gpt-5") def test_windows_anchor_dirs_select_x64(self): @@ -1056,7 +1043,7 @@ def test_windows_anchor_dirs_select_x64(self): arm64=("bin/arm64", "bin"), ) ) - assert WindowsSearchPlatform(target_arch="x64").anchor_rel_dirs(desc) == ("bin/x64", "bin") + assert windows_search_context(desc, "x64").anchor_rel_dirs == ("bin/x64", "bin") def test_nvvm_cuda_home_linux(self, mocker, tmp_path): """End-to-end: find_in_cuda_path resolves nvvm under its custom subdir.""" @@ -1072,33 +1059,7 @@ def test_nvvm_cuda_home_linux(self, mocker, tmp_path): linux_sonames=("libnvvm.so",), anchor_rel_dirs_linux=("nvvm/lib64",), ) - result = find_in_cuda_path(_ctx(desc, platform=LinuxSearchPlatform())) + result = find_in_cuda_path(_ctx(desc)) assert result is not None assert result.abs_path == str(so_file) assert result.found_via == "CUDA_PATH" - - -# --------------------------------------------------------------------------- -# Resolved search context vs. the platform classes it replaces -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize("windows_arch", (None, "x64", "arm64"), ids=("linux", "x64", "arm64")) -@pytest.mark.parametrize("desc", LIB_DESCRIPTORS.values(), ids=lambda desc: desc.name) -@pytest.mark.agent_authored(model="claude-fable-5-2") -def test_search_context_matches_search_platform(desc, windows_arch, monkeypatch): - monkeypatch.delenv("PROGRAMW6432", raising=False) - monkeypatch.setenv("PROGRAMFILES", "ProgramFilesRoot") - if windows_arch is None: - platform, ctx = LinuxSearchPlatform(), linux_search_context(desc) - else: - platform, ctx = WindowsSearchPlatform(target_arch=windows_arch), windows_search_context(desc, windows_arch) - - assert ctx.lib_searched_for == platform.lib_searched_for(desc) - assert ctx.site_packages_rel_dirs == platform.site_packages_rel_dirs(desc) - assert ctx.conda_anchor_point("conda-prefix") == platform.conda_anchor_point("conda-prefix") - assert ctx.anchor_rel_dirs == platform.anchor_rel_dirs(desc) - assert ctx.install_root_env_vars == platform.install_root_env_vars(desc) - assert ctx.install_root_env_rel_dirs == platform.install_root_env_rel_dirs(desc) - program_files_root_globs = tuple(os.path.join("ProgramFilesRoot", glob) for glob in ctx.program_files_rel_globs) - assert program_files_root_globs == platform.program_files_root_globs(desc)