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
3 changes: 3 additions & 0 deletions cuda_pathfinder/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- **CTK-root canary probe**:
- `canary_probe.py` finds the CUDA Toolkit root by loading a canary library
in a fresh Python process. Library, header and binary discovery share it.
- **Static and bitcode libraries**:
- `_static_libs/locate_file.py` holds the one search that
`find_static_lib.py` and `find_bitcode_lib.py` share.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def _find_windows_compute_sanitizer(ctk_root: str) -> str | None:


def _resolve_ctk_root_via_canary() -> str | None:
from cuda.pathfinder._dynamic_libs.load_nvidia_dynamic_lib import resolve_ctk_root_via_canary
from cuda.pathfinder._dynamic_libs.canary_probe import resolve_ctk_root_via_canary

ctk_root: str | None = resolve_ctk_root_via_canary(CTK_ROOT_CANARY_ANCHOR_LIBNAMES[0])
return ctk_root
Expand Down
98 changes: 98 additions & 0 deletions cuda_pathfinder/cuda/pathfinder/_dynamic_libs/canary_probe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""The CTK-root canary probe, shared by library, header and binary discovery.

A "canary" library is loaded by the OS dynamic loader in a fresh Python
process, and the CUDA Toolkit root is derived from where the loader found it.
"""

from __future__ import annotations

import functools
import subprocess

from cuda.pathfinder._dynamic_libs.search_steps import derive_ctk_root
from cuda.pathfinder._dynamic_libs.subprocess_protocol import (
DYNAMIC_LIB_SUBPROCESS_CWD,
MODE_CANARY,
STATUS_OK,
DynamicLibSubprocessPayload,
build_dynamic_lib_subprocess_command,
parse_dynamic_lib_subprocess_payload,
)

_CANARY_PROBE_TIMEOUT_SECONDS = 10.0


def _coerce_subprocess_output(output: str | bytes | None) -> str:
if isinstance(output, bytes):
return output.decode(errors="replace")
return "" if output is None else output


def _raise_canary_probe_child_process_error(
*,
returncode: int | None = None,
timeout: float | None = None,
stderr: str | bytes | None = None,
) -> None:
if timeout is None:
error_line = f"Canary probe child process exited with code {returncode}."
else:
error_line = f"Canary probe child process timed out after {timeout} seconds."
raise ChildProcessError(
f"{error_line}\n"
"--- stderr-from-child-process ---\n"
f"{_coerce_subprocess_output(stderr)}"
"<end-of-stderr-from-child-process>\n"
)


@functools.cache
def _resolve_system_loaded_abs_path_in_subprocess(
libname: str,
*,
timeout: float = _CANARY_PROBE_TIMEOUT_SECONDS,
) -> str | None:
"""Resolve a canary library's absolute path in a fresh Python subprocess."""
try:
result = subprocess.run( # noqa: S603 - trusted argv: current interpreter + internal probe module
build_dynamic_lib_subprocess_command(MODE_CANARY, libname),
capture_output=True,
text=True,
timeout=timeout,
check=False,
cwd=DYNAMIC_LIB_SUBPROCESS_CWD,
)
except subprocess.TimeoutExpired as exc:
_raise_canary_probe_child_process_error(timeout=exc.timeout, stderr=exc.stderr)

if result.returncode != 0:
_raise_canary_probe_child_process_error(returncode=result.returncode, stderr=result.stderr)

payload: DynamicLibSubprocessPayload = parse_dynamic_lib_subprocess_payload(
result.stdout,
libname=libname,
error_label="Canary probe child process",
)
abs_path: str | None = payload.abs_path
if payload.status == STATUS_OK:
return abs_path
return None


def resolve_ctk_root_via_canary(canary_libname: str) -> str | None:
"""Resolve the CUDA Toolkit root from a system-loadable canary library.

The canary library's absolute path is resolved by the OS dynamic loader in
an isolated subprocess, which honors ``LD_LIBRARY_PATH`` on Linux and the
native DLL search on Windows. The toolkit root is then derived from that
path. Returns ``None`` if the canary cannot be resolved or no root can be
derived.
"""
canary_abs_path = _resolve_system_loaded_abs_path_in_subprocess(canary_libname)
if canary_abs_path is None:
return None
ctk_root: str | None = derive_ctk_root(canary_abs_path)
return ctk_root
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@

import functools
import struct
import subprocess
import sys
from typing import TYPE_CHECKING

from cuda.pathfinder._dynamic_libs.canary_probe import resolve_ctk_root_via_canary
from cuda.pathfinder._dynamic_libs.lib_descriptor import LIB_DESCRIPTORS
from cuda.pathfinder._dynamic_libs.load_dl_common import (
DynamicLibNotAvailableError,
Expand All @@ -25,18 +25,9 @@
FindResult,
NotFound,
SearchContext,
derive_ctk_root,
find_via_ctk_root,
run_find_steps,
)
from cuda.pathfinder._dynamic_libs.subprocess_protocol import (
DYNAMIC_LIB_SUBPROCESS_CWD,
MODE_CANARY,
STATUS_OK,
DynamicLibSubprocessPayload,
build_dynamic_lib_subprocess_command,
parse_dynamic_lib_subprocess_payload,
)
from cuda.pathfinder._dynamic_libs.supported_nvidia_libs import ALL_AVAILABLE_LIBNAMES
from cuda.pathfinder._utils.platform_aware import IS_WINDOWS

Expand All @@ -47,7 +38,6 @@
# (CTK, third-party, driver).
_ALL_KNOWN_LIBNAMES: frozenset[str] = frozenset(LIB_DESCRIPTORS)
_PLATFORM_NAME = "Windows" if IS_WINDOWS else "Linux"
_CANARY_PROBE_TIMEOUT_SECONDS = 10.0


def _load_driver_lib_no_cache(desc: LibDescriptor) -> LoadedDL:
Expand All @@ -70,79 +60,6 @@ def _load_driver_lib_no_cache(desc: LibDescriptor) -> LoadedDL:
)


def _coerce_subprocess_output(output: str | bytes | None) -> str:
if isinstance(output, bytes):
return output.decode(errors="replace")
return "" if output is None else output


def _raise_canary_probe_child_process_error(
*,
returncode: int | None = None,
timeout: float | None = None,
stderr: str | bytes | None = None,
) -> None:
if timeout is None:
error_line = f"Canary probe child process exited with code {returncode}."
else:
error_line = f"Canary probe child process timed out after {timeout} seconds."
raise ChildProcessError(
f"{error_line}\n"
"--- stderr-from-child-process ---\n"
f"{_coerce_subprocess_output(stderr)}"
"<end-of-stderr-from-child-process>\n"
)


@functools.cache
def _resolve_system_loaded_abs_path_in_subprocess(
libname: str,
*,
timeout: float = _CANARY_PROBE_TIMEOUT_SECONDS,
) -> str | None:
"""Resolve a canary library's absolute path in a fresh Python subprocess."""
try:
result = subprocess.run( # noqa: S603 - trusted argv: current interpreter + internal probe module
build_dynamic_lib_subprocess_command(MODE_CANARY, libname),
capture_output=True,
text=True,
timeout=timeout,
check=False,
cwd=DYNAMIC_LIB_SUBPROCESS_CWD,
)
except subprocess.TimeoutExpired as exc:
_raise_canary_probe_child_process_error(timeout=exc.timeout, stderr=exc.stderr)

if result.returncode != 0:
_raise_canary_probe_child_process_error(returncode=result.returncode, stderr=result.stderr)

payload: DynamicLibSubprocessPayload = parse_dynamic_lib_subprocess_payload(
result.stdout,
libname=libname,
error_label="Canary probe child process",
)
abs_path: str | None = payload.abs_path
if payload.status == STATUS_OK:
return abs_path
return None


def resolve_ctk_root_via_canary(canary_libname: str) -> str | None:
"""Resolve the CUDA Toolkit root from a system-loadable canary library.

The canary library's absolute path is resolved by the OS dynamic loader in
an isolated subprocess, which honors ``LD_LIBRARY_PATH`` on Linux and the
native DLL search on Windows. The toolkit root is then derived from that
path. Returns ``None`` if the canary cannot be resolved or no root can be
derived.
"""
canary_abs_path = _resolve_system_loaded_abs_path_in_subprocess(canary_libname)
if canary_abs_path is None:
return None
ctk_root: str | None = derive_ctk_root(canary_abs_path)
return ctk_root


def _try_ctk_root_canary(ctx: SearchContext) -> FindResult | NotFound:
"""Try CTK-root canary fallback for descriptor-configured libraries."""
missed = NotFound()
Expand Down
10 changes: 2 additions & 8 deletions cuda_pathfinder/cuda/pathfinder/_headers/find_nvidia_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING

from cuda.pathfinder._dynamic_libs.load_nvidia_dynamic_lib import (
_resolve_system_loaded_abs_path_in_subprocess,
)
from cuda.pathfinder._dynamic_libs.search_steps import derive_ctk_root
from cuda.pathfinder._dynamic_libs.canary_probe import resolve_ctk_root_via_canary
from cuda.pathfinder._headers.header_descriptor import (
HEADER_DESCRIPTORS,
platform_include_subdirs,
Expand Down Expand Up @@ -145,10 +142,7 @@ def find_via_ctk_root_canary(desc: HeaderDescriptor) -> LocatedHeaderDir | None:
"""
if not desc.use_ctk_root_canary:
return None
canary_abs_path = _resolve_system_loaded_abs_path_in_subprocess(CTK_ROOT_CANARY_ANCHOR_LIBNAMES[0])
if canary_abs_path is None:
return None
ctk_root = derive_ctk_root(canary_abs_path)
ctk_root = resolve_ctk_root_via_canary(CTK_ROOT_CANARY_ANCHOR_LIBNAMES[0])
if ctk_root is None:
return None
result = _locate_in_anchor_layout(desc, ctk_root)
Expand Down
6 changes: 2 additions & 4 deletions cuda_pathfinder/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,9 @@ def skip_if_missing_libnvcudla_so(libname: str, *, timeout: float) -> None:
return
# Keep the import inside the helper so unrelated import issues do not fail
# pytest collection for the whole test suite.
from cuda.pathfinder._dynamic_libs import load_nvidia_dynamic_lib as load_nvidia_dynamic_lib_module
from cuda.pathfinder._dynamic_libs.canary_probe import _resolve_system_loaded_abs_path_in_subprocess

canary_abs_path = load_nvidia_dynamic_lib_module._resolve_system_loaded_abs_path_in_subprocess(
"nvcudla", timeout=timeout
)
canary_abs_path = _resolve_system_loaded_abs_path_in_subprocess("nvcudla", timeout=timeout)
if canary_abs_path is not None:
return
pytest.skip("libnvcudla.so is not loadable via canary subprocess on this host.")
Loading
Loading