Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -170,16 +170,19 @@ def _load_lib_no_cache(libname: str) -> LoadedDL:

ctx = SearchContext(desc)

# Phase 1: Try to find the library file on disk (pip wheels, conda).
find = run_find_steps(ctx, EARLY_FIND_STEPS)

# Phase 2: Cross-cutting — already-loaded check and dependency loading.
# An already-loaded library bypasses the wheel and conda search.
loaded = LOADER.check_if_already_loaded_from_elsewhere(desc)
find = None
if loaded is None:
find = run_find_steps(ctx, EARLY_FIND_STEPS)
# Another component may have loaded the library during discovery.
loaded = LOADER.check_if_already_loaded_from_elsewhere(desc)

load_dependencies(desc, load_nvidia_dynamic_lib)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This runs before the already-loaded return, so an already-loaded library still searches the disk for each unloaded dependency. If an optional dependency such as nvrtc is not loaded and its search hits a PermissionError from an unreadable wheel directory, the call fails even though cudnn is already loaded. I saw this with mocks earlier (cudnn loaded, nvrtc not loaded, site-packages listing raises PermissionError); I have not re-run it on the current head.

The PR text and the draft release note say an already-loaded library no longer fails on a search error. That holds only when its dependencies are also loaded. Either narrow that claim, or make the listing failure an attachment line so the search ends in DynamicLibNotFoundError and optional-dependency suppression applies. Either way, add a test for an already-loaded cudnn with an unloaded nvrtc and an unreadable wheel directory.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced on the current head: an already-loaded cudnn failed with PermissionError when nvrtc was not loaded and its wheel directory could not be listed.

The failure came from the unguarded os.listdir that builds the not-found message. Fixed in 6d9a2ea: a listing failure is now a LISTDIR FAILED line in that message, so the search ends in DynamicLibNotFoundError and optional-dependency suppression applies. The same guard covers the lib-dir search on both platforms.

Added the test you asked for (loaded cudnn, unloaded nvrtc, unlistable wheel directory), plus one for the lib-dir path on Linux and Windows. With this, the PR text and release note hold as written.

if loaded is not None:
return loaded

# Phase 3: Load from found path, or fall back to system search + late find.
# 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)

Expand Down
20 changes: 14 additions & 6 deletions cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,24 @@
from cuda.pathfinder._utils.windows_arch import windows_pe_matches_arch, windows_python_arch


def _append_dir_listing(dirpath: str, attachments: list[str]) -> None:
# The listing only illustrates a miss. A directory that cannot be listed is
# reported in the not-found message so the search can move on to the next location.
try:
nodes = sorted(os.listdir(dirpath))
except OSError as exc:
attachments.append(f" LISTDIR FAILED: {type(exc).__name__}: {exc}")
return
attachments.extend(f" {node}" for node in nodes)


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}")
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}")
_append_dir_listing(sub_dir, attachments)


def _find_descriptor_so_under_dir(dirpath: str, desc: LibDescriptor) -> str | None:
Expand Down Expand Up @@ -181,8 +191,7 @@ def find_in_lib_dir(
if not os.path.isdir(lib_dir):
attachments.append(" DIRECTORY DOES NOT EXIST")
else:
for node in sorted(os.listdir(lib_dir)):
attachments.append(f" {node}")
_append_dir_listing(lib_dir, attachments)
return None


Expand Down Expand Up @@ -255,8 +264,7 @@ def find_in_lib_dir(
if not os.path.isdir(lib_dir):
attachments.append(" DIRECTORY DOES NOT EXIST")
else:
for node in sorted(os.listdir(lib_dir)):
attachments.append(f" {node}")
_append_dir_listing(lib_dir, attachments)
return None


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def find_in_program_files_roots(ctx: SearchContext) -> FindResult | None:
# Step sequences per strategy
# ---------------------------------------------------------------------------

#: Find steps that run before the already-loaded check and system search.
#: Find steps that run after the already-loaded check and before system search.
EARLY_FIND_STEPS: tuple[FindStep, ...] = (find_in_site_packages, find_in_conda)

#: Find steps that run after system search fails.
Expand Down
155 changes: 146 additions & 9 deletions cuda_pathfinder/tests/test_load_nvidia_dynamic_lib_using_mocker.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import os
from pathlib import Path

import pytest
Expand All @@ -12,7 +13,7 @@
_load_lib_no_cache,
_resolve_system_loaded_abs_path_in_subprocess,
)
from cuda.pathfinder._dynamic_libs.search_platform import WindowsSearchPlatform
from cuda.pathfinder._dynamic_libs.search_platform import LinuxSearchPlatform, WindowsSearchPlatform
from cuda.pathfinder._dynamic_libs.search_steps import EARLY_FIND_STEPS, SearchContext
from cuda.pathfinder._utils.platform_aware import IS_WINDOWS

Expand Down Expand Up @@ -174,7 +175,7 @@ def _run_find_steps_disabled(ctx, steps):
@pytest.mark.parametrize("preferred_source", ("site-packages", "conda", "system-search"))
@pytest.mark.agent_authored(model="gpt-6.1-sol")
def test_cuda_path_is_a_fallback_to_environment_and_native_search(tmp_path, mocker, monkeypatch, preferred_source):
desc = load_mod.LIB_DESCRIPTORS["cublasLt"]
desc = load_mod.LIB_DESCRIPTORS["cublas"]
platform = steps_mod.PLATFORM
filename = desc.windows_dlls[0] if IS_WINDOWS else desc.linux_sonames[0]

Expand Down Expand Up @@ -208,20 +209,21 @@ def find_wheel_dirs(sub_dirs):
side_effect=find_wheel_dirs,
)
mocker.patch.object(load_mod.LOADER, "check_if_already_loaded_from_elsewhere", return_value=None)
mocker.patch(f"{_MODULE}.load_dependencies")
load_dependency = mocker.patch(f"{_MODULE}.load_nvidia_dynamic_lib")
native_path = tmp_path / "native" / filename
native_search = mocker.patch.object(
load_mod.LOADER,
"load_with_system_search",
return_value=_make_loaded_dl(str(native_path), "system-search"),
)
mocker.patch.object(
load_mod.LOADER,
"load_with_abs_path",
side_effect=lambda _desc, path, via: _make_loaded_dl(path, via),
)

loaded = _load_lib_no_cache("cublasLt")
def load_from_discovered_path(_desc, path, via):
load_dependency.assert_called_once_with("cublasLt")
return _make_loaded_dl(path, via)

mocker.patch.object(load_mod.LOADER, "load_with_abs_path", side_effect=load_from_discovered_path)

loaded = _load_lib_no_cache("cublas")

expected_path = {"site-packages": wheel_path, "conda": conda_path, "system-search": native_path}[preferred_source]
assert loaded.found_via == preferred_source
Expand Down Expand Up @@ -274,3 +276,138 @@ def _run_find_steps_without_site_packages(ctx, steps):
result = _load_lib_no_cache("cupti")
assert result.found_via == "conda"
assert result.abs_path == str(conda_cupti_lib)


@pytest.mark.agent_authored(model="claude-fable-5-2")
def test_already_loaded_library_skips_the_disk_search_but_loads_dependencies(mocker):
"""An unreadable search location must not break a library that is already loaded."""
desc = load_mod.LIB_DESCRIPTORS["cublas"]
already_loaded = _make_loaded_dl("/opt/elsewhere/libcublas.so.13", "was-already-loaded-from-elsewhere")
mocker.patch.object(load_mod.LOADER, "check_if_already_loaded_from_elsewhere", return_value=already_loaded)
load_dependencies = mocker.patch(f"{_MODULE}.load_dependencies")
unreadable = mocker.patch(
"cuda.pathfinder._dynamic_libs.search_platform.find_sub_dirs_all_sitepackages",
side_effect=PermissionError("site-packages is not readable"),
)

assert _load_lib_no_cache("cublas") is already_loaded
unreadable.assert_not_called()
load_dependencies.assert_called_once_with(desc, load_mod.load_nvidia_dynamic_lib)


@pytest.mark.parametrize("find_succeeds", [True, False], ids=["wheel-found", "wheel-missed"])
@pytest.mark.agent_authored(model="gpt-6")
def test_library_loaded_during_early_search_reuses_existing_handle(tmp_path, mocker, find_succeeds):
desc = load_mod.LIB_DESCRIPTORS["cublas"]
filename = desc.windows_dlls[0] if IS_WINDOWS else desc.linux_sonames[0]
already_loaded = LoadedDL(str(tmp_path / "external" / filename), True, 0xBEEF, "was-already-loaded-from-elsewhere")
probe = mocker.patch.object(load_mod.LOADER, "check_if_already_loaded_from_elsewhere", return_value=None)
load_dependencies = mocker.patch(f"{_MODULE}.load_dependencies")
calls = mocker.Mock()
calls.attach_mock(probe, "probe")
calls.attach_mock(load_dependencies, "load_dependencies")

def discover(_ctx, steps):
assert steps is EARLY_FIND_STEPS
probe.return_value = already_loaded
if find_succeeds:
return steps_mod.FindResult(str(tmp_path / "wheel" / filename), "site-packages")
return None

mocker.patch(f"{_MODULE}.run_find_steps", side_effect=discover)
load_wheel = mocker.patch.object(load_mod.LOADER, "load_with_abs_path")
load_native = mocker.patch.object(load_mod.LOADER, "load_with_system_search")

assert _load_lib_no_cache("cublas") is already_loaded
load_wheel.assert_not_called()
load_native.assert_not_called()
assert calls.mock_calls == [
mocker.call.probe(desc),
mocker.call.probe(desc),
mocker.call.load_dependencies(desc, load_mod.load_nvidia_dynamic_lib),
]


@pytest.mark.agent_authored(model="gpt-6")
def test_unloaded_library_search_failure_precedes_dependency_loading(mocker):
probe = mocker.patch.object(load_mod.LOADER, "check_if_already_loaded_from_elsewhere", return_value=None)
failure = PermissionError("site-packages is not readable")
mocker.patch(f"{_MODULE}.run_find_steps", side_effect=failure)
load_dependencies = mocker.patch(f"{_MODULE}.load_dependencies")

with pytest.raises(PermissionError) as exc_info:
_load_lib_no_cache("cublas")

assert exc_info.value is failure
probe.assert_called_once()
load_dependencies.assert_not_called()


def _make_wheel_dir_unlistable(tmp_path, mocker):
"""Offer one wheel directory to the site-packages search and make listing it fail."""
wheel_dir = tmp_path / "unreadable-wheel"
wheel_dir.mkdir()
real_listdir = os.listdir

def listdir(path):
if str(path) == str(wheel_dir):
raise PermissionError(13, "Permission denied", str(wheel_dir))
return real_listdir(path)

mocker.patch(
"cuda.pathfinder._dynamic_libs.search_platform.find_sub_dirs_all_sitepackages",
return_value=[str(wheel_dir)],
)
mocker.patch("cuda.pathfinder._dynamic_libs.search_platform.os.listdir", side_effect=listdir)
return wheel_dir


@pytest.mark.agent_authored(model="claude-fable-5-2")
def test_already_loaded_library_survives_unlistable_wheel_dir_of_optional_dependency(tmp_path, mocker, monkeypatch):
"""cudnn is loaded, its optional nvrtc is not, and nvrtc's wheel directory cannot be listed."""
cudnn_loaded = _make_loaded_dl("/opt/elsewhere/libcudnn.so.9", "was-already-loaded-from-elsewhere")
mocker.patch.object(
load_mod.LOADER,
"check_if_already_loaded_from_elsewhere",
side_effect=lambda desc: cudnn_loaded if desc.name == "cudnn" else None,
)
wheel_dir = _make_wheel_dir_unlistable(tmp_path, mocker)
monkeypatch.delenv("CONDA_PREFIX", raising=False)
mocker.patch.object(load_mod.LOADER, "load_with_system_search", return_value=None)
mocker.patch(f"{_MODULE}.LATE_FIND_STEPS", ())
mocker.patch(f"{_MODULE}._resolve_system_loaded_abs_path_in_subprocess", return_value=None)
load_with_abs_path = mocker.patch.object(load_mod.LOADER, "load_with_abs_path")
nvrtc_errors = []

def load_dependency(name):
if name != "nvrtc":
return _make_loaded_dl(name, "dependency")
try:
return _load_lib_no_cache("nvrtc")
except Exception as exc:
nvrtc_errors.append(exc)
raise

mocker.patch(f"{_MODULE}.load_nvidia_dynamic_lib", side_effect=load_dependency)

assert _load_lib_no_cache("cudnn") is cudnn_loaded
load_with_abs_path.assert_not_called()
# The unlistable directory is reported in the suppressed not-found error, not hidden.
(nvrtc_error,) = nvrtc_errors
assert type(nvrtc_error) is DynamicLibNotFoundError
assert f'listdir("{wheel_dir}"):' in str(nvrtc_error)
assert "LISTDIR FAILED: PermissionError" in str(nvrtc_error)


@pytest.mark.parametrize("platform", (LinuxSearchPlatform(), WindowsSearchPlatform(target_arch="x64")), ids=type)
@pytest.mark.agent_authored(model="claude-fable-5-2")
def test_find_in_lib_dir_reports_an_unlistable_directory_as_a_miss(tmp_path, mocker, platform):
wheel_dir = _make_wheel_dir_unlistable(tmp_path, mocker)
error_messages, attachments = [], []

found = platform.find_in_lib_dir(str(wheel_dir), load_mod.LIB_DESCRIPTORS["nvrtc"], error_messages, attachments)

assert found is None
assert len(error_messages) == 1
assert attachments[0] == f' listdir("{wheel_dir}"):'
assert attachments[1].startswith(" LISTDIR FAILED: PermissionError")
Loading