Skip to content

refactor(pathfinder): write the "first hit, else every miss" loop once - #3632

Open
rparolin wants to merge 1 commit into
pathfinder-readability/22-plain-sub-dir-lookupfrom
pathfinder-readability/23-one-first-hit-loop
Open

rparolin wants to merge 1 commit into
pathfinder-readability/22-plain-sub-dir-lookupfrom
pathfinder-readability/23-one-first-hit-loop

Conversation

@rparolin

@rparolin rparolin commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

— codex on behalf of Ralf —

Description

Part 23 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). No behavior change.

Five functions repeated the same loop: take results in order, return the first hit, otherwise add up the misses. first_hit() in search_steps.py now holds it, and the five pass it their results:

  • _find_under_root
  • find_in_install_root_env_vars
  • find_in_program_files_roots
  • run_find_steps
  • _try_ctk_root_canary in load_nvidia_dynamic_lib.py

Results are produced lazily, so nothing after the first hit runs. That matters for the canary step, which starts a subprocess per anchor: it still stops at the first root that has the library.

No behavior change. The existing run_find_steps tests cover the helper (first hit wins, later steps are not called, misses combine in order). Three planted bugs in the helper each fail the suite.

Testing

  • Full cuda_pathfinder test suite at this commit: 1298 passed, 6 skipped (Linux, Python 3.14).
  • pre-commit clean, including mypy-pathfinder. mypy also passes with --platform win32.
  • The step-by-step comparisons against main are still byte-identical (Linux, simulated Windows x64 and arm64), and all 526 public-API scenarios give the same result as fix(pathfinder): check for an already-loaded library before searching the disk #3623.
  • 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 26, 2026 18:40
@copy-pr-bot

copy-pr-bot Bot commented Nov 26, 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 26, 2026
@rparolin rparolin added the enhancement Any code-related improvements label Nov 26, 2026
@rparolin rparolin added this to the cuda.pathfinder next milestone Nov 26, 2026
@rparolin rparolin self-assigned this Nov 26, 2026
@rparolin
rparolin requested review from juenglin and rwgk November 26, 2026 18:42
@rparolin
rparolin marked this pull request as ready for review November 26, 2026 18:46
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 223c6f2 and 645b57c.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Refactor
    • CUDA library discovery retains its existing search order and results, and stops searching once a match is found.
    • If no library is found, search misses continue to be reported in order. Existing configurations and user-facing behavior remain unchanged; no new settings or steps are required.

The changes add first_hit to handle ordered search results and misses. Dynamic library searches, including the CTK root canary search, now use the helper. Search ordering, filters, and miss aggregation remain unchanged.

Changes: Dynamic library search

Layer / File(s) Summary
Add ordered result aggregation
cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py
Adds first_hit to lazily return the first found result or combine misses in iteration order.
Use shared aggregation in search paths
cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py, cuda_pathfinder/cuda/pathfinder/_dynamic_libs/load_nvidia_dynamic_lib.py
Uses first_hit for directory, environment-variable, Program Files, search-step, and CTK canary searches. Adds iterators for non-empty install-root environment variables, existing Program Files roots, and resolved CTK roots.

Suggested reviewers: cpcloud, dekhtiarjonathan

Change: Refactor

Merge Risk: Minimal · previous review e31a3

This refactor shares one search loop across the dynamic library lookups without changing which library is found or how errors are reported. No concrete risk was identified, and it looks safe to merge.

Architecture risk: Medium · up to e31a3

Dynamic-library searches now stop evaluating candidates after the first match, preserving search order and ordered miss aggregation.

Changed areas: cuda_pathfinder

Review details

Systems and components

  • observed — 2 changed files mapped to cuda_pathfinder.

Reliability and maintainability

  • inferred — Risk-relevant change factors for cuda_pathfinder: blast_radius_1; direct_dependents_1
- [ ] 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 ae3e5d5 and e31a3ad.

Files selected for processing: 2

  • cuda_pathfinder/cuda/pathfinder/_dynamic_libs/load_nvidia_dynamic_lib.py
  • cuda_pathfinder/cuda/pathfinder/_dynamic_libs/search_steps.py

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

@rwgk
rwgk removed this pull request from stack #3616 November 26, 2026 19:19
@rwgk
rwgk force-pushed the pathfinder-readability/23-one-first-hit-loop branch from 73d5042 to a0fac69 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
@github-actions

Copy link
Copy Markdown
Contributor

@NVIDIA NVIDIA deleted a comment from copy-pr-bot Bot Dec 3, 2026
@NVIDIA NVIDIA deleted a comment from copy-pr-bot Bot Dec 3, 2026
@NVIDIA NVIDIA deleted a comment from copy-pr-bot Bot Dec 3, 2026

@juenglin juenglin left a comment

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.

Behavior looks unchanged to me (static review of the diff). Three non-blocking readability suggestions that keep the generators.

Comment on lines +163 to +167
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.found:
return result
missed += result
return missed
roots = ((env_var, os.environ.get(env_var)) for env_var in ctx.install_root_env_vars)
return first_hit(_find_under_root(ctx, root, rel_dirs, env_var) for env_var, root in roots if root)

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.

Readability suggestion (non-blocking, no behavior change): the two-stage generator plus the trailing if root filter makes the reader assemble the "skip unset or empty env vars" rule from two expressions. A small named generator, in the style of _iter_lib_dirs, keeps the loop-and-if shape visible and leaves the caller as a one-line first_hit(...). It stays lazy, so os.environ.get is still read in the same order relative to the searches.

def _iter_install_root_env_vars(ctx: SearchContext) -> Iterator[tuple[str, str]]:
    """Yield (env_var, root) for each descriptor env var that is set and non-empty."""
    for env_var in ctx.install_root_env_vars:
        root = os.environ.get(env_var)
        if root:
            yield env_var, root


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
    return first_hit(
        _find_under_root(ctx, root, rel_dirs, env_var)
        for env_var, root in _iter_install_root_env_vars(ctx)
    )

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.

Done in ae3e5d5. Added _iter_install_root_env_vars as suggested.

Comment on lines 187 to +194
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, resolve_path(root), FOUND_VIA_PROGRAM_FILES)
if result.found:
return result
missed += result
return missed
return first_hit(
_find_under_anchor_root(ctx, resolve_path(root), FOUND_VIA_PROGRAM_FILES)
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 os.path.isdir(root)
)

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.

Readability suggestion (non-blocking, no behavior change): this is the hardest of the new expressions to read. It has a nested for, a sorted(...) with a key and reverse, and a filter, all inside one call argument. Moving the candidate enumeration into a named generator documents the ordering rule ("newest version first") and leaves the caller trivial. Laziness is unchanged: glob.glob for the next root_glob still runs only after the previous roots missed.

def _iter_program_files_roots(ctx: SearchContext) -> Iterator[str]:
    """Yield existing Program Files install roots, newest version first."""
    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 os.path.isdir(root):
                yield root


def find_in_program_files_roots(ctx: SearchContext) -> FindResult | NotFound:
    """Search descriptor-configured installation roots under Program Files."""
    return first_hit(
        _find_under_anchor_root(ctx, resolve_path(root), FOUND_VIA_PROGRAM_FILES)
        for root in _iter_program_files_roots(ctx)
    )

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.

Done in ae3e5d5. Added _iter_program_files_roots as suggested.

Comment on lines +64 to +67
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
result = find_via_ctk_root(ctx, ctk_root)
if result.found:
return result
missed += result
return missed
ctk_roots = (resolve_ctk_root_via_canary(libname) for libname in ctx.desc.ctk_root_canary_anchor_libnames)
return first_hit(find_via_ctk_root(ctx, ctk_root) for ctk_root in ctk_roots if ctk_root is not None)

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.

Readability suggestion (non-blocking, no behavior change): same idea here, to avoid chaining two generators with a None filter on the second. A named generator makes "skip anchors that do not resolve" explicit, and it stays lazy, so the canary probe subprocess still runs one anchor at a time and stops at the first hit.

def _iter_canary_ctk_roots(ctx: SearchContext) -> Iterator[str]:
    """Yield the CTK root found by each canary anchor library, skipping anchors that do not resolve."""
    for libname in ctx.desc.ctk_root_canary_anchor_libnames:
        ctk_root = resolve_ctk_root_via_canary(libname)
        if ctk_root is not None:
            yield ctk_root


def _try_ctk_root_canary(ctx: SearchContext) -> FindResult | NotFound:
    """Try CTK-root canary fallback for descriptor-configured libraries."""
    return first_hit(find_via_ctk_root(ctx, ctk_root) for ctk_root in _iter_canary_ctk_roots(ctx))

Please keep the helper in this module: resolve_ctk_root_via_canary is looked up as a module attribute here, and tests may patch it at this location. This file would also need Iterator imported (from collections.abc).

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.

Done in ae3e5d5. Added _iter_canary_ctk_roots, kept in this module so the resolve_ctk_root_via_canary patch point is unchanged. Iterator is imported under TYPE_CHECKING, since this file only uses it in annotations.

rparolin added a commit that referenced this pull request Dec 4, 2026
Review feedback on #3632. Three inline generator expressions become small
named generators, so each "skip this candidate" rule reads as a loop with
an if. All three stay lazy. No behavior change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@rparolin

rparolin commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

/ok to test e31a3ad

@rparolin

rparolin commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

@juenglin your three readability suggestions are in ae3e5d5. Could you take another look? This is the last PR in the stack still waiting on approval.

@rparolin
rparolin force-pushed the pathfinder-readability/23-one-first-hit-loop branch from e31a3ad to 223c6f2 Compare December 4, 2026 17:54
Five functions repeated the same loop: take results in order, return
the first hit, otherwise add up the misses. `first_hit()` in
`search_steps.py` now holds it, and the five pass it their results:

- `_find_under_root`
- `find_in_install_root_env_vars`
- `find_in_program_files_roots`
- `run_find_steps`
- `_try_ctk_root_canary` in `load_nvidia_dynamic_lib.py`

Results are produced lazily, so nothing after the first hit runs. That
matters for the canary step, which starts a subprocess per anchor: it
still stops at the first root that has the library.

No behavior change. The existing `run_find_steps` tests cover the helper
(first hit wins, later steps are not called, misses combine in order),
and three planted bugs in it each fail the suite.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Rob Parolin <rparolin@nvidia.com>
@rparolin
rparolin force-pushed the pathfinder-readability/23-one-first-hit-loop branch from 223c6f2 to 645b57c Compare December 4, 2026 20:44

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

cuda.pathfinder Everything related to the cuda.pathfinder module enhancement Any code-related improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants