From 7cfcbeb4f265e68f23c4035aa823faf4534eb2fd Mon Sep 17 00:00:00 2001 From: Rob Parolin Date: Wed, 25 Nov 2026 12:59:13 -0700 Subject: [PATCH 1/4] refactor(pathfinder): static and bitcode finders share one search `find_static_lib.py` was written as a copy of `find_bitcode_lib.py` (#1690). Each had its own finder class, its own copy of the three search steps, and its own error formatter, and later changes had to be made twice (#2493, #2708, #3418). Both now call `locate_file()` in the new `_static_libs/locate_file.py`: site-packages, then `$CONDA_PREFIX`, then `$CUDA_PATH`. It returns the hit or `None`, and each public function raises its own documented error. The two finder classes and their scratch lists are gone (379 -> 275 lines in `_static_libs/`). An unreachable fallback message ("No search paths available") is dropped: the last search step always reported a reason. Tests: the 15 `monkeypatch.setattr(..., "find_sub_dirs_all_sitepackages")` calls now patch `locate_file`, where that lookup lives. Nothing else changes. No behavior change. Checked beyond the test suite: 831 scenarios (every supported name; Linux, Windows x64, Windows arm64; file in each search location or nowhere; `CONDA_PREFIX` set, unset, empty; `CUDA_PATH`, `CUDA_HOME`, unset, missing directory, relative path) give the same result, error type and error text as `main`, byte for byte. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Rob Parolin --- .../_static_libs/find_bitcode_lib.py | 122 +++-------------- .../_static_libs/find_static_lib.py | 123 +++--------------- .../pathfinder/_static_libs/locate_file.py | 71 ++++++++++ .../tests/test_find_bitcode_lib.py | 15 ++- cuda_pathfinder/tests/test_find_static_lib.py | 17 +-- 5 files changed, 123 insertions(+), 225 deletions(-) create mode 100644 cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py diff --git a/cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py b/cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py index 8f8e99de82d9..71c84f154062 100644 --- a/cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py +++ b/cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py @@ -2,17 +2,12 @@ # SPDX-License-Identifier: Apache-2.0 import functools -import os from dataclasses import dataclass -from pathlib import Path -from typing import NoReturn, TypedDict +from typing import TypedDict -from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home -from cuda.pathfinder._utils.find_sub_dirs import find_sub_dirs_all_sitepackages +from cuda.pathfinder._static_libs.locate_file import locate_file, not_found_message from cuda.pathfinder._utils.platform_aware import IS_WINDOWS -from .._utils.resolve_path import resolve_path - class BitcodeLibNotFoundError(RuntimeError): """Raised when a bitcode library cannot be found.""" @@ -69,73 +64,6 @@ class _BitcodeLibInfo(TypedDict): ) -def _no_such_file_in_dir(directory: Path, filename: str, error_messages: list[str], attachments: list[str]) -> None: - error_messages.append(f"No such file: {directory / filename}") - if directory.is_dir(): - attachments.append(f' listdir("{directory}"):') - for node in sorted(node_path.name for node_path in directory.iterdir()): - attachments.append(f" {node}") - else: - attachments.append(f' Directory does not exist: "{directory}"') - - -class _FindBitcodeLib: - def __init__(self, name: str) -> None: - if name not in _SUPPORTED_BITCODE_LIBS_INFO: # Updated reference - raise ValueError(f"Unknown bitcode library: '{name}'. Supported: {', '.join(SUPPORTED_BITCODE_LIBS)}") - self.name: str = name - self.config: _BitcodeLibInfo = _SUPPORTED_BITCODE_LIBS_INFO[name] # Updated reference - self.filename: str = self.config["filename"] - self.rel_path: str = self.config["rel_path"] - self.site_packages_dirs: tuple[str, ...] = self.config["site_packages_dirs"] - self.error_messages: list[str] = [] - self.attachments: list[str] = [] - - def try_site_packages(self) -> Path | None: - for rel_dir in self.site_packages_dirs: - sub_dir = tuple(rel_dir.split("/")) - for abs_dir in find_sub_dirs_all_sitepackages(sub_dir): - file_path = Path(abs_dir, self.filename) - if file_path.is_file(): - return resolve_path(file_path) - return None - - def try_with_conda_prefix(self) -> Path | None: - conda_prefix = os.environ.get("CONDA_PREFIX") - if not conda_prefix: - return None - - anchor = Path(conda_prefix, "Library") if IS_WINDOWS else Path(conda_prefix) - file_path = anchor / self.rel_path / self.filename - if file_path.is_file(): - return resolve_path(file_path) - return None - - def try_with_cuda_home(self) -> Path | None: - cuda_home = get_cuda_path_or_home() - if cuda_home is None: - self.error_messages.append("CUDA_HOME/CUDA_PATH not set") - return None - - anchor = Path(cuda_home) - file_path = anchor / self.rel_path / self.filename - if file_path.is_file(): - return resolve_path(file_path) - - _no_such_file_in_dir( - anchor / self.rel_path, - self.filename, - self.error_messages, - self.attachments, - ) - return None - - def raise_not_found_error(self) -> NoReturn: - err = ", ".join(self.error_messages) if self.error_messages else "No search paths available" - att = "\n".join(self.attachments) if self.attachments else "" - raise BitcodeLibNotFoundError(f'Failure finding "{self.filename}": {err}\n{att}') - - def locate_bitcode_lib(name: str) -> LocatedBitcodeLib: """Locate a bitcode library by name, returning its resolved absolute path. @@ -143,36 +71,22 @@ def locate_bitcode_lib(name: str) -> LocatedBitcodeLib: ValueError: If ``name`` is not a supported bitcode library. BitcodeLibNotFoundError: If the bitcode library cannot be found. """ - finder = _FindBitcodeLib(name) - - abs_path = finder.try_site_packages() - if abs_path is not None: - return LocatedBitcodeLib( - name=name, - abs_path=str(abs_path), - filename=finder.filename, - found_via="site-packages", - ) - - abs_path = finder.try_with_conda_prefix() - if abs_path is not None: - return LocatedBitcodeLib( - name=name, - abs_path=str(abs_path), - filename=finder.filename, - found_via="conda", - ) - - abs_path = finder.try_with_cuda_home() - if abs_path is not None: - return LocatedBitcodeLib( - name=name, - abs_path=str(abs_path), - filename=finder.filename, - found_via="CUDA_PATH", - ) - - finder.raise_not_found_error() + if name not in _SUPPORTED_BITCODE_LIBS_INFO: + raise ValueError(f"Unknown bitcode library: '{name}'. Supported: {', '.join(SUPPORTED_BITCODE_LIBS)}") + info = _SUPPORTED_BITCODE_LIBS_INFO[name] + filename = info["filename"] + rel_paths = (info["rel_path"],) + + found = locate_file( + filename, + site_packages_dirs=info["site_packages_dirs"], + conda_rel_paths=rel_paths, + ctk_rel_paths=rel_paths, + ) + if found is None: + raise BitcodeLibNotFoundError(not_found_message(filename, rel_paths)) + abs_path, found_via = found + return LocatedBitcodeLib(name=name, abs_path=abs_path, filename=filename, found_via=found_via) @functools.cache diff --git a/cuda_pathfinder/cuda/pathfinder/_static_libs/find_static_lib.py b/cuda_pathfinder/cuda/pathfinder/_static_libs/find_static_lib.py index 0a56885b598c..d8b5678cbb62 100644 --- a/cuda_pathfinder/cuda/pathfinder/_static_libs/find_static_lib.py +++ b/cuda_pathfinder/cuda/pathfinder/_static_libs/find_static_lib.py @@ -2,18 +2,14 @@ # SPDX-License-Identifier: Apache-2.0 import functools -import os from dataclasses import dataclass from pathlib import Path -from typing import NoReturn, TypedDict +from typing import TypedDict -from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home -from cuda.pathfinder._utils.find_sub_dirs import find_sub_dirs_all_sitepackages +from cuda.pathfinder._static_libs.locate_file import locate_file, not_found_message from cuda.pathfinder._utils.platform_aware import IS_WINDOWS from cuda.pathfinder._utils.windows_arch import windows_python_arch -from .._utils.resolve_path import resolve_path - class StaticLibNotFoundError(RuntimeError): """Raised when a static library cannot be found.""" @@ -65,76 +61,6 @@ def _cudadevrt_info() -> _StaticLibInfo: SUPPORTED_STATIC_LIBS: tuple[str, ...] = tuple(sorted(_SUPPORTED_STATIC_LIBS_INFO.keys())) -def _no_such_file_in_dir(directory: Path, filename: str, error_messages: list[str], attachments: list[str]) -> None: - error_messages.append(f"No such file: {directory / filename}") - if directory.is_dir(): - attachments.append(f' listdir("{directory}"):') - for node in sorted(node_path.name for node_path in directory.iterdir()): - attachments.append(f" {node}") - else: - attachments.append(f' Directory does not exist: "{directory}"') - - -class _FindStaticLib: - def __init__(self, name: str) -> None: - if name not in _SUPPORTED_STATIC_LIBS_INFO: - raise ValueError(f"Unknown static library: '{name}'. Supported: {', '.join(SUPPORTED_STATIC_LIBS)}") - self.name: str = name - self.config: _StaticLibInfo = _SUPPORTED_STATIC_LIBS_INFO[name] - self.filename: str = self.config["filename"] - self.ctk_rel_paths: tuple[str, ...] = self.config["ctk_rel_paths"] - self.conda_rel_paths: tuple[str, ...] = self.config["conda_rel_paths"] - self.site_packages_dirs: tuple[str, ...] = self.config["site_packages_dirs"] - self.error_messages: list[str] = [] - self.attachments: list[str] = [] - - def try_site_packages(self) -> Path | None: - for rel_dir in self.site_packages_dirs: - sub_dir = tuple(rel_dir.split("/")) - for abs_dir in find_sub_dirs_all_sitepackages(sub_dir): - file_path = Path(abs_dir, self.filename) - if file_path.is_file(): - return resolve_path(file_path) - return None - - def try_with_conda_prefix(self) -> Path | None: - conda_prefix = os.environ.get("CONDA_PREFIX") - if not conda_prefix: - return None - - anchor = Path(conda_prefix, "Library") if IS_WINDOWS else Path(conda_prefix) - for rel_path in self.conda_rel_paths: - file_path = anchor / rel_path / self.filename - if file_path.is_file(): - return resolve_path(file_path) - return None - - def try_with_cuda_home(self) -> Path | None: - cuda_home = get_cuda_path_or_home() - if cuda_home is None: - self.error_messages.append("CUDA_HOME/CUDA_PATH not set") - return None - - anchor = Path(cuda_home) - for rel_path in self.ctk_rel_paths: - file_path = anchor / rel_path / self.filename - if file_path.is_file(): - return resolve_path(file_path) - - _no_such_file_in_dir( - anchor / self.ctk_rel_paths[0], - self.filename, - self.error_messages, - self.attachments, - ) - return None - - def raise_not_found_error(self) -> NoReturn: - err = ", ".join(self.error_messages) if self.error_messages else "No search paths available" - att = "\n".join(self.attachments) if self.attachments else "" - raise StaticLibNotFoundError(f'Failure finding "{self.filename}": {err}\n{att}') - - def locate_static_lib(name: str) -> LocatedStaticLib: """Locate a static library by name, returning its resolved absolute path. @@ -142,36 +68,21 @@ def locate_static_lib(name: str) -> LocatedStaticLib: ValueError: If ``name`` is not a supported static library. StaticLibNotFoundError: If the static library cannot be found. """ - finder = _FindStaticLib(name) - - abs_path = finder.try_site_packages() - if abs_path is not None: - return LocatedStaticLib( - name=name, - abs_path=str(abs_path), - filename=finder.filename, - found_via="site-packages", - ) - - abs_path = finder.try_with_conda_prefix() - if abs_path is not None: - return LocatedStaticLib( - name=name, - abs_path=str(abs_path), - filename=finder.filename, - found_via="conda", - ) - - abs_path = finder.try_with_cuda_home() - if abs_path is not None: - return LocatedStaticLib( - name=name, - abs_path=str(abs_path), - filename=finder.filename, - found_via="CUDA_PATH", - ) - - finder.raise_not_found_error() + if name not in _SUPPORTED_STATIC_LIBS_INFO: + raise ValueError(f"Unknown static library: '{name}'. Supported: {', '.join(SUPPORTED_STATIC_LIBS)}") + info = _SUPPORTED_STATIC_LIBS_INFO[name] + filename = info["filename"] + + found = locate_file( + filename, + site_packages_dirs=info["site_packages_dirs"], + conda_rel_paths=info["conda_rel_paths"], + ctk_rel_paths=info["ctk_rel_paths"], + ) + if found is None: + raise StaticLibNotFoundError(not_found_message(filename, info["ctk_rel_paths"])) + abs_path, found_via = found + return LocatedStaticLib(name=name, abs_path=abs_path, filename=filename, found_via=found_via) @functools.cache diff --git a/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py b/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py new file mode 100644 index 000000000000..d4501b406692 --- /dev/null +++ b/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py @@ -0,0 +1,71 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Search shared by the static-library and bitcode-library finders.""" + +import os +from pathlib import Path + +from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home +from cuda.pathfinder._utils.find_sub_dirs import find_sub_dirs_all_sitepackages +from cuda.pathfinder._utils.platform_aware import IS_WINDOWS + +from .._utils.resolve_path import resolve_path + + +def _resolved_if_file(directory: Path | str, filename: str) -> str | None: + file_path = Path(directory, filename) + if file_path.is_file(): + return str(resolve_path(file_path)) + return None + + +def locate_file( + filename: str, + *, + site_packages_dirs: tuple[str, ...], + conda_rel_paths: tuple[str, ...], + ctk_rel_paths: tuple[str, ...], +) -> tuple[str, str] | None: + """Return ``(abs_path, found_via)`` for the first place that has *filename*, else ``None``. + + Search order: NVIDIA wheels (``site-packages``), ``$CONDA_PREFIX``, then + ``$CUDA_PATH`` / ``$CUDA_HOME``. Directories are tried first-to-last. + """ + for rel_dir in site_packages_dirs: + for abs_dir in find_sub_dirs_all_sitepackages(tuple(rel_dir.split("/"))): + abs_path = _resolved_if_file(abs_dir, filename) + if abs_path is not None: + return abs_path, "site-packages" + + conda_prefix = os.environ.get("CONDA_PREFIX") + if conda_prefix: + anchor = Path(conda_prefix, "Library") if IS_WINDOWS else Path(conda_prefix) + for rel_path in conda_rel_paths: + abs_path = _resolved_if_file(anchor / rel_path, filename) + if abs_path is not None: + return abs_path, "conda" + + cuda_home = get_cuda_path_or_home() + if cuda_home is not None: + for rel_path in ctk_rel_paths: + abs_path = _resolved_if_file(Path(cuda_home, rel_path), filename) + if abs_path is not None: + return abs_path, "CUDA_PATH" + + return None + + +def not_found_message(filename: str, ctk_rel_paths: tuple[str, ...]) -> str: + """Explain a :func:`locate_file` miss by describing the last place it searched.""" + cuda_home = get_cuda_path_or_home() + if cuda_home is None: + return f'Failure finding "{filename}": CUDA_HOME/CUDA_PATH not set\n' + + directory = Path(cuda_home, ctk_rel_paths[0]) + if directory.is_dir(): + listing = [f' listdir("{directory}"):'] + listing.extend(f" {node}" for node in sorted(node_path.name for node_path in directory.iterdir())) + else: + listing = [f' Directory does not exist: "{directory}"'] + return f'Failure finding "{filename}": No such file: {directory / filename}\n' + "\n".join(listing) diff --git a/cuda_pathfinder/tests/test_find_bitcode_lib.py b/cuda_pathfinder/tests/test_find_bitcode_lib.py index 3ecd7fddf255..a308b74c0bdd 100644 --- a/cuda_pathfinder/tests/test_find_bitcode_lib.py +++ b/cuda_pathfinder/tests/test_find_bitcode_lib.py @@ -7,6 +7,7 @@ import pytest import cuda.pathfinder._static_libs.find_bitcode_lib as find_bitcode_lib_module +import cuda.pathfinder._static_libs.locate_file as locate_file_module from cuda.pathfinder._static_libs.find_bitcode_lib import ( SUPPORTED_BITCODE_LIBS, BitcodeLibNotFoundError, @@ -111,7 +112,7 @@ def find_expected_sub_dir(sub_dir): return [] monkeypatch.setattr( - find_bitcode_lib_module, + locate_file_module, "find_sub_dirs_all_sitepackages", find_expected_sub_dir, ) @@ -147,9 +148,9 @@ def test_locate_bitcode_lib_returns_resolved_path_for_relative_root(monkeypatch, root = Path("relative-root") if source == "site-packages": lib_dir = root / Path(info["site_packages_dirs"][0]) - monkeypatch.setattr(find_bitcode_lib_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [str(lib_dir)]) + monkeypatch.setattr(locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [str(lib_dir)]) else: - monkeypatch.setattr(find_bitcode_lib_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) + monkeypatch.setattr(locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) if source == "conda": monkeypatch.setenv("CONDA_PREFIX", str(root)) lib_dir = _conda_anchor(root) / Path(info["rel_path"]) @@ -178,7 +179,7 @@ def test_locate_bitcode_lib_preserves_symlink_parent(monkeypatch, tmp_path): monkeypatch.delenv("CONDA_PREFIX", raising=False) monkeypatch.delenv("CUDA_PATH", raising=False) monkeypatch.setenv("CUDA_HOME", "alias/..") - monkeypatch.setattr(find_bitcode_lib_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) + monkeypatch.setattr(locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) real_root = tmp_path / "real" (real_root / "child").mkdir(parents=True) @@ -202,7 +203,7 @@ def test_locate_bitcode_lib_preserves_symlink_parent(monkeypatch, tmp_path): def test_locate_bitcode_lib_resolves_symlinked_file(monkeypatch, tmp_path): monkeypatch.delenv("CONDA_PREFIX", raising=False) monkeypatch.delenv("CUDA_PATH", raising=False) - monkeypatch.setattr(find_bitcode_lib_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) + monkeypatch.setattr(locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) root = tmp_path / "toolkit" monkeypatch.setenv("CUDA_HOME", str(root)) info = _bitcode_lib_info("device") @@ -227,7 +228,7 @@ def test_find_bitcode_lib_not_found_error_includes_cuda_home_directory_listing(m extra_file.write_text("placeholder", encoding="utf-8") monkeypatch.setattr( - find_bitcode_lib_module, + locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [], ) @@ -248,7 +249,7 @@ def test_find_bitcode_lib_not_found_error_includes_cuda_home_directory_listing(m @pytest.mark.usefixtures("clear_find_bitcode_lib_cache") def test_find_bitcode_lib_not_found_error_without_cuda_home(monkeypatch): monkeypatch.setattr( - find_bitcode_lib_module, + locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [], ) diff --git a/cuda_pathfinder/tests/test_find_static_lib.py b/cuda_pathfinder/tests/test_find_static_lib.py index a0f3e6b287ce..faff0e5b867b 100644 --- a/cuda_pathfinder/tests/test_find_static_lib.py +++ b/cuda_pathfinder/tests/test_find_static_lib.py @@ -8,6 +8,7 @@ from local_helpers import quote_for_shell import cuda.pathfinder._static_libs.find_static_lib as find_static_lib_module +import cuda.pathfinder._static_libs.locate_file as locate_file_module from cuda.pathfinder._static_libs.find_static_lib import ( SUPPORTED_STATIC_LIBS, StaticLibNotFoundError, @@ -93,7 +94,7 @@ def test_locate_static_lib_search_order(monkeypatch, tmp_path): cuda_home_path = _make_static_lib_file(cuda_home_lib_dir, filename) monkeypatch.setattr( - find_static_lib_module, + locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [str(site_packages_lib_dir)], ) @@ -128,9 +129,9 @@ def test_locate_static_lib_returns_resolved_path_for_relative_root(monkeypatch, root = Path("relative-root") if source == "site-packages": lib_dir = root / Path(CUDADEVRT_INFO["site_packages_dirs"][0]) - monkeypatch.setattr(find_static_lib_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [str(lib_dir)]) + monkeypatch.setattr(locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [str(lib_dir)]) else: - monkeypatch.setattr(find_static_lib_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) + monkeypatch.setattr(locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) if source == "conda": monkeypatch.setenv("CONDA_PREFIX", str(root)) lib_dir = _conda_anchor(root) / Path(CUDADEVRT_INFO["conda_rel_paths"][0]) @@ -159,7 +160,7 @@ def test_locate_static_lib_preserves_symlink_parent(monkeypatch, tmp_path): monkeypatch.delenv("CONDA_PREFIX", raising=False) monkeypatch.delenv("CUDA_PATH", raising=False) monkeypatch.setenv("CUDA_HOME", "alias/..") - monkeypatch.setattr(find_static_lib_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) + monkeypatch.setattr(locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) real_root = tmp_path / "real" (real_root / "child").mkdir(parents=True) @@ -182,7 +183,7 @@ def test_locate_static_lib_preserves_symlink_parent(monkeypatch, tmp_path): def test_locate_static_lib_resolves_symlinked_file(monkeypatch, tmp_path): monkeypatch.delenv("CONDA_PREFIX", raising=False) monkeypatch.delenv("CUDA_PATH", raising=False) - monkeypatch.setattr(find_static_lib_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) + monkeypatch.setattr(locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) root = tmp_path / "toolkit" monkeypatch.setenv("CUDA_HOME", str(root)) info = CUDADEVRT_INFO @@ -211,7 +212,7 @@ def test_locate_static_lib_conda_rel_path_fallback(monkeypatch, tmp_path): conda_path = _make_static_lib_file(conda_lib_dir, filename) monkeypatch.setattr( - find_static_lib_module, + locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [], ) @@ -271,7 +272,7 @@ def test_find_static_lib_not_found_error_includes_cuda_home_directory_listing(mo extra_file.write_text("placeholder", encoding="utf-8") monkeypatch.setattr( - find_static_lib_module, + locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [], ) @@ -294,7 +295,7 @@ def test_find_static_lib_not_found_error_without_cuda_home(monkeypatch): filename = CUDADEVRT_INFO["filename"] monkeypatch.setattr( - find_static_lib_module, + locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: [], ) From e5d320ffad7891ff85ced81acc9441baad787dde Mon Sep 17 00:00:00 2001 From: Rob Parolin Date: Wed, 25 Nov 2026 15:52:03 -0700 Subject: [PATCH 2/4] docs(pathfinder): describe the shared static/bitcode search accurately `not_found_message` describes the first `CUDA_PATH` directory tried, not the last place searched; its docstring now says so. `AGENTS.md` names `_static_libs/locate_file.py` as the search both finders share. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Rob Parolin --- cuda_pathfinder/AGENTS.md | 3 +++ cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/cuda_pathfinder/AGENTS.md b/cuda_pathfinder/AGENTS.md index 2b6a8e03115f..f3fdb7784c1a 100644 --- a/cuda_pathfinder/AGENTS.md +++ b/cuda_pathfinder/AGENTS.md @@ -28,6 +28,9 @@ Windows. - **Load orchestration**: - `load_nvidia_dynamic_lib.py` coordinates find/load phases, dependency loading, driver-lib fast path, and cache semantics. +- **Static and bitcode libraries**: + - `_static_libs/locate_file.py` holds the one search that + `find_static_lib.py` and `find_bitcode_lib.py` share. - **Process isolation helper**: - `cuda/pathfinder/_utils/spawned_process_runner.py` is used where process global dynamic loader state would otherwise leak across tests. diff --git a/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py b/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py index d4501b406692..92ae44d10918 100644 --- a/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py +++ b/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py @@ -57,7 +57,7 @@ def locate_file( def not_found_message(filename: str, ctk_rel_paths: tuple[str, ...]) -> str: - """Explain a :func:`locate_file` miss by describing the last place it searched.""" + """Explain a :func:`locate_file` miss by describing the first ``CUDA_PATH`` directory it tried.""" cuda_home = get_cuda_path_or_home() if cuda_home is None: return f'Failure finding "{filename}": CUDA_HOME/CUDA_PATH not set\n' From ecb564c811c7c38af7ff7c9c8d404d02f37abdef Mon Sep 17 00:00:00 2001 From: Rob Parolin Date: Thu, 26 Nov 2026 10:59:40 -0700 Subject: [PATCH 3/4] fix(pathfinder): describe the CUDA root that was searched in not-found errors `locate_file` read `get_cuda_path_or_home()` to search, and `not_found_message` read it a second time to write the error. The original finders read it once. If two threads looked up at the same time on a cold cache while `CUDA_HOME` changed, the error could name a directory that was never searched. A review bot found this. `locate_file` now raises the finder's own error itself, from the root it read. The callers pass their error class and lose their `if found is None` branch. The message text is unchanged. A new test fails on the old code and passes now. The static and bitcode comparison against the original code is still byte-identical (831 scenarios). Co-Authored-By: Claude Fable 5.2 Signed-off-by: Rob Parolin --- .../_static_libs/find_bitcode_lib.py | 8 +++----- .../pathfinder/_static_libs/find_static_lib.py | 8 +++----- .../pathfinder/_static_libs/locate_file.py | 16 ++++++++++------ cuda_pathfinder/tests/test_find_bitcode_lib.py | 18 ++++++++++++++++++ 4 files changed, 34 insertions(+), 16 deletions(-) diff --git a/cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py b/cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py index 71c84f154062..d9fb53f3983c 100644 --- a/cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py +++ b/cuda_pathfinder/cuda/pathfinder/_static_libs/find_bitcode_lib.py @@ -5,7 +5,7 @@ from dataclasses import dataclass from typing import TypedDict -from cuda.pathfinder._static_libs.locate_file import locate_file, not_found_message +from cuda.pathfinder._static_libs.locate_file import locate_file from cuda.pathfinder._utils.platform_aware import IS_WINDOWS @@ -77,15 +77,13 @@ def locate_bitcode_lib(name: str) -> LocatedBitcodeLib: filename = info["filename"] rel_paths = (info["rel_path"],) - found = locate_file( + abs_path, found_via = locate_file( filename, site_packages_dirs=info["site_packages_dirs"], conda_rel_paths=rel_paths, ctk_rel_paths=rel_paths, + not_found_error=BitcodeLibNotFoundError, ) - if found is None: - raise BitcodeLibNotFoundError(not_found_message(filename, rel_paths)) - abs_path, found_via = found return LocatedBitcodeLib(name=name, abs_path=abs_path, filename=filename, found_via=found_via) diff --git a/cuda_pathfinder/cuda/pathfinder/_static_libs/find_static_lib.py b/cuda_pathfinder/cuda/pathfinder/_static_libs/find_static_lib.py index d8b5678cbb62..302109e0295a 100644 --- a/cuda_pathfinder/cuda/pathfinder/_static_libs/find_static_lib.py +++ b/cuda_pathfinder/cuda/pathfinder/_static_libs/find_static_lib.py @@ -6,7 +6,7 @@ from pathlib import Path from typing import TypedDict -from cuda.pathfinder._static_libs.locate_file import locate_file, not_found_message +from cuda.pathfinder._static_libs.locate_file import locate_file from cuda.pathfinder._utils.platform_aware import IS_WINDOWS from cuda.pathfinder._utils.windows_arch import windows_python_arch @@ -73,15 +73,13 @@ def locate_static_lib(name: str) -> LocatedStaticLib: info = _SUPPORTED_STATIC_LIBS_INFO[name] filename = info["filename"] - found = locate_file( + abs_path, found_via = locate_file( filename, site_packages_dirs=info["site_packages_dirs"], conda_rel_paths=info["conda_rel_paths"], ctk_rel_paths=info["ctk_rel_paths"], + not_found_error=StaticLibNotFoundError, ) - if found is None: - raise StaticLibNotFoundError(not_found_message(filename, info["ctk_rel_paths"])) - abs_path, found_via = found return LocatedStaticLib(name=name, abs_path=abs_path, filename=filename, found_via=found_via) diff --git a/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py b/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py index 92ae44d10918..941d1f7bdad2 100644 --- a/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py +++ b/cuda_pathfinder/cuda/pathfinder/_static_libs/locate_file.py @@ -26,11 +26,16 @@ def locate_file( site_packages_dirs: tuple[str, ...], conda_rel_paths: tuple[str, ...], ctk_rel_paths: tuple[str, ...], -) -> tuple[str, str] | None: - """Return ``(abs_path, found_via)`` for the first place that has *filename*, else ``None``. + not_found_error: type[Exception], +) -> tuple[str, str]: + """Return ``(abs_path, found_via)`` for the first place that has *filename*. Search order: NVIDIA wheels (``site-packages``), ``$CONDA_PREFIX``, then ``$CUDA_PATH`` / ``$CUDA_HOME``. Directories are tried first-to-last. + + Raises: + not_found_error: If no place has *filename*. The message describes the + ``CUDA_PATH`` root that this search read. """ for rel_dir in site_packages_dirs: for abs_dir in find_sub_dirs_all_sitepackages(tuple(rel_dir.split("/"))): @@ -53,12 +58,11 @@ def locate_file( if abs_path is not None: return abs_path, "CUDA_PATH" - return None + raise not_found_error(_not_found_message(filename, cuda_home, ctk_rel_paths)) -def not_found_message(filename: str, ctk_rel_paths: tuple[str, ...]) -> str: - """Explain a :func:`locate_file` miss by describing the first ``CUDA_PATH`` directory it tried.""" - cuda_home = get_cuda_path_or_home() +def _not_found_message(filename: str, cuda_home: str | None, ctk_rel_paths: tuple[str, ...]) -> str: + """Explain a miss by describing the first directory tried under *cuda_home*.""" if cuda_home is None: return f'Failure finding "{filename}": CUDA_HOME/CUDA_PATH not set\n' diff --git a/cuda_pathfinder/tests/test_find_bitcode_lib.py b/cuda_pathfinder/tests/test_find_bitcode_lib.py index a308b74c0bdd..098a8b89d590 100644 --- a/cuda_pathfinder/tests/test_find_bitcode_lib.py +++ b/cuda_pathfinder/tests/test_find_bitcode_lib.py @@ -267,3 +267,21 @@ def test_find_bitcode_lib_not_found_error_without_cuda_home(monkeypatch): def test_find_bitcode_lib_invalid_name(): with pytest.raises(ValueError, match="Unknown bitcode library"): find_bitcode_lib_module.locate_bitcode_lib("invalid") + + +@pytest.mark.usefixtures("clear_find_bitcode_lib_cache") +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_not_found_error_describes_the_root_that_was_searched(monkeypatch, tmp_path): + """The error names the CUDA root the search read, even if a second read would differ.""" + monkeypatch.delenv("CONDA_PREFIX", raising=False) + monkeypatch.setattr(locate_file_module, "find_sub_dirs_all_sitepackages", lambda _sub_dir: []) + searched_root = tmp_path / "searched" + other_root = tmp_path / "other" + roots = iter([str(searched_root), str(other_root)]) + monkeypatch.setattr(locate_file_module, "get_cuda_path_or_home", lambda: next(roots)) + + with pytest.raises(BitcodeLibNotFoundError) as exc_info: + locate_bitcode_lib("device") + + assert str(searched_root) in str(exc_info.value) + assert str(other_root) not in str(exc_info.value) From 358af9be66bdfed9d51ed7d749e8f949e671cc5e Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Thu, 26 Nov 2026 11:17:26 -0800 Subject: [PATCH 4/4] ci: require manual copy-pr-bot approval Signed-off-by: Ralf W. Grosse-Kunstleve