Skip to content

fix(pathfinder): check for an already-loaded library before searching the disk - #3623

Open
rparolin wants to merge 5 commits into
mainfrom
pathfinder-readability/17-check-loaded-before-searching
Open

rparolin wants to merge 5 commits into
mainfrom
pathfinder-readability/17-check-loaded-before-searching

Conversation

@rparolin

@rparolin rparolin commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

— codex on behalf of Ralf —

Description

Part 1 of 23 of a readability stack for cuda.pathfinder (stack: #3623 → #3602 → #3603 → #3604 → #3605 → #3606 → #3607 → #3608 → #3609 → #3610 → #3611 → #3613 → #3618 → #3619 → #3620 → #3621 → #3622 → #3627 → #3628 → #3629 → #3630 → #3631 → #3632). Unlike the rest of the stack, this PR changes behavior on purpose. It fixes a failure; details below.

This changes behavior on purpose.

Before: _load_lib_no_cache searched site-packages and conda first, then checked whether the library was already loaded, and if it was, threw the search result away. A problem during that unused search, such as a wheel's library directory that cannot be listed, made load_nvidia_dynamic_lib fail for a library that was already loaded and usable.

After: the already-loaded check runs first, as the docstring's search order has always said ("0. Already loaded ... skip the rest of the search"). An already-loaded library is returned without touching the disk.

What changes for callers:

  • A library that is already loaded no longer fails because of a search error. This is the fix.
  • Dependencies are loaded before the wheel and conda search, not after it. If that search raises, the dependencies are already loaded.
  • On Windows, that leaves one more trace. Loading cufft or nvrtc as a dependency adds its folder to the DLL search list and to PATH. If the search for cufftw or mathdx then raises, the caller sees the same error as before, but the dependency is loaded and PATH has one more folder.
  • If a dependency is missing and the search would also have raised, the dependency's error now wins. Example: cusolver with an unlistable wheel directory and no nvJitLink raised PermissionError before and raises DynamicLibNotFoundError for nvJitLink now.
  • When the library is already loaded, site-packages is not listed, so find_sub_dirs caches nothing about it.

Nothing else changes. For every case in the comparison against main (all 50 libraries; Linux, simulated Windows x64 and arm64) results, error types and error text are identical.

Tests: one test fails on the old order with PermissionError and passes now. Two more pin that an already-loaded library still loads its dependencies and runs no search step, and the order of the first three steps: loaded check, dependencies, search. Four planted bugs in the changed lines each fail a test. 1297 passed, 6 skipped.

Release note, to add once the next version's notes file exists: "load_nvidia_dynamic_lib checks whether a library is already loaded before it searches site-packages and conda. A library that is already loaded no longer fails because a search location cannot be read."

Testing

  • Full cuda_pathfinder test suite at this commit: 1297 passed, 6 skipped (Linux, Python 3.14).
  • pre-commit clean, including mypy-pathfinder.
  • Not run on Windows. Windows rules are exercised by tests that simulate Windows on Linux.

PLC Local Security Evidence (Advisory)

Local advisory checks only, run over the whole stack. Not release-gate results.

Check Status Tool Details
Secrets SKIP Pulse Secret Scanner scanner image not available locally (registry login); the repo trufflehog pre-commit hook passed
SAST WARN Semgrep 1 finding, not from this stack: the existing subprocess.run call in the canary probe, now in canary_probe.py
Dependencies WARN pip-audit / osv-scanner no manifest or lockfile in scope, so the local scan could not run; this stack changes no dependencies
License N/A - no dependencies changed
Container N/A - no container changed

Checklist

  • I have read the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

🤖 Generated with Claude Code

@rparolin
rparolin added this pull request to stack #3616 November 25, 2026 23:32
@copy-pr-bot

copy-pr-bot Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@github-actions github-actions Bot added the cuda.pathfinder Everything related to the cuda.pathfinder module label Nov 25, 2026
@rparolin rparolin added the bug Something isn't working label Nov 25, 2026
@rparolin rparolin added this to the cuda.pathfinder next milestone Nov 25, 2026
@rparolin rparolin self-assigned this Nov 25, 2026
@rparolin
rparolin requested review from juenglin and rwgk November 25, 2026 23:33
@rparolin
rparolin marked this pull request as ready for review November 26, 2026 14:36
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Library loading now reuses a library that is already loaded, avoiding unnecessary package-location searches. Dependencies are still loaded when reusing an existing library. If a library becomes available during an early search, that loaded library is reused instead of loading another copy from a discovered or system location. If an early search encounters a permission error while the library is not loaded, loading stops and reports the error.
  • Documentation
    • Clarified that early package-location searches occur after checking for an already-loaded library and before searching the system.

The loader now checks for an already-loaded library before early discovery and checks again after discovery. Dependencies still load for a reused library. Tests cover both lookup checks, the cublas dependency path, and propagation of PermissionError.

Changes: Library Lookup

Layer / File(s) Summary
Loaded-library precedence
cuda_pathfinder/cuda/pathfinder/_dynamic_libs/load_nvidia_dynamic_lib.py, cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py, cuda_pathfinder/tests/test_load_nvidia_dynamic_lib_using_mocker.py
The loader checks for an already-loaded library before early discovery and checks again afterward. Tests verify that it skips discovery when a library is already loaded, reuses a library loaded during discovery, loads dependencies, and propagates a search PermissionError.

Possibly related PRs

  • NVIDIA/cuda-python#3627: Its Windows loader equivalence checks use this pull request as a comparison, and it edits the Windows wheel-directory helper.

Suggested reviewers: cpcloud

Change: Bug fix

Merge Risk: Minimal · up to 2afbe

This change lets an already-loaded CUDA library be reused without a disk search. That avoids failures caused by an unreadable wheel directory. Dependencies are still loaded, and a library loaded during discovery is still reused. No merge-blocking risk was found.

Security architecture risk: Low · up to 2afbe

Reusing a library that is already loaded avoids failures from unreadable package directories. The tradeoff is that, on Windows, a lookup can now change where later DLL loads search in cases where it previously stopped without changing the search path. The change does not give callers a new way to supply a DLL path.

Retained concerns

  • Low · security · observed: An initial Windows hit for a library configured to register its directory now updates process-wide DLL search state without requiring wheel or Conda discovery to complete. The base did not reach registration if discovery raised. The head can also leave the registration in place if a later dependency load fails, affecting subsequent DLL resolution in the same process.
Security review details

Security Blast Radius

  • inferred — The changed Windows search state can affect other DLL loads in the same process and child processes that inherit its PATH. It does not change machine-wide configuration. Whether a later load uses the added directory depends on the native search policy.

Trust Boundaries and Controls

  • observed — Wheel and Conda discovery locate candidate files; the base did not require a package match or compare its path with the loaded module before reusing the handle. Skipping discovery removes a possible error, not a module provenance check.

Resilience and Maintainability Implications

  • inferred — A failed call does not cache a successful result or undo a completed Windows directory registration. A retry can repeat the PATH append, and the result cache does not serialize overlapping first calls. Those properties predate this PR; the earlier hit makes them relevant in cases previously stopped by discovery.
- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 438058d and 2afbe62.

Files selected for processing: 2

  • cuda_pathfinder/cuda/pathfinder/_dynamic_libs/load_nvidia_dynamic_lib.py
  • cuda_pathfinder/tests/test_load_nvidia_dynamic_lib_using_mocker.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 9 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nitpick comments: 1

cuda_pathfinder/tests/test_load_nvidia_dynamic_lib_using_mocker.py: 1

281-281: Trivial · Maintainability & Code Quality · Quick win

suggestion: Use the canonical found_via constant.

Import FOUND_VIA_WAS_ALREADY_LOADED_FROM_ELSEWHERE from cuda.pathfinder._utils.found_via instead of repeating its value. This keeps the mocked result aligned with the production label. (raw.githubusercontent.com)

As per coding guidelines, “Do not type the label strings anywhere else.”

Source: Coding guidelines

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 0f9c5b9 and 2040340.

Files selected for processing: 2

  • cuda_pathfinder/cuda/pathfinder/_dynamic_libs/load_nvidia_dynamic_lib.py
  • cuda_pathfinder/tests/test_load_nvidia_dynamic_lib_using_mocker.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@github-actions

Copy link
Copy Markdown
Contributor

@rwgk

rwgk commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Some forensics (codex GPT-6.2-Sol ultra):

The bug was introduced on August 19, 2025, in PR #855, and first shipped in cuda-pathfinder 1.2.0. Before that change, _load_lib_no_cache returned an already-loaded library before searching disk. #855 moved the site-packages search ahead of that check so Windows could use the search result to decide whether to call AddDllDirectory. That also meant an unreadable wheel directory could raise before Pathfinder noticed the library was already loaded. Before #855 · After #855

PR #1003 added the explicit CONDA_PREFIX fallback to that same early search on September 25, 2025 Pacific time. Both searches preceded the already-loaded check starting in 1.3.0. Source at #1003

PR #2680 removed the Windows check’s dependency on the search result in August 2026 and left the order in place. PR #3623 restores the already-loaded check to the front.

@rwgk

rwgk commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

@rparolin fixing the long-standing bug seems to be the most important change in this stack.

I asked codex

I wonder: could we fix the bug without first having to go through the entire stack of 16 PRs below?

The rest seems like optional refactoring.

Could you maybe make a triage-kind-of pass to determine:

Can we reasonably work through the entire stack without holding back the bug fix?

codex response

Yes. I’d land a small standalone fix on main, then review the 16 refactoring PRs at their own pace. The fix uses the loader APIs already on main. PR #3623 · Current loader

I’d make the standalone patch slightly narrower than #3623. Check whether the target is already loaded, skip its disk search on a hit, and still resolve its dependencies. On a miss, keep searching before loading dependencies. That preserves the existing error precedence and Windows PATH behavior when the search fails.

I verified this in a temporary copy of main on Linux. With a preloaded test library and a real unreadable wheel directory, current main raised PermissionError and the patch returned the loaded handle. Ordinary wheel loading and the unloaded error case behaved as before. Native Windows remains to be verified in CI.

Replaying the loader file through all 16 layers produced one conflict, where #3607 changes how search misses are represented. The fix carried through the remaining layers after that resolution. For the separate review, I’d flag #3610 because it removes internal Windows aliases that the 1.6.1 release notes explicitly retained for backward compatibility. Both can be handled independently of shipping the fix. PR #3607 · PR #3610 · 1.6.1 release notes

rparolin and others added 3 commits November 26, 2026 11:17
… the disk

Probe the target library before searching site-packages and conda. A hit skips that search and still resolves dependencies. A miss keeps the existing search and dependency order.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Rob Parolin <rparolin@nvidia.com>

Signed-off-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
An already-loaded target still resolves dependencies. For an unloaded target, a discovery failure reaches the caller before dependency loading.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Rob Parolin <rparolin@nvidia.com>

Signed-off-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
Signed-off-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
@rwgk
rwgk removed this pull request from stack #3616 November 26, 2026 19:19
@rwgk
rwgk changed the base branch from pathfinder-readability/16-type-check-own-imports to main November 26, 2026 19:19
@rwgk
rwgk force-pushed the pathfinder-readability/17-check-loaded-before-searching branch from 323beb4 to 438058d Compare November 26, 2026 19:19
@copy-pr-bot

copy-pr-bot Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@rwgk
rwgk added this pull request to stack #3633 November 26, 2026 19:19
@rwgk

rwgk commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Update: after coordinating with @rparolin on DM, I re-stacked the 23 PRs so that this PR is now at the bottom of the stack (so that we get the bug fix in first). The PR descriptions are updated accordingly.

@rwgk

rwgk commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

codex GPT-6.2-Sol ultra findings:

  • [P2] The earlier probe can miss a concurrent load. I reproduced this on Linux with two test DSOs sharing the SONAME libcublasLt.so.13. When another thread loaded the external copy during wheel discovery, main reused its handle. fix(pathfinder): check for an already-loaded library before searching the disk #3623 opened the wheel copy and returned a different handle. On an initial miss, probe again after discovery and before resolving dependencies. Add a regression test that forces this interleaving. Loader code

  • [P3] The tests leave a successful-load ordering gap. The full Pathfinder suite still passed when I deliberately moved a successful wheel load ahead of dependency resolution. Extend an existing wheel-success test to assert that dependencies have been resolved by the time load_with_abs_path is called. Existing search-order tests

rwgk added 2 commits November 26, 2026 11:58
Probe again after the wheel and conda search on an initial miss. Reuse a library loaded by another component during discovery and preserve the already-loaded fast path.

Signed-off-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
Require the cuBLAS dependency to be resolved before loading the target discovered in a wheel or conda environment.

Signed-off-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
@rwgk

rwgk commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

One subtle case with the second probe added by Codex: if two Pathfinder calls overlap and the first loads the library while the second is searching, the second can report found_via="was-already-loaded-from-elsewhere" even though Pathfinder loaded it.

I’d like to preserve the provenance from the call that actually loaded the library. Copying find.found_via would describe the search candidate, which can be a different copy from the one whose handle we return.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working cuda.pathfinder Everything related to the cuda.pathfinder module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants