From 5eeb823ee86ec5c662e1dd523d4438335b854452 Mon Sep 17 00:00:00 2001 From: Rob Parolin Date: Wed, 25 Nov 2026 12:59:07 -0700 Subject: [PATCH 1/5] refactor(pathfinder): search steps return their misses Until now a failed probe appended its error text to two lists on the search context, so every step mutated shared state as a side effect. Now a step returns either a `FindResult` (hit) or a `NotFound` (miss) that carries its error text. `run_find_steps` combines the misses, and `_load_lib_no_cache` hands the combined result to `raise_not_found`. `SearchContext` loses both lists and is a plain immutable record. `FindResult` is frozen too. A step that does not apply returns an empty `NotFound()`, not `None`. Tests: `result is None` becomes `isinstance(result, NotFound)`, and `result is not None` becomes `isinstance(result, FindResult)`, for step results only. Tests that read `ctx.error_messages` read `result.error_messages`. One new test covers how misses are combined. No behavior change. Checked beyond the test suite: for every catalog entry on Linux, Windows x64 and Windows arm64, each step's hit (path and `found_via`) or miss (messages and listings) and the final error text are byte-identical to `main`, over two fake install trees (1800 step results), as is `_load_lib_no_cache` for all 50 libraries. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Rob Parolin --- .../_dynamic_libs/load_nvidia_dynamic_lib.py | 36 +++--- .../_dynamic_libs/search_platform.py | 57 ++++++---- .../pathfinder/_dynamic_libs/search_steps.py | 73 +++++++----- .../tests/test_ctk_root_discovery.py | 22 ++-- .../tests/test_driver_lib_loading.py | 3 +- ...st_load_nvidia_dynamic_lib_using_mocker.py | 4 +- cuda_pathfinder/tests/test_search_steps.py | 107 ++++++++++-------- 7 files changed, 171 insertions(+), 131 deletions(-) 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 049d44d5a96..6aa3bcff2ac 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 @@ -22,6 +22,8 @@ from cuda.pathfinder._dynamic_libs.search_steps import ( EARLY_FIND_STEPS, LATE_FIND_STEPS, + FindResult, + NotFound, SearchContext, derive_ctk_root, find_via_ctk_root, @@ -146,16 +148,18 @@ def resolve_ctk_root_via_canary(canary_libname: str) -> str | None: return ctk_root -def _try_ctk_root_canary(ctx: SearchContext) -> str | None: +def _try_ctk_root_canary(ctx: SearchContext) -> FindResult | NotFound: """Try CTK-root canary fallback for descriptor-configured libraries.""" + missed = NotFound() for canary_libname in ctx.desc.ctk_root_canary_anchor_libnames: ctk_root = resolve_ctk_root_via_canary(canary_libname) if ctk_root is None: continue - find = find_via_ctk_root(ctx, ctk_root) - if find is not None: - return str(find.abs_path) - return None + result = find_via_ctk_root(ctx, ctk_root) + if isinstance(result, FindResult): + return result + missed += result + return missed def _load_lib_no_cache(libname: str) -> LoadedDL: @@ -168,30 +172,32 @@ def _load_lib_no_cache(libname: str) -> LoadedDL: # An already-loaded library bypasses the wheel and conda search. loaded = LOADER.check_if_already_loaded_from_elsewhere(desc) - find = run_find_steps(ctx, EARLY_FIND_STEPS) if loaded is None else None + early = run_find_steps(ctx, EARLY_FIND_STEPS) if loaded is None else NotFound() load_dependencies(desc, load_nvidia_dynamic_lib) if loaded is not None: return loaded # Phase 3: Load from found path, or fall back to system search + late find. - if find is not None: - return LOADER.load_with_abs_path(desc, find.abs_path, find.found_via) + if isinstance(early, FindResult): + return LOADER.load_with_abs_path(desc, early.abs_path, early.found_via) loaded = LOADER.load_with_system_search(desc) if loaded is not None: return loaded - find = run_find_steps(ctx, LATE_FIND_STEPS) - if find is not None: - return LOADER.load_with_abs_path(desc, find.abs_path, find.found_via) + late = run_find_steps(ctx, LATE_FIND_STEPS) + if isinstance(late, FindResult): + return LOADER.load_with_abs_path(desc, late.abs_path, late.found_via) + missed = early + late if desc.ctk_root_canary_anchor_libnames: - canary_abs_path = _try_ctk_root_canary(ctx) - if canary_abs_path is not None: - return LOADER.load_with_abs_path(desc, canary_abs_path, "system-ctk-root") + canary = _try_ctk_root_canary(ctx) + if isinstance(canary, FindResult): + return LOADER.load_with_abs_path(desc, canary.abs_path, canary.found_via) + missed += canary - ctx.raise_not_found() + ctx.raise_not_found(missed) @functools.cache diff --git a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py index 8ac3643c790..722c4fa171a 100644 --- a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py +++ b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py @@ -12,7 +12,7 @@ import os from collections.abc import Sequence -from dataclasses import dataclass, field +from dataclasses import dataclass from pathlib import PurePath from typing import NoReturn @@ -24,6 +24,17 @@ from cuda.pathfinder._utils.windows_arch import windows_pe_matches_arch, windows_python_arch +@dataclass(frozen=True, slots=True) +class NotFound: + """Why a search missed: the text for the final not-found error.""" + + error_messages: tuple[str, ...] = () + attachments: tuple[str, ...] = () + + def __add__(self, other: NotFound) -> NotFound: + return NotFound(self.error_messages + other.error_messages, self.attachments + other.attachments) + + @dataclass(frozen=True, slots=True) class SearchContext: """One library's search inputs, resolved for one target platform. @@ -47,8 +58,6 @@ class SearchContext: program_files_rel_globs: tuple[str, ...] #: Windows architecture that a candidate DLL must match; ``None`` means no check. pe_arch_to_check: str | None - error_messages: list[str] = field(default_factory=list) - attachments: list[str] = field(default_factory=list) def conda_anchor_point(self, conda_prefix: str) -> str: return os.path.join(conda_prefix, *self.conda_anchor_parts) @@ -59,9 +68,9 @@ def program_files_root_globs(self) -> tuple[str, ...]: 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) + def raise_not_found(self, missed: NotFound) -> NoReturn: + err = ", ".join(missed.error_messages) + att = "\n".join(missed.attachments) raise DynamicLibNotFoundError(f'Failure finding "{self.lib_searched_for}": {err}\n{att}') @@ -105,14 +114,15 @@ def search_context(desc: LibDescriptor) -> SearchContext: return linux_search_context(desc) -def _no_such_file_in_sub_dirs( - sub_dirs: Sequence[str], file_description: str, error_messages: list[str], attachments: list[str] -) -> None: - error_messages.append(f"No such file: {file_description}") +def _listdir_attachment(dirpath: str) -> tuple[str, ...]: + return (f' listdir("{dirpath}"):', *(f" {node}" for node in sorted(os.listdir(dirpath)))) + + +def _no_such_file_in_sub_dirs(sub_dirs: Sequence[str], file_description: str) -> NotFound: + attachments: tuple[str, ...] = () for sub_dir in find_sub_dirs_all_sitepackages(sub_dirs): - attachments.append(f' listdir("{sub_dir}"):') - for node in sorted(os.listdir(sub_dir)): - attachments.append(f" {node}") + attachments += _listdir_attachment(sub_dir) + return NotFound((f"No such file: {file_description}",), attachments) def _find_descriptor_so_under_dir(dirpath: str, desc: LibDescriptor) -> str | None: @@ -149,7 +159,7 @@ def _find_lib_file(ctx: SearchContext, dirpath: str) -> str | None: return _find_descriptor_dll_under_dir(dirpath, ctx.desc, ctx.pe_arch_to_check) -def find_lib_in_site_packages(ctx: SearchContext) -> str | None: +def find_lib_in_site_packages(ctx: SearchContext) -> str | NotFound: sub_dirs_searched: list[tuple[str, ...]] = [] for rel_dir in ctx.site_packages_rel_dirs: sub_dir = PurePath(rel_dir).parts @@ -158,23 +168,22 @@ def find_lib_in_site_packages(ctx: SearchContext) -> str | None: if lib_path is not None: return lib_path sub_dirs_searched.append(sub_dir) + missed = NotFound() for sub_dir in sub_dirs_searched: - _no_such_file_in_sub_dirs(sub_dir, ctx.lib_searched_for, ctx.error_messages, ctx.attachments) - return None + missed += _no_such_file_in_sub_dirs(sub_dir, ctx.lib_searched_for) + return missed -def find_lib_in_dir(ctx: SearchContext, lib_dir: str) -> str | None: +def find_lib_in_dir(ctx: SearchContext, lib_dir: str) -> str | NotFound: 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}") + error_message = 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}"):') + error_message = f"No {ctx.pe_arch_to_check}-compatible PE file: {ctx.lib_searched_for}" if not os.path.isdir(lib_dir): - ctx.attachments.append(" DIRECTORY DOES NOT EXIST") + attachments: tuple[str, ...] = (f' listdir("{lib_dir}"):', " DIRECTORY DOES NOT EXIST") else: - for node in sorted(os.listdir(lib_dir)): - ctx.attachments.append(f" {node}") - return None + attachments = _listdir_attachment(lib_dir) + return NotFound((error_message,), attachments) diff --git a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py index ba412274cbb..8e73c11eb4d 100644 --- a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py +++ b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py @@ -5,7 +5,11 @@ Each find step is a callable with signature:: - (SearchContext) -> FindResult | None + (SearchContext) -> FindResult | NotFound + +A step returns a :class:`FindResult` for a hit. For a miss it returns a +:class:`NotFound` that carries what the final error message should say, which +is nothing when the step did not apply. Find steps locate a library file on disk without loading it. The orchestrator in :mod:`load_nvidia_dynamic_lib` handles loading, the @@ -25,6 +29,7 @@ from dataclasses import dataclass from cuda.pathfinder._dynamic_libs.search_platform import ( + NotFound, SearchContext, find_lib_in_dir, find_lib_in_site_packages, @@ -39,7 +44,7 @@ # --------------------------------------------------------------------------- -@dataclass +@dataclass(frozen=True) class FindResult: """A library file located on disk (not yet loaded).""" @@ -48,7 +53,7 @@ class FindResult: #: Type alias for a find step callable. -FindStep = Callable[[SearchContext], FindResult | None] +FindStep = Callable[[SearchContext], FindResult | NotFound] def _iter_lib_dirs(root: str, rel_dirs: tuple[str, ...]) -> Iterator[str]: @@ -64,16 +69,18 @@ def _find_under_root( root: str, rel_dirs: tuple[str, ...], found_via: str, -) -> FindResult | None: +) -> FindResult | NotFound: """Resolve *rel_dirs* under *root*, then find the requested library.""" + missed = NotFound() for lib_dir in _iter_lib_dirs(root, rel_dirs): - abs_path = find_lib_in_dir(ctx, lib_dir) - if abs_path is not None: - return FindResult(abs_path, found_via) - return None + found = find_lib_in_dir(ctx, lib_dir) + if not isinstance(found, NotFound): + return FindResult(found, found_via) + missed += found + return missed -def _find_under_anchor_root(ctx: SearchContext, root: str, found_via: str) -> FindResult | None: +def _find_under_anchor_root(ctx: SearchContext, root: str, found_via: str) -> FindResult | NotFound: """Resolve the descriptor's general anchors under *root*.""" return _find_under_root(ctx, root, ctx.anchor_rel_dirs, found_via) @@ -127,7 +134,7 @@ def derive_ctk_root(resolved_lib_path: str) -> str | None: return _derive_ctk_root_windows(resolved_lib_path) -def find_via_ctk_root(ctx: SearchContext, ctk_root: str) -> FindResult | None: +def find_via_ctk_root(ctx: SearchContext, ctk_root: str) -> FindResult | NotFound: """Find a library under a previously derived CTK root.""" return _find_under_anchor_root(ctx, ctk_root, "system-ctk-root") @@ -137,39 +144,41 @@ def find_via_ctk_root(ctx: SearchContext, ctk_root: str) -> FindResult | None: # --------------------------------------------------------------------------- -def find_in_site_packages(ctx: SearchContext) -> FindResult | None: +def find_in_site_packages(ctx: SearchContext) -> FindResult | NotFound: """Search pip wheel install locations.""" if not ctx.site_packages_rel_dirs: - return None - abs_path = find_lib_in_site_packages(ctx) - if abs_path is not None: - return FindResult(abs_path, "site-packages") - return None + return NotFound() + found = find_lib_in_site_packages(ctx) + if isinstance(found, NotFound): + return found + return FindResult(found, "site-packages") -def find_in_conda(ctx: SearchContext) -> FindResult | None: +def find_in_conda(ctx: SearchContext) -> FindResult | NotFound: """Search ``$CONDA_PREFIX``.""" conda_prefix = os.environ.get("CONDA_PREFIX") if not conda_prefix: - return None + return NotFound() 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: +def find_in_install_root_env_vars(ctx: SearchContext) -> FindResult | NotFound: """Search installation roots named by descriptor-specific environment variables.""" rel_dirs = ctx.install_root_env_rel_dirs + missed = NotFound() for env_var in ctx.install_root_env_vars: root = os.environ.get(env_var) if not root: continue result = _find_under_root(ctx, root, rel_dirs, env_var) - if result is not None: + if isinstance(result, FindResult): return result - return None + missed += result + return missed -def find_in_cuda_path(ctx: SearchContext) -> FindResult | None: +def find_in_cuda_path(ctx: SearchContext) -> FindResult | NotFound: """Search ``$CUDA_PATH`` / ``$CUDA_HOME`` as fallback toolkit roots. This step runs after native system search on both platforms. On Windows, @@ -182,20 +191,22 @@ def find_in_cuda_path(ctx: SearchContext) -> FindResult | None: """ cuda_home = get_cuda_path_or_home() if cuda_home is None: - return None + return NotFound() return _find_under_anchor_root(ctx, cuda_home, "CUDA_PATH") -def find_in_program_files_roots(ctx: SearchContext) -> FindResult | None: +def find_in_program_files_roots(ctx: SearchContext) -> FindResult | NotFound: """Search descriptor-configured installation roots under Program Files.""" + missed = NotFound() 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 result = _find_under_anchor_root(ctx, str(resolve_path(root)), "ProgramFiles") - if result is not None: + if isinstance(result, FindResult): return result - return None + missed += result + return missed # --------------------------------------------------------------------------- @@ -218,10 +229,12 @@ def find_in_program_files_roots(ctx: SearchContext) -> FindResult | None: # --------------------------------------------------------------------------- -def run_find_steps(ctx: SearchContext, steps: tuple[FindStep, ...]) -> FindResult | None: - """Run find steps in order, returning the first hit.""" +def run_find_steps(ctx: SearchContext, steps: tuple[FindStep, ...]) -> FindResult | NotFound: + """Run find steps in order, returning the first hit or else every step's miss combined.""" + missed = NotFound() for step in steps: result = step(ctx) - if result is not None: + if isinstance(result, FindResult): return result - return None + missed += result + return missed diff --git a/cuda_pathfinder/tests/test_ctk_root_discovery.py b/cuda_pathfinder/tests/test_ctk_root_discovery.py index 2e96bebade2..f445d241e1c 100644 --- a/cuda_pathfinder/tests/test_ctk_root_discovery.py +++ b/cuda_pathfinder/tests/test_ctk_root_discovery.py @@ -26,6 +26,8 @@ windows_search_context, ) from cuda.pathfinder._dynamic_libs.search_steps import ( + FindResult, + NotFound, SearchContext, _derive_ctk_root_linux, _derive_ctk_root_windows, @@ -192,7 +194,7 @@ def test_try_via_ctk_root_finds_nvvm(tmp_path): nvvm_lib = _create_nvvm_in_ctk(ctk_root) result = find_via_ctk_root(_ctx("nvvm"), str(ctk_root)) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(nvvm_lib) assert result.found_via == "system-ctk-root" @@ -201,7 +203,7 @@ def test_try_via_ctk_root_returns_none_when_dir_missing(tmp_path): ctk_root = tmp_path / "cuda-13" ctk_root.mkdir() - assert find_via_ctk_root(_ctx("nvvm"), str(ctk_root)) is None + assert isinstance(find_via_ctk_root(_ctx("nvvm"), str(ctk_root)), NotFound) def test_try_via_ctk_root_regular_lib(tmp_path): @@ -209,7 +211,7 @@ def test_try_via_ctk_root_regular_lib(tmp_path): cudart_lib = _create_cudart_in_ctk(ctk_root) result = find_via_ctk_root(_ctx("cudart"), str(ctk_root)) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(cudart_lib) assert result.found_via == "system-ctk-root" @@ -227,7 +229,7 @@ def test_try_via_ctk_root_windows_arm64_prefers_arch_dir(tmp_path): ctx = windows_search_context(LIB_DESCRIPTORS["cudart"], "arm64") result = find_via_ctk_root(ctx, str(ctk_root)) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(arm64_lib) assert result.found_via == "system-ctk-root" @@ -377,14 +379,14 @@ def test_canary_finds_nvvm(tmp_path, mocker): ) parent_system_loader = mocker.patch.object(load_mod.LOADER, "load_with_system_search") - assert _try_ctk_root_canary(_ctx("nvvm")) == str(nvvm_lib) + assert _try_ctk_root_canary(_ctx("nvvm")) == FindResult(str(nvvm_lib), "system-ctk-root") probe.assert_called_once_with("cudart") parent_system_loader.assert_not_called() def test_canary_returns_none_when_subprocess_probe_fails(mocker): mocker.patch(f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value=None) - assert _try_ctk_root_canary(_ctx("nvvm")) is None + assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) def test_canary_returns_none_when_ctk_root_unrecognized(mocker): @@ -392,7 +394,7 @@ def test_canary_returns_none_when_ctk_root_unrecognized(mocker): f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value="/weird/path/libcudart.so.13", ) - assert _try_ctk_root_canary(_ctx("nvvm")) is None + assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) def test_canary_returns_none_when_nvvm_not_in_ctk_root(tmp_path, mocker): @@ -404,12 +406,12 @@ def test_canary_returns_none_when_nvvm_not_in_ctk_root(tmp_path, mocker): f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value=_fake_canary_path(ctk_root), ) - assert _try_ctk_root_canary(_ctx("nvvm")) is None + assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) def test_canary_skips_when_abs_path_none(mocker): mocker.patch(f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value=None) - assert _try_ctk_root_canary(_ctx("nvvm")) is None + assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) # --------------------------------------------------------------------------- @@ -458,7 +460,7 @@ def _isolate_load_cascade(mocker): # system-search, CUDA_HOME and canary behavior. def _run_find_steps_with_early_disabled(ctx, steps): if steps is load_mod.EARLY_FIND_STEPS: - return None + return NotFound() return steps_mod.run_find_steps(ctx, steps) mocker.patch(f"{_MODULE}.run_find_steps", side_effect=_run_find_steps_with_early_disabled) diff --git a/cuda_pathfinder/tests/test_driver_lib_loading.py b/cuda_pathfinder/tests/test_driver_lib_loading.py index 4550d9fae2f..c3ecb569e4c 100644 --- a/cuda_pathfinder/tests/test_driver_lib_loading.py +++ b/cuda_pathfinder/tests/test_driver_lib_loading.py @@ -26,6 +26,7 @@ _load_driver_lib_no_cache, _load_lib_no_cache, ) +from cuda.pathfinder._dynamic_libs.search_steps import NotFound from cuda.pathfinder._dynamic_libs.subprocess_protocol import STATUS_NOT_FOUND, parse_dynamic_lib_subprocess_payload from cuda.pathfinder._utils import driver_info from cuda.pathfinder._utils.platform_aware import IS_WINDOWS @@ -111,7 +112,7 @@ def test_load_lib_no_cache_dispatches_to_driver_path(libname, mocker): def test_load_lib_no_cache_does_not_dispatch_ctk_lib_to_driver_path(mocker): """Ensure regular CTK libs don't take the driver shortcut.""" mock_driver = mocker.patch(f"{_MODULE}._load_driver_lib_no_cache") - mocker.patch(f"{_MODULE}.run_find_steps", return_value=None) + mocker.patch(f"{_MODULE}.run_find_steps", return_value=NotFound()) mocker.patch(f"{_LOADER_MODULE}.check_if_already_loaded_from_elsewhere", return_value=None) mocker.patch(f"{_MODULE}.load_dependencies") mocker.patch( 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 801e770497a..d5ffc36bcb8 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 @@ -13,7 +13,7 @@ _resolve_system_loaded_abs_path_in_subprocess, ) 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._dynamic_libs.search_steps import EARLY_FIND_STEPS, NotFound from cuda.pathfinder._utils.platform_aware import IS_WINDOWS _MODULE = "cuda.pathfinder._dynamic_libs.load_nvidia_dynamic_lib" @@ -150,7 +150,7 @@ def test_cupti_not_found_raises_error(mocker): # Mock all search paths to return None def _run_find_steps_disabled(ctx, steps): - return None + return NotFound() mocker.patch(f"{_MODULE}.run_find_steps", side_effect=_run_find_steps_disabled) mocker.patch.object(load_mod.LOADER, "check_if_already_loaded_from_elsewhere", return_value=None) diff --git a/cuda_pathfinder/tests/test_search_steps.py b/cuda_pathfinder/tests/test_search_steps.py index 379e5fe64c0..8500698ba10 100644 --- a/cuda_pathfinder/tests/test_search_steps.py +++ b/cuda_pathfinder/tests/test_search_steps.py @@ -25,6 +25,7 @@ EARLY_FIND_STEPS, LATE_FIND_STEPS, FindResult, + NotFound, SearchContext, find_in_conda, find_in_cuda_path, @@ -100,15 +101,14 @@ def test_lib_searched_for_windows(self): def test_raise_not_found_includes_messages(self): ctx = _ctx() - ctx.error_messages.append("No such file: libcudart.so") - ctx.attachments.append(' listdir("/some/dir"):') + missed = NotFound(("No such file: libcudart.so",), (' listdir("/some/dir"):',)) with pytest.raises(DynamicLibNotFoundError, match="No such file"): - ctx.raise_not_found() + ctx.raise_not_found(missed) def test_raise_not_found_empty_messages(self): ctx = _ctx() with pytest.raises(DynamicLibNotFoundError): - ctx.raise_not_found() + ctx.raise_not_found(NotFound()) # --------------------------------------------------------------------------- @@ -264,7 +264,7 @@ class TestFindInSitePackages: def test_returns_none_when_no_rel_dirs(self): desc = _make_desc(site_packages_linux=(), site_packages_windows=WindowsSearchDirs()) result = find_in_site_packages(_ctx(desc)) - assert result is None + assert isinstance(result, NotFound) def test_found_linux(self, mocker, tmp_path): lib_dir = tmp_path / "nvidia" / "cuda_runtime" / "lib" @@ -281,7 +281,7 @@ def test_found_linux(self, mocker, tmp_path): site_packages_linux=(os.path.join("nvidia", "cuda_runtime", "lib"),), ) result = find_in_site_packages(_ctx(desc)) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(so_file) assert result.found_via == "site-packages" @@ -299,7 +299,7 @@ def test_nvvm_linux_wheel_accepts_declared_unversioned_filename(self, mocker, tm result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["nvvm"])) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(so_file) assert result.found_via == "site-packages" @@ -323,7 +323,7 @@ def test_found_windows(self, mocker, tmp_path): ), ) result = find_in_site_packages(_ctx(desc, windows_arch="x64")) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(dll) assert result.found_via == "site-packages" @@ -340,7 +340,7 @@ def test_windows_exact_names_reject_cudnn_sidecar(self, mocker, tmp_path): result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch="x64")) - assert result is None + assert isinstance(result, NotFound) @pytest.mark.agent_authored(model="gpt-5.6-sol") def test_windows_matching_rejects_unlisted_cupti_name(self, mocker, tmp_path): @@ -355,7 +355,7 @@ def test_windows_matching_rejects_unlisted_cupti_name(self, mocker, tmp_path): result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["cupti"], windows_arch="x64")) - assert result is None + assert isinstance(result, NotFound) @pytest.mark.agent_authored(model="gpt-5.6-sol") def test_windows_known_cupti_names_follow_declared_preference_order(self, tmp_path): @@ -404,7 +404,7 @@ def test_found_windows_arm64_prefers_cuda13_arch_dir_to_cuda12(self, mocker, tmp desc = LIB_DESCRIPTORS["cudart"] result = find_in_site_packages(_ctx(desc, windows_arch="arm64")) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(arm64_dll) assert result.found_via == "site-packages" @@ -426,7 +426,7 @@ def test_found_windows_x64_prefers_cuda13_arch_dir_to_cuda12(self, mocker, tmp_p desc = LIB_DESCRIPTORS["cudart"] result = find_in_site_packages(_ctx(desc, windows_arch="x64")) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(x86_64_dll) assert result.found_via == "site-packages" @@ -442,7 +442,7 @@ def test_found_windows_x64_uses_cuda12_when_cuda13_is_absent(self, mocker, tmp_p desc = LIB_DESCRIPTORS["cudart"] result = find_in_site_packages(_ctx(desc, windows_arch="x64")) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(cuda12_dll) assert result.found_via == "site-packages" @@ -461,7 +461,7 @@ def test_found_windows_arm64_skips_cuda12_when_cuda13_is_absent(self, mocker, tm result = find_in_site_packages(ctx) - assert result is None + assert isinstance(result, NotFound) @pytest.mark.parametrize( ("target_arch", "wheel_arch", "expected_source"), @@ -509,8 +509,8 @@ def test_not_found_appends_error(self, mocker, tmp_path): 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) + assert isinstance(result, NotFound) + assert any("No such file" in m for m in result.error_messages) @pytest.mark.agent_authored(model="gpt-5.6-sol") def test_linux_declared_versioned_soname_does_not_need_unversioned_link(self, mocker, tmp_path): @@ -526,7 +526,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)) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(versioned) assert result.found_via == "site-packages" @@ -546,7 +546,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)) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(preferred) assert result.found_via == "site-packages" @@ -568,9 +568,9 @@ 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) result = find_in_site_packages(ctx) - assert result is None - assert ctx.error_messages - assert all("*" not in message for message in ctx.error_messages) + assert isinstance(result, NotFound) + assert result.error_messages + assert all("*" not in message for message in result.error_messages) # --------------------------------------------------------------------------- @@ -581,11 +581,11 @@ def test_linux_rejects_undeclared_filename(self, mocker, tmp_path, undeclared_fi class TestFindInConda: def test_returns_none_without_conda_prefix(self, mocker): mocker.patch.dict(os.environ, {}, clear=True) - assert find_in_conda(_ctx()) is None + assert isinstance(find_in_conda(_ctx()), NotFound) def test_returns_none_with_empty_conda_prefix(self, mocker): mocker.patch.dict(os.environ, {"CONDA_PREFIX": ""}) - assert find_in_conda(_ctx()) is None + assert isinstance(find_in_conda(_ctx()), NotFound) def test_found_linux(self, mocker, tmp_path): lib_dir = tmp_path / "lib" @@ -596,7 +596,7 @@ def test_found_linux(self, mocker, tmp_path): mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path)}) result = find_in_conda(_ctx()) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(so_file) assert result.found_via == "conda" @@ -609,7 +609,7 @@ def test_found_windows(self, mocker, tmp_path): mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path)}) result = find_in_conda(_ctx(windows_arch="x64")) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(dll) assert result.found_via == "conda" @@ -626,7 +626,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(windows_arch="arm64")) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(arm64_dll) assert result.found_via == "conda" @@ -641,7 +641,7 @@ def test_linux_declared_versioned_soname_found_in_lib_dir(self, mocker, tmp_path desc = _make_desc(linux_sonames=("libcudart.so.13", "libcudart.so.12")) result = find_in_conda(_ctx(desc)) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(versioned) assert result.found_via == "conda" @@ -660,9 +660,9 @@ def test_linux_rejects_undeclared_filename_in_lib_dir(self, mocker, tmp_path, un desc = _make_desc(linux_sonames=("libcudart.so.13", "libcudart.so.12")) ctx = _ctx(desc) result = find_in_conda(ctx) - assert result is None - assert ctx.error_messages - assert all("*" not in message for message in ctx.error_messages) + assert isinstance(result, NotFound) + assert result.error_messages + assert all("*" not in message for message in result.error_messages) # --------------------------------------------------------------------------- @@ -673,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()) is None + assert isinstance(find_in_cuda_path(_ctx()), NotFound) def test_found_linux(self, mocker, tmp_path): lib_dir = tmp_path / "lib64" @@ -684,7 +684,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()) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(so_file) assert result.found_via == "CUDA_PATH" @@ -707,7 +707,7 @@ def test_symlink_parent_root_selects_correct_library(self, mocker, tmp_path): result = find_in_cuda_path(_ctx()) - assert result is not None + assert isinstance(result, FindResult) assert result.found_via == "CUDA_PATH" assert os.path.samefile(result.abs_path, selected_library) @@ -720,7 +720,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(windows_arch="x64")) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(dll) assert result.found_via == "CUDA_PATH" @@ -737,7 +737,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(windows_arch="arm64")) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(arm64_dll) assert result.found_via == "CUDA_PATH" @@ -762,13 +762,13 @@ def test_nvvm_windows_checks_binary_arch(self, mocker, tmp_path, target_arch, ma ctx = _ctx(LIB_DESCRIPTORS["nvvm"], windows_arch=target_arch) result = find_in_cuda_path(ctx) - assert (result is not None) is expected_found + assert isinstance(result, FindResult) is expected_found if expected_found: - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(dll) assert result.found_via == "CUDA_PATH" else: - assert any(f"No {target_arch}-compatible PE file" in message for message in ctx.error_messages) + assert any(f"No {target_arch}-compatible PE file" in message for message in result.error_messages) # --------------------------------------------------------------------------- @@ -861,7 +861,7 @@ def test_cudnn_path_does_not_cross_architectures(self, mocker, tmp_path, target_ result = find_in_install_root_env_vars(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch=target_arch)) - assert result is None + assert isinstance(result, NotFound) @pytest.mark.agent_authored(model="gpt-5") def test_program_files_finds_versioned_cudnn_install(self, mocker, tmp_path): @@ -915,9 +915,9 @@ 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"], 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 isinstance(find_in_conda(ctx), NotFound) + assert isinstance(find_in_cuda_path(ctx), NotFound) + assert isinstance(find_in_program_files_roots(ctx), NotFound) assert ctx.site_packages_rel_dirs == ("nvidia/cudnn/bin",) @@ -939,16 +939,25 @@ def step_b(_ctx): result = run_find_steps(_ctx(), (step_a, step_b)) assert result is hit - def test_returns_none_when_all_miss(self): - result = run_find_steps(_ctx(), (lambda _: None, lambda _: None)) - assert result is None + def test_returns_not_found_when_all_miss(self): + result = run_find_steps(_ctx(), (lambda _: NotFound(), lambda _: NotFound())) + assert result == NotFound() + + @pytest.mark.agent_authored(model="claude-fable-5-2") + def test_combines_misses_in_step_order(self): + step_a_miss = NotFound(("a1", "a2"), ("listing a",)) + step_b_miss = NotFound(("b1",), ("listing b",)) + + result = run_find_steps(_ctx(), (lambda _: step_a_miss, lambda _: NotFound(), lambda _: step_b_miss)) + + assert result == NotFound(("a1", "a2", "b1"), ("listing a", "listing b")) def test_empty_steps(self): - assert run_find_steps(_ctx(), ()) is None + assert run_find_steps(_ctx(), ()) == NotFound() - def test_skips_nones_returns_later_hit(self): + def test_skips_misses_returns_later_hit(self): hit = FindResult("/later/lib.so", "step-c") - result = run_find_steps(_ctx(), (lambda _: None, lambda _: hit)) + result = run_find_steps(_ctx(), (lambda _: NotFound(), lambda _: hit)) assert result is hit @@ -1060,6 +1069,6 @@ def test_nvvm_cuda_home_linux(self, mocker, tmp_path): anchor_rel_dirs_linux=("nvvm/lib64",), ) result = find_in_cuda_path(_ctx(desc)) - assert result is not None + assert isinstance(result, FindResult) assert result.abs_path == str(so_file) assert result.found_via == "CUDA_PATH" From f27fac491b9f2a2295203c81678ec7c2d3add4f2 Mon Sep 17 00:00:00 2001 From: Rob Parolin Date: Wed, 25 Nov 2026 15:14:33 -0700 Subject: [PATCH 2/5] refactor(pathfinder): ask a search result whether it found something Callers told a hit from a miss with `isinstance(result, FindResult)`. Both result types now carry a `found` flag, so callers write `if result.found:` instead. The flag is typed as a literal `True` on `FindResult` and `False` on `NotFound`, so a type checker still narrows the type inside the `if`. To make that uniform, the two file probes in `search_platform.py` return a `FindResult` instead of a bare path, and `FindResult` moves there, next to `NotFound`. `search_steps.py` still exports it. No behavior change. 1647 passed, 6 skipped, and every comparison against `main` is still byte-identical, including simulated Windows. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Rob Parolin --- .../_dynamic_libs/load_nvidia_dynamic_lib.py | 8 ++--- .../_dynamic_libs/search_platform.py | 21 +++++++++--- .../pathfinder/_dynamic_libs/search_steps.py | 34 +++++-------------- cuda_pathfinder/tests/test_search_steps.py | 5 +++ 4 files changed, 34 insertions(+), 34 deletions(-) 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 6aa3bcff2ac..a542a37aa14 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 @@ -156,7 +156,7 @@ def _try_ctk_root_canary(ctx: SearchContext) -> FindResult | NotFound: if ctk_root is None: continue result = find_via_ctk_root(ctx, ctk_root) - if isinstance(result, FindResult): + if result.found: return result missed += result return missed @@ -179,7 +179,7 @@ def _load_lib_no_cache(libname: str) -> LoadedDL: return loaded # Phase 3: Load from found path, or fall back to system search + late find. - if isinstance(early, FindResult): + if early.found: return LOADER.load_with_abs_path(desc, early.abs_path, early.found_via) loaded = LOADER.load_with_system_search(desc) @@ -187,13 +187,13 @@ def _load_lib_no_cache(libname: str) -> LoadedDL: return loaded late = run_find_steps(ctx, LATE_FIND_STEPS) - if isinstance(late, FindResult): + if late.found: return LOADER.load_with_abs_path(desc, late.abs_path, late.found_via) missed = early + late if desc.ctk_root_canary_anchor_libnames: canary = _try_ctk_root_canary(ctx) - if isinstance(canary, FindResult): + if canary.found: return LOADER.load_with_abs_path(desc, canary.abs_path, canary.found_via) missed += canary diff --git a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py index 722c4fa171a..a91ccabbb26 100644 --- a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py +++ b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py @@ -14,7 +14,7 @@ from collections.abc import Sequence from dataclasses import dataclass from pathlib import PurePath -from typing import NoReturn +from typing import ClassVar, Literal, NoReturn from cuda.pathfinder._dynamic_libs.lib_descriptor import LibDescriptor from cuda.pathfinder._dynamic_libs.load_dl_common import DynamicLibNotFoundError @@ -24,12 +24,23 @@ from cuda.pathfinder._utils.windows_arch import windows_pe_matches_arch, windows_python_arch +@dataclass(frozen=True, slots=True) +class FindResult: + """A library file located on disk (not yet loaded).""" + + abs_path: str + found_via: str + #: Lets callers ask ``result.found`` of either result type. + found: ClassVar[Literal[True]] = True + + @dataclass(frozen=True, slots=True) class NotFound: """Why a search missed: the text for the final not-found error.""" error_messages: tuple[str, ...] = () attachments: tuple[str, ...] = () + found: ClassVar[Literal[False]] = False def __add__(self, other: NotFound) -> NotFound: return NotFound(self.error_messages + other.error_messages, self.attachments + other.attachments) @@ -159,14 +170,14 @@ def _find_lib_file(ctx: SearchContext, dirpath: str) -> str | None: return _find_descriptor_dll_under_dir(dirpath, ctx.desc, ctx.pe_arch_to_check) -def find_lib_in_site_packages(ctx: SearchContext) -> str | NotFound: +def find_lib_in_site_packages(ctx: SearchContext) -> FindResult | NotFound: sub_dirs_searched: list[tuple[str, ...]] = [] 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): lib_path = _find_lib_file(ctx, abs_dir) if lib_path is not None: - return lib_path + return FindResult(lib_path, "site-packages") sub_dirs_searched.append(sub_dir) missed = NotFound() for sub_dir in sub_dirs_searched: @@ -174,10 +185,10 @@ def find_lib_in_site_packages(ctx: SearchContext) -> str | NotFound: return missed -def find_lib_in_dir(ctx: SearchContext, lib_dir: str) -> str | NotFound: +def find_lib_in_dir(ctx: SearchContext, lib_dir: str, found_via: str) -> FindResult | NotFound: lib_path = _find_lib_file(ctx, lib_dir) if lib_path is not None: - return lib_path + return FindResult(lib_path, found_via) if ctx.pe_arch_to_check is None: error_message = f"No such file: {ctx.lib_searched_for}" else: diff --git a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py index 8e73c11eb4d..63425e8e15b 100644 --- a/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py +++ b/cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py @@ -26,9 +26,9 @@ import glob import os from collections.abc import Callable, Iterator -from dataclasses import dataclass from cuda.pathfinder._dynamic_libs.search_platform import ( + FindResult, NotFound, SearchContext, find_lib_in_dir, @@ -39,19 +39,6 @@ from .._utils.resolve_path import resolve_path -# --------------------------------------------------------------------------- -# Data types -# --------------------------------------------------------------------------- - - -@dataclass(frozen=True) -class FindResult: - """A library file located on disk (not yet loaded).""" - - abs_path: str - found_via: str - - #: Type alias for a find step callable. FindStep = Callable[[SearchContext], FindResult | NotFound] @@ -73,10 +60,10 @@ def _find_under_root( """Resolve *rel_dirs* under *root*, then find the requested library.""" missed = NotFound() for lib_dir in _iter_lib_dirs(root, rel_dirs): - found = find_lib_in_dir(ctx, lib_dir) - if not isinstance(found, NotFound): - return FindResult(found, found_via) - missed += found + result = find_lib_in_dir(ctx, lib_dir, found_via) + if result.found: + return result + missed += result return missed @@ -148,10 +135,7 @@ def find_in_site_packages(ctx: SearchContext) -> FindResult | NotFound: """Search pip wheel install locations.""" if not ctx.site_packages_rel_dirs: return NotFound() - found = find_lib_in_site_packages(ctx) - if isinstance(found, NotFound): - return found - return FindResult(found, "site-packages") + return find_lib_in_site_packages(ctx) def find_in_conda(ctx: SearchContext) -> FindResult | NotFound: @@ -172,7 +156,7 @@ def find_in_install_root_env_vars(ctx: SearchContext) -> FindResult | NotFound: if not root: continue result = _find_under_root(ctx, root, rel_dirs, env_var) - if isinstance(result, FindResult): + if result.found: return result missed += result return missed @@ -203,7 +187,7 @@ def find_in_program_files_roots(ctx: SearchContext) -> FindResult | NotFound: if not os.path.isdir(root): continue result = _find_under_anchor_root(ctx, str(resolve_path(root)), "ProgramFiles") - if isinstance(result, FindResult): + if result.found: return result missed += result return missed @@ -234,7 +218,7 @@ def run_find_steps(ctx: SearchContext, steps: tuple[FindStep, ...]) -> FindResul missed = NotFound() for step in steps: result = step(ctx) - if isinstance(result, FindResult): + if result.found: return result missed += result return missed diff --git a/cuda_pathfinder/tests/test_search_steps.py b/cuda_pathfinder/tests/test_search_steps.py index 8500698ba10..81bcd6bfdc2 100644 --- a/cuda_pathfinder/tests/test_search_steps.py +++ b/cuda_pathfinder/tests/test_search_steps.py @@ -955,6 +955,11 @@ def test_combines_misses_in_step_order(self): def test_empty_steps(self): assert run_find_steps(_ctx(), ()) == NotFound() + @pytest.mark.agent_authored(model="claude-fable-5-2") + def test_both_result_types_say_whether_they_found_something(self): + assert FindResult("/lib/libfoo.so", "conda").found is True + assert NotFound(("No such file: libfoo.so",)).found is False + def test_skips_misses_returns_later_hit(self): hit = FindResult("/later/lib.so", "step-c") result = run_find_steps(_ctx(), (lambda _: NotFound(), lambda _: hit)) From 3cbddfd98733063ef6a2f0f974e689875f161796 Mon Sep 17 00:00:00 2001 From: Rob Parolin Date: Wed, 25 Nov 2026 15:51:55 -0700 Subject: [PATCH 3/5] test(pathfinder): pin the not-found error text and its order The search steps now return their misses, and the error text is put together in six places. Only `run_find_steps` was tested, so reversing or dropping any of the other five went unnoticed. Three new tests pin the exact text: the full `DynamicLibNotFoundError` for a library that misses in the early steps, the late steps and the canary root, and the misses reported by the product-root and Program Files steps. Each of the seven ways to reverse or drop a part now fails a test. Also renames eight tests whose names still said "returns none"; a miss is a `NotFound` now. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Rob Parolin --- .../tests/test_ctk_root_discovery.py | 8 +-- ...st_load_nvidia_dynamic_lib_using_mocker.py | 2 +- cuda_pathfinder/tests/test_search_steps.py | 51 +++++++++++++++++-- 3 files changed, 52 insertions(+), 9 deletions(-) diff --git a/cuda_pathfinder/tests/test_ctk_root_discovery.py b/cuda_pathfinder/tests/test_ctk_root_discovery.py index f445d241e1c..276d6de646b 100644 --- a/cuda_pathfinder/tests/test_ctk_root_discovery.py +++ b/cuda_pathfinder/tests/test_ctk_root_discovery.py @@ -199,7 +199,7 @@ def test_try_via_ctk_root_finds_nvvm(tmp_path): assert result.found_via == "system-ctk-root" -def test_try_via_ctk_root_returns_none_when_dir_missing(tmp_path): +def test_try_via_ctk_root_misses_when_dir_missing(tmp_path): ctk_root = tmp_path / "cuda-13" ctk_root.mkdir() @@ -384,12 +384,12 @@ def test_canary_finds_nvvm(tmp_path, mocker): parent_system_loader.assert_not_called() -def test_canary_returns_none_when_subprocess_probe_fails(mocker): +def test_canary_misses_when_subprocess_probe_fails(mocker): mocker.patch(f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value=None) assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) -def test_canary_returns_none_when_ctk_root_unrecognized(mocker): +def test_canary_misses_when_ctk_root_unrecognized(mocker): mocker.patch( f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value="/weird/path/libcudart.so.13", @@ -397,7 +397,7 @@ def test_canary_returns_none_when_ctk_root_unrecognized(mocker): assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) -def test_canary_returns_none_when_nvvm_not_in_ctk_root(tmp_path, mocker): +def test_canary_misses_when_nvvm_not_in_ctk_root(tmp_path, mocker): ctk_root = tmp_path / "cuda-13" # Create only the canary lib dir, not nvvm _create_cudart_in_ctk(ctk_root) 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 d5ffc36bcb8..9680b182d1c 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 @@ -148,7 +148,7 @@ def test_cupti_not_found_raises_error(mocker): if IS_WINDOWS: pytest.skip("Windows support for cupti not yet implemented") - # Mock all search paths to return None + # Make every search step miss def _run_find_steps_disabled(ctx, steps): return NotFound() diff --git a/cuda_pathfinder/tests/test_search_steps.py b/cuda_pathfinder/tests/test_search_steps.py index 81bcd6bfdc2..b8011d302c2 100644 --- a/cuda_pathfinder/tests/test_search_steps.py +++ b/cuda_pathfinder/tests/test_search_steps.py @@ -261,7 +261,7 @@ def test_windows_pe_matches_arch_rejects_malformed_file(tmp_path): class TestFindInSitePackages: - def test_returns_none_when_no_rel_dirs(self): + def test_misses_when_no_rel_dirs(self): desc = _make_desc(site_packages_linux=(), site_packages_windows=WindowsSearchDirs()) result = find_in_site_packages(_ctx(desc)) assert isinstance(result, NotFound) @@ -579,11 +579,11 @@ def test_linux_rejects_undeclared_filename(self, mocker, tmp_path, undeclared_fi class TestFindInConda: - def test_returns_none_without_conda_prefix(self, mocker): + def test_misses_without_conda_prefix(self, mocker): mocker.patch.dict(os.environ, {}, clear=True) assert isinstance(find_in_conda(_ctx()), NotFound) - def test_returns_none_with_empty_conda_prefix(self, mocker): + def test_misses_with_empty_conda_prefix(self, mocker): mocker.patch.dict(os.environ, {"CONDA_PREFIX": ""}) assert isinstance(find_in_conda(_ctx()), NotFound) @@ -671,7 +671,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): + def test_misses_without_env_var(self, mocker): mocker.patch(f"{_STEPS_MOD}.get_cuda_path_or_home", return_value=None) assert isinstance(find_in_cuda_path(_ctx()), NotFound) @@ -1077,3 +1077,46 @@ def test_nvvm_cuda_home_linux(self, mocker, tmp_path): assert isinstance(result, FindResult) assert result.abs_path == str(so_file) assert result.found_via == "CUDA_PATH" + + +# --------------------------------------------------------------------------- +# What a miss reports +# --------------------------------------------------------------------------- + + +class TestMissReports: + @pytest.mark.agent_authored(model="claude-fable-5-2") + def test_product_root_miss_reports_each_directory_searched(self, mocker, tmp_path): + desc = LIB_DESCRIPTORS["nccl"] + lib_dirs = [] + for rel_dir in desc.install_root_env_rel_dirs_linux[:2]: + lib_dir = tmp_path / rel_dir + lib_dir.mkdir(parents=True) + (lib_dir / "unrelated.txt").touch() + lib_dirs.append(lib_dir) + mocker.patch.dict(os.environ, {"NCCL_HOME": str(tmp_path)}) + + result = find_in_install_root_env_vars(_ctx(desc)) + + searched = " or ".join(desc.linux_sonames) + assert result == NotFound( + (f"No such file: {searched}",) * 2, + tuple(line for lib_dir in lib_dirs for line in (f' listdir("{lib_dir.resolve()}"):', " unrelated.txt")), + ) + + @pytest.mark.agent_authored(model="claude-fable-5-2") + def test_program_files_miss_reports_each_root_searched(self, mocker, tmp_path): + bin_dirs = [] + for version in ("v9.10", "v9.9"): # newest first: the order the roots are searched in + bin_dir = tmp_path / "NVIDIA" / "CUDNN" / version / "bin" + bin_dir.mkdir(parents=True) + (bin_dir / "unrelated.txt").touch() + bin_dirs.append(bin_dir) + mocker.patch.dict(os.environ, {"PROGRAMFILES": str(tmp_path), "PROGRAMW6432": ""}) + + result = find_in_program_files_roots(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch="x64")) + + assert result == NotFound( + ("No x64-compatible PE file: known cudnn DLL",) * 2, + tuple(line for bin_dir in bin_dirs for line in (f' listdir("{bin_dir.resolve()}"):', " unrelated.txt")), + ) From 3676bd98241d6d3433be0d590e2a7c6f386c5217 Mon Sep 17 00:00:00 2001 From: Rob Parolin Date: Thu, 26 Nov 2026 10:30:01 -0700 Subject: [PATCH 4/5] test(pathfinder): ask search results `.found` instead of using isinstance Package code asks a search result `result.found`. The tests still used `isinstance(result, FindResult)` and `isinstance(result, NotFound)` in 41 places. They now ask `.found` too, so tests read like the code they cover. One assert became redundant and is removed: the line above it already checks the same flag. Test only. No package code changes. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Rob Parolin --- .../tests/test_ctk_root_discovery.py | 16 ++--- cuda_pathfinder/tests/test_search_steps.py | 65 +++++++++---------- 2 files changed, 40 insertions(+), 41 deletions(-) diff --git a/cuda_pathfinder/tests/test_ctk_root_discovery.py b/cuda_pathfinder/tests/test_ctk_root_discovery.py index 276d6de646b..5f1bdd08411 100644 --- a/cuda_pathfinder/tests/test_ctk_root_discovery.py +++ b/cuda_pathfinder/tests/test_ctk_root_discovery.py @@ -194,7 +194,7 @@ def test_try_via_ctk_root_finds_nvvm(tmp_path): nvvm_lib = _create_nvvm_in_ctk(ctk_root) result = find_via_ctk_root(_ctx("nvvm"), str(ctk_root)) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(nvvm_lib) assert result.found_via == "system-ctk-root" @@ -203,7 +203,7 @@ def test_try_via_ctk_root_misses_when_dir_missing(tmp_path): ctk_root = tmp_path / "cuda-13" ctk_root.mkdir() - assert isinstance(find_via_ctk_root(_ctx("nvvm"), str(ctk_root)), NotFound) + assert not find_via_ctk_root(_ctx("nvvm"), str(ctk_root)).found def test_try_via_ctk_root_regular_lib(tmp_path): @@ -211,7 +211,7 @@ def test_try_via_ctk_root_regular_lib(tmp_path): cudart_lib = _create_cudart_in_ctk(ctk_root) result = find_via_ctk_root(_ctx("cudart"), str(ctk_root)) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(cudart_lib) assert result.found_via == "system-ctk-root" @@ -229,7 +229,7 @@ def test_try_via_ctk_root_windows_arm64_prefers_arch_dir(tmp_path): ctx = windows_search_context(LIB_DESCRIPTORS["cudart"], "arm64") result = find_via_ctk_root(ctx, str(ctk_root)) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(arm64_lib) assert result.found_via == "system-ctk-root" @@ -386,7 +386,7 @@ def test_canary_finds_nvvm(tmp_path, mocker): def test_canary_misses_when_subprocess_probe_fails(mocker): mocker.patch(f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value=None) - assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) + assert not _try_ctk_root_canary(_ctx("nvvm")).found def test_canary_misses_when_ctk_root_unrecognized(mocker): @@ -394,7 +394,7 @@ def test_canary_misses_when_ctk_root_unrecognized(mocker): f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value="/weird/path/libcudart.so.13", ) - assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) + assert not _try_ctk_root_canary(_ctx("nvvm")).found def test_canary_misses_when_nvvm_not_in_ctk_root(tmp_path, mocker): @@ -406,12 +406,12 @@ def test_canary_misses_when_nvvm_not_in_ctk_root(tmp_path, mocker): f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value=_fake_canary_path(ctk_root), ) - assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) + assert not _try_ctk_root_canary(_ctx("nvvm")).found def test_canary_skips_when_abs_path_none(mocker): mocker.patch(f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value=None) - assert isinstance(_try_ctk_root_canary(_ctx("nvvm")), NotFound) + assert not _try_ctk_root_canary(_ctx("nvvm")).found # --------------------------------------------------------------------------- diff --git a/cuda_pathfinder/tests/test_search_steps.py b/cuda_pathfinder/tests/test_search_steps.py index b8011d302c2..46082c71ba2 100644 --- a/cuda_pathfinder/tests/test_search_steps.py +++ b/cuda_pathfinder/tests/test_search_steps.py @@ -264,7 +264,7 @@ class TestFindInSitePackages: def test_misses_when_no_rel_dirs(self): desc = _make_desc(site_packages_linux=(), site_packages_windows=WindowsSearchDirs()) result = find_in_site_packages(_ctx(desc)) - assert isinstance(result, NotFound) + assert not result.found def test_found_linux(self, mocker, tmp_path): lib_dir = tmp_path / "nvidia" / "cuda_runtime" / "lib" @@ -281,7 +281,7 @@ def test_found_linux(self, mocker, tmp_path): site_packages_linux=(os.path.join("nvidia", "cuda_runtime", "lib"),), ) result = find_in_site_packages(_ctx(desc)) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(so_file) assert result.found_via == "site-packages" @@ -299,7 +299,7 @@ def test_nvvm_linux_wheel_accepts_declared_unversioned_filename(self, mocker, tm result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["nvvm"])) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(so_file) assert result.found_via == "site-packages" @@ -323,7 +323,7 @@ def test_found_windows(self, mocker, tmp_path): ), ) result = find_in_site_packages(_ctx(desc, windows_arch="x64")) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(dll) assert result.found_via == "site-packages" @@ -340,7 +340,7 @@ def test_windows_exact_names_reject_cudnn_sidecar(self, mocker, tmp_path): result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch="x64")) - assert isinstance(result, NotFound) + assert not result.found @pytest.mark.agent_authored(model="gpt-5.6-sol") def test_windows_matching_rejects_unlisted_cupti_name(self, mocker, tmp_path): @@ -355,7 +355,7 @@ def test_windows_matching_rejects_unlisted_cupti_name(self, mocker, tmp_path): result = find_in_site_packages(_ctx(LIB_DESCRIPTORS["cupti"], windows_arch="x64")) - assert isinstance(result, NotFound) + assert not result.found @pytest.mark.agent_authored(model="gpt-5.6-sol") def test_windows_known_cupti_names_follow_declared_preference_order(self, tmp_path): @@ -404,7 +404,7 @@ def test_found_windows_arm64_prefers_cuda13_arch_dir_to_cuda12(self, mocker, tmp desc = LIB_DESCRIPTORS["cudart"] result = find_in_site_packages(_ctx(desc, windows_arch="arm64")) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(arm64_dll) assert result.found_via == "site-packages" @@ -426,7 +426,7 @@ def test_found_windows_x64_prefers_cuda13_arch_dir_to_cuda12(self, mocker, tmp_p desc = LIB_DESCRIPTORS["cudart"] result = find_in_site_packages(_ctx(desc, windows_arch="x64")) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(x86_64_dll) assert result.found_via == "site-packages" @@ -442,7 +442,7 @@ def test_found_windows_x64_uses_cuda12_when_cuda13_is_absent(self, mocker, tmp_p desc = LIB_DESCRIPTORS["cudart"] result = find_in_site_packages(_ctx(desc, windows_arch="x64")) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(cuda12_dll) assert result.found_via == "site-packages" @@ -461,7 +461,7 @@ def test_found_windows_arm64_skips_cuda12_when_cuda13_is_absent(self, mocker, tm result = find_in_site_packages(ctx) - assert isinstance(result, NotFound) + assert not result.found @pytest.mark.parametrize( ("target_arch", "wheel_arch", "expected_source"), @@ -509,7 +509,7 @@ def test_not_found_appends_error(self, mocker, tmp_path): ctx = _ctx() result = find_in_site_packages(ctx) - assert isinstance(result, NotFound) + assert not result.found assert any("No such file" in m for m in result.error_messages) @pytest.mark.agent_authored(model="gpt-5.6-sol") @@ -526,7 +526,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)) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(versioned) assert result.found_via == "site-packages" @@ -546,7 +546,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)) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(preferred) assert result.found_via == "site-packages" @@ -568,7 +568,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) result = find_in_site_packages(ctx) - assert isinstance(result, NotFound) + assert not result.found assert result.error_messages assert all("*" not in message for message in result.error_messages) @@ -581,11 +581,11 @@ def test_linux_rejects_undeclared_filename(self, mocker, tmp_path, undeclared_fi class TestFindInConda: def test_misses_without_conda_prefix(self, mocker): mocker.patch.dict(os.environ, {}, clear=True) - assert isinstance(find_in_conda(_ctx()), NotFound) + assert not find_in_conda(_ctx()).found def test_misses_with_empty_conda_prefix(self, mocker): mocker.patch.dict(os.environ, {"CONDA_PREFIX": ""}) - assert isinstance(find_in_conda(_ctx()), NotFound) + assert not find_in_conda(_ctx()).found def test_found_linux(self, mocker, tmp_path): lib_dir = tmp_path / "lib" @@ -596,7 +596,7 @@ def test_found_linux(self, mocker, tmp_path): mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path)}) result = find_in_conda(_ctx()) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(so_file) assert result.found_via == "conda" @@ -609,7 +609,7 @@ def test_found_windows(self, mocker, tmp_path): mocker.patch.dict(os.environ, {"CONDA_PREFIX": str(tmp_path)}) result = find_in_conda(_ctx(windows_arch="x64")) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(dll) assert result.found_via == "conda" @@ -626,7 +626,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(windows_arch="arm64")) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(arm64_dll) assert result.found_via == "conda" @@ -641,7 +641,7 @@ def test_linux_declared_versioned_soname_found_in_lib_dir(self, mocker, tmp_path desc = _make_desc(linux_sonames=("libcudart.so.13", "libcudart.so.12")) result = find_in_conda(_ctx(desc)) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(versioned) assert result.found_via == "conda" @@ -660,7 +660,7 @@ def test_linux_rejects_undeclared_filename_in_lib_dir(self, mocker, tmp_path, un desc = _make_desc(linux_sonames=("libcudart.so.13", "libcudart.so.12")) ctx = _ctx(desc) result = find_in_conda(ctx) - assert isinstance(result, NotFound) + assert not result.found assert result.error_messages assert all("*" not in message for message in result.error_messages) @@ -673,7 +673,7 @@ def test_linux_rejects_undeclared_filename_in_lib_dir(self, mocker, tmp_path, un class TestFindInCudaHome: def test_misses_without_env_var(self, mocker): mocker.patch(f"{_STEPS_MOD}.get_cuda_path_or_home", return_value=None) - assert isinstance(find_in_cuda_path(_ctx()), NotFound) + assert not find_in_cuda_path(_ctx()).found def test_found_linux(self, mocker, tmp_path): lib_dir = tmp_path / "lib64" @@ -684,7 +684,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()) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(so_file) assert result.found_via == "CUDA_PATH" @@ -707,7 +707,7 @@ def test_symlink_parent_root_selects_correct_library(self, mocker, tmp_path): result = find_in_cuda_path(_ctx()) - assert isinstance(result, FindResult) + assert result.found assert result.found_via == "CUDA_PATH" assert os.path.samefile(result.abs_path, selected_library) @@ -720,7 +720,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(windows_arch="x64")) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(dll) assert result.found_via == "CUDA_PATH" @@ -737,7 +737,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(windows_arch="arm64")) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(arm64_dll) assert result.found_via == "CUDA_PATH" @@ -762,9 +762,8 @@ def test_nvvm_windows_checks_binary_arch(self, mocker, tmp_path, target_arch, ma ctx = _ctx(LIB_DESCRIPTORS["nvvm"], windows_arch=target_arch) result = find_in_cuda_path(ctx) - assert isinstance(result, FindResult) is expected_found + assert result.found is expected_found if expected_found: - assert isinstance(result, FindResult) assert result.abs_path == str(dll) assert result.found_via == "CUDA_PATH" else: @@ -861,7 +860,7 @@ def test_cudnn_path_does_not_cross_architectures(self, mocker, tmp_path, target_ result = find_in_install_root_env_vars(_ctx(LIB_DESCRIPTORS["cudnn"], windows_arch=target_arch)) - assert isinstance(result, NotFound) + assert not result.found @pytest.mark.agent_authored(model="gpt-5") def test_program_files_finds_versioned_cudnn_install(self, mocker, tmp_path): @@ -915,9 +914,9 @@ 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"], windows_arch="arm64") - assert isinstance(find_in_conda(ctx), NotFound) - assert isinstance(find_in_cuda_path(ctx), NotFound) - assert isinstance(find_in_program_files_roots(ctx), NotFound) + assert not find_in_conda(ctx).found + assert not find_in_cuda_path(ctx).found + assert not find_in_program_files_roots(ctx).found assert ctx.site_packages_rel_dirs == ("nvidia/cudnn/bin",) @@ -1074,7 +1073,7 @@ def test_nvvm_cuda_home_linux(self, mocker, tmp_path): anchor_rel_dirs_linux=("nvvm/lib64",), ) result = find_in_cuda_path(_ctx(desc)) - assert isinstance(result, FindResult) + assert result.found assert result.abs_path == str(so_file) assert result.found_via == "CUDA_PATH" From 07afb1a29c57a0f707a8ac8423a8e9ff39475a2e Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Thu, 26 Nov 2026 11:17:26 -0800 Subject: [PATCH 5/5] ci: require manual copy-pr-bot approval Signed-off-by: Ralf W. Grosse-Kunstleve