Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 result.found:
return result
missed += result
return missed


def _load_lib_no_cache(libname: str) -> LoadedDL:
Expand All @@ -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 early.found:
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 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_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 canary.found:
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
Expand Down
74 changes: 47 additions & 27 deletions cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@

import os
from collections.abc import Sequence
from dataclasses import dataclass, field
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
Expand All @@ -24,6 +24,28 @@
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)


@dataclass(frozen=True, slots=True)
class SearchContext:
"""One library's search inputs, resolved for one target platform.
Expand All @@ -47,8 +69,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)
Expand All @@ -59,9 +79,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}')


Expand Down Expand Up @@ -105,14 +125,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:
Expand Down Expand Up @@ -149,32 +170,31 @@ 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) -> 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:
_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, 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:
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)
83 changes: 40 additions & 43 deletions cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -22,9 +26,10 @@
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,
find_lib_in_site_packages,
Expand All @@ -34,21 +39,8 @@

from .._utils.resolve_path import resolve_path

# ---------------------------------------------------------------------------
# Data types
# ---------------------------------------------------------------------------


@dataclass
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 | None]
FindStep = Callable[[SearchContext], FindResult | NotFound]


def _iter_lib_dirs(root: str, rel_dirs: tuple[str, ...]) -> Iterator[str]:
Expand All @@ -64,16 +56,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
result = find_lib_in_dir(ctx, lib_dir, found_via)
if result.found:
return result
missed += result
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)

Expand Down Expand Up @@ -127,7 +121,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")

Expand All @@ -137,39 +131,38 @@ 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()
return find_lib_in_site_packages(ctx)


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 result.found:
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,
Expand All @@ -182,20 +175,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 result.found:
return result
return None
missed += result
return missed


# ---------------------------------------------------------------------------
Expand All @@ -218,10 +213,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 result.found:
return result
return None
missed += result
return missed
Loading
Loading