Skip to content

Skip GPU detection for subcommands that don't need it - #2589

Open
bmahabirbu wants to merge 1 commit into
containers:mainfrom
bmahabirbu:skip-gpu-detection-lightweight
Open

Skip GPU detection for subcommands that don't need it#2589
bmahabirbu wants to merge 1 commit into
containers:mainfrom
bmahabirbu:skip-gpu-detection-lightweight

Conversation

@bmahabirbu

@bmahabirbu bmahabirbu commented Apr 4, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Subcommands like list, version, pull, rm, etc. don't need runtime plugin registration or GPU detection, but were paying the cost because all subcommand parsers were built together
  • Detects the subcommand early in phase 1 parsing and skips runtime/sandbox/daemon parser registration for lightweight subcommands
  • Avoids expensive GPU detection calls (e.g. nvidia-smi, CDI config lookups) for commands that never use them

Test plan

  • Verify lightweight subcommands (list, version, pull, rm, containers, login, logout, push, inspect, info, help, stop, chat) work without GPU detection
  • Verify GPU-dependent subcommands (run, serve, sandbox, daemon) still perform GPU detection as before
  • Run make validate to check lint/format/type checks

🤖 Generated with Claude Code

Summary by Sourcery

Optimize CLI argument parsing to avoid unnecessary runtime plugin registration and GPU detection for lightweight subcommands.

Enhancements:

  • Add early subcommand detection to classify lightweight commands and skip expensive parser setup for them.
  • Restrict runtime plugin subcommand registration and GPU-related setup to GPU-dependent commands while keeping lightweight commands fully functional.

@sourcery-ai

sourcery-ai Bot commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Adds a lightweight subcommand path to the CLI so that commands which do not require runtime plugin registration or GPU/GPU-detection setup can bypass that expensive initialization, while keeping existing behavior for GPU-dependent subcommands.

File-Level Changes

Change Details Files
Introduce a lightweight parsing path that detects the subcommand early and skips runtime plugin registration and GPU detection for known cheap subcommands.
  • Extend get_parser to accept a lightweight flag and forward it to subcommand configuration.
  • Use the phase-1 parse to capture remaining arguments, infer the requested subcommand, and compute a lightweight boolean for phase-2 parsing.
  • Add a LIGHTWEIGHT_SUBCOMMANDS set listing subcommands that do not require GPU-related initialization.
  • Short-circuit subcommand registration in configure_subcommands when lightweight is true so only lightweight subcommands are attached to the parser.
ramalama/cli.py
Restructure subcommand registration to always add lightweight subcommands directly and only register runtime-dependent subcommands and sandbox/daemon when not in lightweight mode.
  • Move direct parser registrations for lightweight subcommands ahead of any runtime-dependent registration logic.
  • Guard runtime plugin subcommand registration and sandbox/daemon parser registration behind the lightweight flag.
  • Clarify comments to document which subcommands need runtime plugin registration and GPU detection and which do not.
ramalama/cli.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot 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.

Hey - I've found 2 issues, and left some high level feedback:

  • The LIGHTWEIGHT_SUBCOMMANDS set duplicates the hard-coded subparser registrations in configure_subcommands; consider deriving this set from a single source of truth (e.g., constants next to each parser registration) to avoid drift when commands are added/renamed.
  • The lightweight detection logic assumes the first remaining token after phase 1 parse is the subcommand; if you expect patterns like prog --flag value -v list, it may be safer to scan remaining for the first non-option token instead of indexing remaining[0].
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `LIGHTWEIGHT_SUBCOMMANDS` set duplicates the hard-coded subparser registrations in `configure_subcommands`; consider deriving this set from a single source of truth (e.g., constants next to each parser registration) to avoid drift when commands are added/renamed.
- The lightweight detection logic assumes the first remaining token after phase 1 parse is the subcommand; if you expect patterns like `prog --flag value -v list`, it may be safer to scan `remaining` for the first non-option token instead of indexing `remaining[0]`.

## Individual Comments

### Comment 1
<location path="ramalama/cli.py" line_range="200" />
<code_context>

+    # Some subcommands (e.g. list, version) don't need runtime plugin registration
+    # or GPU detection, so skip the expensive parser setup for those.
+    subcommand = remaining[0] if remaining else None
+    lightweight = subcommand in LIGHTWEIGHT_SUBCOMMANDS
+
</code_context>
<issue_to_address>
**issue (performance):** Subcommand detection via `remaining[0]` can misclassify options as subcommands

`parse_known_args` groups all unknown tokens in `remaining`, including options, so assuming `remaining[0]` is the subcommand is unsafe. In `ramalama --plugin-opt val list`, you’d get `remaining = ['--plugin-opt', 'val', 'list']`, so `subcommand` becomes `'--plugin-opt'` and `lightweight` stays `False` even if `list` is lightweight. Consider identifying the subcommand as the first token in `remaining` that doesn’t start with `'-'`, or otherwise matching how `argparse` determines subparsers.
</issue_to_address>

### Comment 2
<location path="ramalama/cli.py" line_range="201-207" />
<code_context>
+    # Some subcommands (e.g. list, version) don't need runtime plugin registration
+    # or GPU detection, so skip the expensive parser setup for those.
+    subcommand = remaining[0] if remaining else None
+    lightweight = subcommand in LIGHTWEIGHT_SUBCOMMANDS
+
     # Phase 2: Re-parse the arguments with the subcommands enabled
</code_context>
<issue_to_address>
**issue (bug_risk):** Marking `help` as lightweight may prevent it from seeing runtime-specific subcommands

Because `help` is in `LIGHTWEIGHT_SUBCOMMANDS`, `ramalama help run` will set `lightweight=True` based on the top-level `help` subcommand. In that mode, runtime-registered subcommands (like `run`, `serve`, `bench`) are never registered, so `help` can’t show their usage. If `help` should cover all subcommands (including runtime ones), consider removing it from `LIGHTWEIGHT_SUBCOMMANDS` or special-casing `lightweight` for `help` so that it triggers full registration when needed.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread ramalama/cli.py Outdated
Comment thread ramalama/cli.py

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces a lightweight parser configuration for specific subcommands to optimize performance by skipping expensive runtime plugin registration and GPU detection. Feedback suggests that including the "help" command in the lightweight list prevents the full command set from being displayed and that the early return logic negatively impacts the subcommand ordering in help outputs.

Comment thread ramalama/cli.py Outdated
"chat",
"containers",
"ps",
"help",

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.

high

Including "help" in LIGHTWEIGHT_SUBCOMMANDS causes the ramalama help command to only display lightweight subcommands in its output. This is because the heavyweight commands (like run, serve, sandbox, and daemon) are skipped during parser configuration when lightweight is True. Removing "help" from this set ensures that the help subcommand always triggers a full parser setup and displays all available commands to the user.

Comment thread ramalama/cli.py Outdated
Comment on lines +361 to +362
if lightweight:
return

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.

medium

Returning early here changes the order of subcommands in the help output (e.g., ramalama --help). Previously, primary commands like run and serve (registered via the runtime plugin) appeared at the top of the subcommands list. With this change, they appear at the bottom after all lightweight commands. To maintain the original order while still benefiting from the optimization, consider wrapping the heavyweight registrations in if not lightweight: blocks at their original positions instead of using an early return.

@bmahabirbu
bmahabirbu force-pushed the skip-gpu-detection-lightweight branch from 193650c to 33c4e30 Compare April 4, 2026 00:56
@bmahabirbu
bmahabirbu temporarily deployed to macos-installer April 4, 2026 00:56 — with GitHub Actions Inactive
@bmahabirbu
bmahabirbu force-pushed the skip-gpu-detection-lightweight branch from 33c4e30 to de8e3c5 Compare April 4, 2026 03:01
@bmahabirbu
bmahabirbu temporarily deployed to macos-installer April 4, 2026 03:01 — with GitHub Actions Inactive

@mikebonnet mikebonnet left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM!

@mikebonnet
mikebonnet temporarily deployed to macos-installer April 7, 2026 15:58 — with GitHub Actions Inactive
Comment thread ramalama/cli.py


def configure_subcommands(parser):
# Subcommands that don't need runtime plugin registration or GPU detection.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@bmahabirbu it probably makes more sense to move the gpu detection call into the runtime plugin code path that actually depends on it. I can take a look at this in a follow-up, but might be a good idea to add some basic tests in this PR to ensure it doesn't regress?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this still true, @Oll did you ever work on this?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

No, was planning to look at it once this merges

@github-actions

github-actions Bot commented May 8, 2026

Copy link
Copy Markdown

A friendly reminder that this PR had no activity for 30 days.

Subcommands like list, version, pull, rm, etc. don't need runtime plugin
registration or GPU detection, but were paying the cost because all
subcommand parsers were built together. Detect the subcommand early in
phase 1 parsing and skip runtime/sandbox/daemon parser registration for
lightweight subcommands, avoiding expensive GPU detection calls.

Signed-off-by: Brian <bmahabir@redhat.com>
Signed-off-by: Brian <bmahabir@bu.edu>
@bmahabirbu
bmahabirbu force-pushed the skip-gpu-detection-lightweight branch from 246c12a to d3fd39f Compare June 17, 2026 06:14
@bmahabirbu
bmahabirbu temporarily deployed to macos-installer June 17, 2026 06:14 — with GitHub Actions Inactive
@coderabbitai

coderabbitai Bot commented Jun 17, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • Chores
    • Enhanced CLI startup performance through optimized argument parsing that intelligently skips unnecessary plugin registration and resource initialization for specific subcommands, reducing overhead and enabling faster execution.

Walkthrough

The CLI gains a "lightweight" parsing mode. A LIGHTWEIGHT_SUBCOMMANDS set is defined, and configure_subcommands and get_parser are updated to accept a lightweight flag that skips runtime plugin, sandbox, and daemon subcommand registration. parse_args_from_cmd detects the requested subcommand from CLI tokens and re-invokes the parser with the appropriate lightweight value.

Changes

Lightweight CLI parsing mode

Layer / File(s) Summary
LIGHTWEIGHT_SUBCOMMANDS set and conditional subcommand registration
ramalama/cli.py
Introduces the LIGHTWEIGHT_SUBCOMMANDS set. Extends configure_subcommands with a lightweight parameter that skips runtime plugin subcommand registration when true. Gates sandbox_parser and daemon_parser wiring behind not lightweight.
get_parser and parse_args_from_cmd lightweight wiring
ramalama/cli.py
Updates get_parser to accept and forward lightweight into configure_subcommands. Updates parse_args_from_cmd to locate the first non-option token from remaining args as the subcommand, check it against LIGHTWEIGHT_SUBCOMMANDS, and re-build the parser via get_parser(lightweight=...).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 Hoppy paths through the CLI,
Some commands need no GPU to fly!
A lightweight flag, a nimble parse,
Skipping plugins — nothing sparse.
Fast as a bunny through the grass! 🌿

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main optimization of skipping GPU detection for lightweight subcommands that don't need it.
Description check ✅ Passed The description is directly related to the changeset, providing context about the problem, solution, and test plan for skipping GPU detection in lightweight subcommands.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
ramalama/cli.py (2)

358-358: ⚡ Quick win

Add type hints for function parameters.

As per coding guidelines, type hints should be used for mypy compatibility.

Suggested fix
-def configure_subcommands(parser, lightweight=False):
+def configure_subcommands(parser: argparse.ArgumentParser, lightweight: bool = False) -> None:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ramalama/cli.py` at line 358, Add type hints to the configure_subcommands
function parameters for mypy compatibility. The parser parameter should be
annotated with the appropriate argument parser type, and the lightweight
parameter should be annotated as bool to indicate it accepts a boolean value
with a default of False.

Source: Coding guidelines


191-191: ⚡ Quick win

Add type hint for the lightweight parameter.

As per coding guidelines, type hints should be used in Python code for mypy compatibility.

Suggested fix
-def get_parser(lightweight=False):
+def get_parser(lightweight: bool = False) -> argparse.ArgumentParser:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ramalama/cli.py` at line 191, The get_parser function is missing a type hint
for the lightweight parameter. Add a bool type hint to the lightweight parameter
in the function signature to ensure mypy compatibility and follow coding
guidelines. The parameter should be annotated as lightweight: bool since it has
a boolean default value of False.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ramalama/cli.py`:
- Around line 340-355: The LIGHTWEIGHT_SUBCOMMANDS set is missing the "help"
subcommand even though a help_parser is defined and the help subcommand does not
require runtime plugin registration or GPU detection. Add "help" as a string
element to the LIGHTWEIGHT_SUBCOMMANDS set definition to prevent unnecessary
full parser setup when the help command is invoked.

---

Nitpick comments:
In `@ramalama/cli.py`:
- Line 358: Add type hints to the configure_subcommands function parameters for
mypy compatibility. The parser parameter should be annotated with the
appropriate argument parser type, and the lightweight parameter should be
annotated as bool to indicate it accepts a boolean value with a default of
False.
- Line 191: The get_parser function is missing a type hint for the lightweight
parameter. Add a bool type hint to the lightweight parameter in the function
signature to ensure mypy compatibility and follow coding guidelines. The
parameter should be annotated as lightweight: bool since it has a boolean
default value of False.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ded62ebd-daef-4060-8fda-1268cd69102e

📥 Commits

Reviewing files that changed from the base of the PR and between 42d123c and d3fd39f.

📒 Files selected for processing (1)
  • ramalama/cli.py

Comment thread ramalama/cli.py
Comment thread ramalama/cli.py
def configure_subcommands(parser):
# Subcommands that don't need runtime plugin registration or GPU detection.
# Only run/serve/bench (via runtime plugin), sandbox, and daemon need it.
LIGHTWEIGHT_SUBCOMMANDS = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

would it be easier to list the heavyweight subcommands?

@olliewalsh olliewalsh Jun 17, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@bmahabirbu did you measure how expensive is the GPU detection is? Doesn't seem to be significant. Maybe just on windows where process creation is painfully slow?

@github-actions github-actions Bot removed the stale-pr label Jul 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants