-
Notifications
You must be signed in to change notification settings - Fork 285
chore typing and some bug fixes #2241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Signed-off-by: Ian Eaves <[email protected]>
Reviewer's GuideAdds stricter typing across CLI, engine, RAG, and common utilities, introduces structured arg types for serve/run and RAG commands, tightens error handling and invariants, and fixes small behavioral issues (port computation, config finalization, tests isolation, and argument validation). File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Summary of ChangesHello @ieaves, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly improves the codebase by integrating comprehensive type annotations throughout key modules, which enhances code readability, maintainability, and allows for more robust static analysis. It also includes critical bug fixes related to argument parsing and port allocation, alongside minor refactorings to streamline existing code and improve test isolation for future development. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey there - I've reviewed your changes - here's some feedback:
- In
engine.info, the returned JSON is now cast todict[str, Any]even thoughjson.loadscan return a list (and the function’s return type hint still includeslist[Any]); consider preserving the actual type (Anyordict | list) or narrowing the annotation instead of forcing a dict cast. - The SafetensorModelNotSupported error message construction in
cli.mainlost the line breaks between commands when you switched to a single parenthesized string; consider adding explicit\nor using a multiline string to keep the output readable. - Several new
# type: ignore[possibly-unbound]comments aroundparserandargs.modelincli.mainsuggest real control-flow uncertainty; it may be cleaner to initialize these variables before thetryor restructure the control flow so they are always defined instead of suppressing the type checker.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In `engine.info`, the returned JSON is now cast to `dict[str, Any]` even though `json.loads` can return a list (and the function’s return type hint still includes `list[Any]`); consider preserving the actual type (`Any` or `dict | list`) or narrowing the annotation instead of forcing a dict cast.
- The SafetensorModelNotSupported error message construction in `cli.main` lost the line breaks between commands when you switched to a single parenthesized string; consider adding explicit `\n` or using a multiline string to keep the output readable.
- Several new `# type: ignore[possibly-unbound]` comments around `parser` and `args.model` in `cli.main` suggest real control-flow uncertainty; it may be cleaner to initialize these variables before the `try` or restructure the control flow so they are always defined instead of suppressing the type checker.
## Individual Comments
### Comment 1
<location> `ramalama/cli.py:317` </location>
<code_context>
"""Perform additional setup after parsing arguments."""
- def map_https_to_transport(input: str) -> str | None:
+ def map_https_to_transport(input: str) -> str:
if input.startswith("https://") or input.startswith("http://"):
url = urlparse(input)
</code_context>
<issue_to_address>
**issue (bug_risk):** The return type annotation for `map_https_to_transport` is too narrow and does not match the implementation.
Because the function can reach the end without a `return` when `input` is not an HTTP(S) URL, it currently returns `None` despite the `-> str` annotation. This mismatch will be flagged by type checkers and can mislead callers into assuming a non-`None` result. Please either restore the `str | None` return type or add an explicit return for the non-URL case that matches the intended behavior.
</issue_to_address>
### Comment 2
<location> `ramalama/cli.py:1566-1572` </location>
<code_context>
-$ ramalama run <oci-name>
-""",
- errno.ENOTSUP,
+ message = (
+ "Safetensor models are not supported. Please convert it to GGUF via:"
+ f"$ ramalama convert --gguf=<quantization> {args.model} <oci-name>" # type: ignore[possibly-unbound]
+ "$ ramalama run <oci-name>"
)
+ eprint(message, errno.ENOTSUP)
</code_context>
<issue_to_address>
**suggestion (bug_risk):** The Safetensor error message loses line breaks/spaces compared to the previous version.
The concatenated string will render as `...via:$ ramalama convert...$ ramalama run...` with no spaces or newlines, reducing readability compared to the previous triple-quoted version. Please add `"\n"` (or at least a space) between segments to preserve the intended formatting.
```suggestion
except SafetensorModelNotSupported:
message = (
"Safetensor models are not supported. Please convert it to GGUF via:\n"
f"$ ramalama convert --gguf=<quantization> {args.model} <oci-name>\n" # type: ignore[possibly-unbound]
"$ ramalama run <oci-name>\n"
)
eprint(message, errno.ENOTSUP)
```
</issue_to_address>
### Comment 3
<location> `ramalama/engine.py:333` </location>
<code_context>
if output == "":
return []
- return json.loads(output)
+ return cast(dict[str, Any], json.loads(output))
except FileNotFoundError as e:
return str(e)
</code_context>
<issue_to_address>
**issue (bug_risk):** Casting `json.loads(output)` to `dict[str, Any]` is misleading given `info`'s actual return shape.
The function’s signature still allows `list[Any] | str | dict[str, Any]`, and `json.loads(output)` can return a list. Casting to `dict[str, Any]` misleads type checkers and callers into assuming a dict and can hide real type issues. Either keep the union return type without a cast, or enforce and validate that the result is always a dict before returning it.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
ramalama/engine.py
Outdated
| if output == "": | ||
| return [] | ||
| return json.loads(output) | ||
| return cast(dict[str, Any], json.loads(output)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue (bug_risk): Casting json.loads(output) to dict[str, Any] is misleading given info's actual return shape.
The function’s signature still allows list[Any] | str | dict[str, Any], and json.loads(output) can return a list. Casting to dict[str, Any] misleads type checkers and callers into assuming a dict and can hide real type issues. Either keep the union return type without a cast, or enforce and validate that the result is always a dict before returning it.
There was a problem hiding this comment.
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 significant improvements to type safety and robustness across the codebase. The addition of typed argument protocols, refined type annotations, and bug fixes in areas like argument parsing and port computation are excellent. The test isolation for config-related tests is also a great enhancement. I've found a couple of minor areas for improvement, mainly related to code consistency and cleanup, which I've detailed in the comments.
| eprint(message, errno.ENOTSUP) | ||
| except NoGGUFModelFileFound: | ||
| eprint(f"No GGUF model file found for downloaded model '{args.model}'", errno.ENOENT) | ||
| eprint(f"No GGUF model file found for downloaded model '{args.model}'", errno.ENOENT) # type: ignore |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For consistency with the type: ignore on line 1569 and for better clarity, it's good practice to specify the error code being ignored. In this case, args could be unbound if init_cli() fails.
| eprint(f"No GGUF model file found for downloaded model '{args.model}'", errno.ENOENT) # type: ignore | |
| eprint(f"No GGUF model file found for downloaded model '{args.model}'", errno.ENOENT) # type: ignore[possibly-unbound] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The line exceeds 120 characters with the error specified
| @pytest.fixture(autouse=True) | ||
| def isolate_config(): | ||
| """ | ||
| Isolate tests from user configuration files by mocking config loading. | ||
| This fixture is automatically used for all tests in this module. | ||
| Individual tests can override by explicitly patching if needed. | ||
| """ | ||
| with patch("ramalama.config.load_file_config", return_value={}): | ||
| with patch("ramalama.config.apple_vm", return_value=False): | ||
| yield |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This autouse fixture is a great addition for isolating tests from the user's environment. It simplifies the test setup significantly. As a follow-up, you could remove the now-redundant with patch(\"ramalama.config.load_file_config\", ...) context manager from test_correct_config_defaults to clean up the code.
Signed-off-by: Ian Eaves <[email protected]>
Summary by Sourcery
Improve type safety and robustness across CLI, engine, RAG, and common utilities while tightening port selection logic and test isolation.
Bug Fixes:
Enhancements:
Tests: