Skip to content

fix: use return value from download_virtctl_from_cluster()#388

Open
rgolangh wants to merge 1 commit into
RedHatQE:mainfrom
rgolangh:fix/virtctl-path-from-existing-binary
Open

fix: use return value from download_virtctl_from_cluster()#388
rgolangh wants to merge 1 commit into
RedHatQE:mainfrom
rgolangh:fix/virtctl-path-from-existing-binary

Conversation

@rgolangh
Copy link
Copy Markdown
Contributor

@rgolangh rgolangh commented Mar 25, 2026

Summary

  • Fix virtctl_binary fixture to use the return value from download_virtctl_from_cluster() instead of hardcoding shared_dir / "virtctl"
  • When virtctl already exists in PATH, the function returns early without downloading to shared_dir, causing a false ValueError
  • Remove redundant existence checks and duplicate add_to_path() call (handled internally by the function)

Test plan

  • Tested with virtctl in PATH → fixture succeeds (previously failed with ValueError)
  • Tested without virtctl in PATH → download and extraction works as before

Summary by CodeRabbit

  • Chores
    • Simplified test fixture initialization by streamlining dependency management and removing unnecessary validation steps during setup.

When virtctl already exists in PATH, download_virtctl_from_cluster()
returns early without writing to shared_dir. The fixture ignored the
return value and checked shared_dir/virtctl, which didn't exist.

Use the function's return value directly, which handles all cases:
PATH lookup, cached binary, fresh download.
@qodo-code-review
Copy link
Copy Markdown

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

Review Summary by Qodo

Fix virtctl_binary fixture to use function return value

🐞 Bug fix

Grey Divider

Walkthroughs

Description
• Use return value from download_virtctl_from_cluster() instead of hardcoding path
• Handles all virtctl lookup cases: PATH, cached binary, fresh download
• Remove redundant existence checks and duplicate add_to_path() call
• Fix false ValueError when virtctl exists in PATH
Diagram
flowchart LR
  A["virtctl_binary fixture"] -->|calls| B["download_virtctl_from_cluster"]
  B -->|returns| C["virtctl_path"]
  C -->|used directly| D["fixture returns path"]
  E["Removed: hardcoded path check"] -.->|eliminated| F["false ValueError"]
Loading

Grey Divider

File Changes

1. conftest.py 🐞 Bug fix +2/-9

Use download function return value directly

• Removed import of add_to_path function (no longer needed)
• Replaced hardcoded shared_dir / "virtctl" path with return value from
 download_virtctl_from_cluster()
• Removed redundant existence and executable checks before and after download
• Removed duplicate add_to_path() call (handled internally by download function)

conftest.py


Grey Divider

Qodo Logo

@qodo-code-review
Copy link
Copy Markdown

qodo-code-review Bot commented Mar 25, 2026

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (1) 📎 Requirement gaps (0) 📐 Spec deviations (0)

Grey Divider


Action required

1. Wrong virtctl chosen 🐞 Bug ✓ Correctness
Description
virtctl_binary now always calls download_virtctl_from_cluster(), which prefers any PATH-installed
virtctl over the cluster-versioned shared_dir cache, defeating the fixture’s version-based cache
invalidation and risking a virtctl/cluster incompatibility.
Code

conftest.py[R509-510]

        with filelock.FileLock(lock_file, timeout=600):
-            if not virtctl_path.is_file() or not os.access(virtctl_path, os.X_OK):
-                download_virtctl_from_cluster(client=ocp_admin_client, download_dir=shared_dir)
-                # Validate binary was downloaded successfully
-                if not virtctl_path.is_file() or not os.access(virtctl_path, os.X_OK):
-                    raise ValueError(f"Failed to download or make executable virtctl at {virtctl_path}")
+            virtctl_path = download_virtctl_from_cluster(client=ocp_admin_client, download_dir=shared_dir)
Evidence
The fixture explicitly builds a cluster-versioned shared directory to provide cache invalidation
when switching clusters, but download_virtctl_from_cluster() returns early if virtctl is found in
PATH, so a preinstalled (possibly stale) virtctl can be used instead of the cluster-matched
cached/downloaded binary. This is a semantic regression compared to the previous fixture logic,
which preferred shared_dir/virtctl and didn’t consult PATH unless the shared copy was missing.

conftest.py[477-487]
conftest.py[505-516]
utilities/virtctl.py[17-38]
utilities/virtctl.py[241-246]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`virtctl_binary` is intended to use a cluster-versioned cache directory to ensure the virtctl binary matches the current cluster version. After this PR, `download_virtctl_from_cluster()` may return a PATH-installed virtctl before checking the versioned cache directory, which bypasses version-based cache invalidation and can use an incompatible virtctl.

### Issue Context
- `conftest.py` derives `shared_dir` from `get_cluster_version_str(...)` specifically for cache invalidation.
- `utilities/virtctl.py::_check_existing_virtctl()` checks `shutil.which('virtctl')` before checking `download_dir / 'virtctl'`.

### Fix Focus Areas
- Update cache selection order (or add an opt-in flag) so `virtctl_binary` prefers the versioned `download_dir` binary over an arbitrary PATH binary.
- Ensure PATH is still updated to include the chosen binary’s parent directory.

- conftest.py[505-516]
- utilities/virtctl.py[17-38]
- utilities/virtctl.py[211-246]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Redundant virtctl_path alias 📘 Rule violation ⚙ Maintainability
Description
The fixture assigns virtctl_path to the direct return of download_virtctl_from_cluster() and
then immediately returns it, adding an unnecessary intermediate variable. This reduces conciseness
and violates the guideline to avoid alias-only variables in simple flows.
Code

conftest.py[R510-516]

+            virtctl_path = download_virtctl_from_cluster(client=ocp_admin_client, download_dir=shared_dir)
    except filelock.Timeout as err:
        raise TimeoutError(
            f"Timeout (600s) waiting for virtctl lock at {lock_file}. Another process may be stuck."
        ) from err

-    # Add to PATH for all workers
-    add_to_path(str(shared_dir))
    return virtctl_path
Evidence
PR Compliance ID 11 forbids introducing intermediate variables that simply alias another expression
without adding clarity. The added line assigns virtctl_path from
download_virtctl_from_cluster(...) and the fixture then returns virtctl_path without additional
processing.

CLAUDE.md
conftest.py[510-516]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`virtctl_path` is an intermediate variable that only aliases the return value of `download_virtctl_from_cluster()` and is immediately returned.

## Issue Context
This is in a fixture flow where the value is not transformed after assignment, so returning the expression directly is clearer and more concise.

## Fix Focus Areas
- conftest.py[510-516]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Cache check misses subdir 🐞 Bug ➹ Performance
Description
download_virtctl_from_cluster() can extract virtctl into a subdirectory but
_check_existing_virtctl() only checks download_dir/virtctl, so subsequent xdist workers may
re-download unnecessarily (sequentially under the lock).
Code

conftest.py[R509-510]

        with filelock.FileLock(lock_file, timeout=600):
-            if not virtctl_path.is_file() or not os.access(virtctl_path, os.X_OK):
-                download_virtctl_from_cluster(client=ocp_admin_client, download_dir=shared_dir)
-                # Validate binary was downloaded successfully
-                if not virtctl_path.is_file() or not os.access(virtctl_path, os.X_OK):
-                    raise ValueError(f"Failed to download or make executable virtctl at {virtctl_path}")
+            virtctl_path = download_virtctl_from_cluster(client=ocp_admin_client, download_dir=shared_dir)
Evidence
Extraction explicitly falls back to download_dir.rglob('virtctl') when download_dir/'virtctl' is
missing, meaning a valid extracted binary may live in a subdirectory. But
_check_existing_virtctl() does not perform the same rglob search, so other processes/workers
starting with a clean PATH won’t detect the already-extracted binary in shared_dir and will
download/extract again (lock prevents corruption, but not repeated work).

utilities/virtctl.py[32-38]
utilities/virtctl.py[178-187]
utilities/virtctl.py[241-246]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`_download_and_extract_virtctl()` supports archives where `virtctl` is not at `download_dir/virtctl` by searching subdirectories with `rglob`. However, `_check_existing_virtctl()` only checks `download_dir/virtctl`, so it may miss a previously extracted binary and trigger redundant downloads.

### Issue Context
This becomes more impactful with pytest-xdist because each worker process has its own environment; PATH changes from one worker don’t propagate to others, so they rely on the shared_dir cache to avoid repeated downloads.

### Fix Focus Areas
- Extend `_check_existing_virtctl(download_dir)` to also search `download_dir.rglob('virtctl')` and return an executable candidate.
- Keep PATH-preference behavior (if desired) but ensure the download_dir cache is actually detectable.

- utilities/virtctl.py[17-38]
- utilities/virtctl.py[127-196]
- utilities/virtctl.py[211-246]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 25, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 973fd90c-3dff-4993-b92a-ad246f9928ee

📥 Commits

Reviewing files that changed from the base of the PR and between c4484e0 and 249c7d1.

📒 Files selected for processing (1)
  • conftest.py

Walkthrough

The conftest.py fixture for virtctl_binary is simplified by removing the add_to_path import and validation logic. The fixture now directly returns the result of download_virtctl_from_cluster() without post-download checks or PATH modifications.

Changes

Cohort / File(s) Summary
Fixture Simplification
conftest.py
Removed add_to_path import and usage, eliminated virtctl_path variable and post-download validation (executable check). Fixture now returns directly from download_virtctl_from_cluster() call under file lock without additional PATH setup or verification.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: the fixture now uses the return value from download_virtctl_from_cluster() instead of hardcoding a path.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch fix/virtctl-path-from-existing-binary

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@redhat-qe-bot
Copy link
Copy Markdown

Report bugs in Issues

Welcome! 🎉

This pull request will be automatically processed with the following features:

🔄 Automatic Actions

  • Reviewer Assignment: Reviewers are automatically assigned based on the OWNERS file in the repository root
  • Size Labeling: PR size labels (XS, S, M, L, XL, XXL) are automatically applied based on changes
  • Issue Creation: Disabled for this repository
  • Branch Labeling: Branch-specific labels are applied to track the target branch
  • Auto-verification: Auto-verified users have their PRs automatically marked as verified
  • Labels: All label categories are enabled (default configuration)

📋 Available Commands

PR Status Management

  • /wip - Mark PR as work in progress (adds WIP: prefix to title)
  • /wip cancel - Remove work in progress status
  • /hold - Block PR merging (approvers only)
  • /hold cancel - Unblock PR merging
  • /verified - Mark PR as verified
  • /verified cancel - Remove verification status
  • /reprocess - Trigger complete PR workflow reprocessing (useful if webhook failed or configuration changed)
  • /regenerate-welcome - Regenerate this welcome message

Review & Approval

  • /lgtm - Approve changes (looks good to me)
  • /approve - Approve PR (approvers only)
  • /automerge - Enable automatic merging when all requirements are met (maintainers and approvers only)
  • /assign-reviewers - Assign reviewers based on OWNERS file
  • /assign-reviewer @username - Assign specific reviewer
  • /check-can-merge - Check if PR meets merge requirements

Testing & Validation

  • /retest tox - Run Python test suite with tox
  • /retest build-container - Rebuild and test container image
  • /retest conventional-title - Validate commit message format
  • /retest all - Run all available tests

Container Operations

  • /build-and-push-container - Build and push container image (tagged with PR number)
    • Supports additional build arguments: /build-and-push-container --build-arg KEY=value

Cherry-pick Operations

  • /cherry-pick <branch> - Schedule cherry-pick to target branch when PR is merged
    • Multiple branches: /cherry-pick branch1 branch2 branch3

Label Management

  • /<label-name> - Add a label to the PR
  • /<label-name> cancel - Remove a label from the PR

✅ Merge Requirements

This PR will be automatically approved when the following conditions are met:

  1. Approval: /approve from at least one approver
  2. Status Checks: All required status checks must pass
  3. No Blockers: No wip, hold, has-conflicts labels and PR must be mergeable (no conflicts)
  4. Verified: PR must be marked as verified

📊 Review Process

Approvers and Reviewers

Approvers:

  • myakove
  • solenoci

Reviewers:

  • krcmarik
  • myakove
  • solenoci
Available Labels
  • hold
  • verified
  • wip
  • lgtm
  • approve
  • automerge
AI Features
  • Conventional Title: Mode: fix (claude/claude-opus-4-6[1m])
  • Cherry-Pick Conflict Resolution: Enabled (claude/claude-opus-4-6[1m])

💡 Tips

  • WIP Status: Use /wip when your PR is not ready for review
  • Verification: The verified label is automatically removed on each new commit
  • Cherry-picking: Cherry-pick labels are processed when the PR is merged
  • Container Builds: Container images are automatically tagged with the PR number
  • Permission Levels: Some commands require approver permissions
  • Auto-verified Users: Certain users have automatic verification and merge privileges

For more information, please refer to the project documentation or contact the maintainers.

Comment thread conftest.py
Comment on lines 509 to +510
with filelock.FileLock(lock_file, timeout=600):
if not virtctl_path.is_file() or not os.access(virtctl_path, os.X_OK):
download_virtctl_from_cluster(client=ocp_admin_client, download_dir=shared_dir)
# Validate binary was downloaded successfully
if not virtctl_path.is_file() or not os.access(virtctl_path, os.X_OK):
raise ValueError(f"Failed to download or make executable virtctl at {virtctl_path}")
virtctl_path = download_virtctl_from_cluster(client=ocp_admin_client, download_dir=shared_dir)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Wrong virtctl chosen 🐞 Bug ✓ Correctness

virtctl_binary now always calls download_virtctl_from_cluster(), which prefers any PATH-installed
virtctl over the cluster-versioned shared_dir cache, defeating the fixture’s version-based cache
invalidation and risking a virtctl/cluster incompatibility.
Agent Prompt
### Issue description
`virtctl_binary` is intended to use a cluster-versioned cache directory to ensure the virtctl binary matches the current cluster version. After this PR, `download_virtctl_from_cluster()` may return a PATH-installed virtctl before checking the versioned cache directory, which bypasses version-based cache invalidation and can use an incompatible virtctl.

### Issue Context
- `conftest.py` derives `shared_dir` from `get_cluster_version_str(...)` specifically for cache invalidation.
- `utilities/virtctl.py::_check_existing_virtctl()` checks `shutil.which('virtctl')` before checking `download_dir / 'virtctl'`.

### Fix Focus Areas
- Update cache selection order (or add an opt-in flag) so `virtctl_binary` prefers the versioned `download_dir` binary over an arbitrary PATH binary.
- Ensure PATH is still updated to include the chosen binary’s parent directory.

- conftest.py[505-516]
- utilities/virtctl.py[17-38]
- utilities/virtctl.py[211-246]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants