Skip to content

Conversation

@olliewalsh
Copy link
Collaborator

@olliewalsh olliewalsh commented Dec 11, 2025

We currently depend on some python 3.11+ features. Add unit/e2e test coverage for Python 3.10 and workaround the issues.

Summary by Sourcery

Add Python 3.10 compatibility and extend CI coverage to run unit and end-to-end tests across both default and Python 3.10 environments.

New Features:

  • Introduce a compat module providing a StrEnum fallback implementation for Python 3.10.

Bug Fixes:

  • Fix temporary file handling in engine containerfile builds to avoid Python 3.10 incompatibilities and ensure proper cleanup.
  • Adjust unit tests that rely on NamedTemporaryFile semantics for compatibility with Python 3.10.
  • Stabilize e2e serve tests by adding a context manager to safely change and restore the working directory.

Enhancements:

  • Declare support for Python 3.14 in the project metadata classifiers.

CI:

  • Refactor CI workflows to run unit and e2e tests in a matrix including Python 3.10 variants across Linux, macOS, and Windows.
  • Simplify CI setup by relying on uv configuration for Python selection and environment activation instead of manual system package and Python management.

Some python 3.12+ code has been merged, breaking compatibility with 3.10.

Signed-off-by: Oliver Walsh <[email protected]>
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Dec 11, 2025

Reviewer's Guide

Adds Python 3.10 compatibility by introducing a StrEnum fallback, ensuring temp file handling works on 3.10, and extending CI to run unit and e2e test matrices across both default and Python 3.10 environments on all platforms.

File-Level Changes

Change Details Files
Extend CI pipelines to run unit and e2e tests against Python 3.10 across Linux, macOS, and Windows using uv matrices instead of per-job setup.
  • Introduce a matrix.strategy.variant for unit-test, e2e-tests, e2e-tests-nocontainer, e2e-tests-docker, e2e-tests-macos, and e2e-tests-windows jobs to add a Python 3.10 variant
  • Pass variant-specific options to astral-sh/setup-uv via matrix.variant.uv-options, including python-version '3.10' and activate-environment where needed
  • Remove redundant apt/podman setup and manual Python dependency installation in CI in favor of uv-managed environments
  • Switch Windows e2e tests to invoke tox via uv run tox instead of a globally installed tox
.github/workflows/ci.yml
Fix temporary file usage so it is compatible with Python 3.10 and avoids invalid parameters and leaked files.
  • Refactor test_accel_image to create a NamedTemporaryFile with delete=False, manually manage RAMALAMA_CONFIG pointing at the file, and ensure the file is closed and unlinked in a finally block
  • Adjust engine.build_containerfile to create a NamedTemporaryFile with delete=False and wrap write/build in a try/finally that closes and removes the temp file
test/unit/test_common.py
ramalama/engine.py
Add a small compat layer providing StrEnum on Python 3.10 and update metadata for supported Python versions.
  • Introduce ramalama.compat module that tries to import StrEnum and defines a StrEnum subclass of str and Enum as a fallback when unavailable (e.g., Python 3.10)
  • Update pyproject classifiers to include Python 3.14 as a supported version
ramalama/compat.py
pyproject.toml
Introduce a simple directory-changing context manager for e2e tests to work consistently across Python versions.
  • Add a chdir(contextmanager) helper to temporarily change the working directory in e2e tests, restoring the original directory in a finally block
test/e2e/test_serve.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

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @olliewalsh, 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 addresses compatibility issues with Python 3.10 by backporting certain features and adjusting code that relied on Python 3.11+ specific functionalities. The changes ensure that the application and its test suite can run seamlessly on Python 3.10, broadening the supported Python environment. This involves creating a compatibility layer for StrEnum, implementing a custom chdir context manager for testing, and improving temporary file management for greater reliability.

Highlights

  • Python 3.10 Compatibility: Introduced a new ramalama/compat.py module to provide a backported StrEnum implementation for Python versions prior to 3.11, ensuring core functionalities remain accessible.
  • Test Suite Compatibility: Implemented a custom chdir context manager within the test suite (test/e2e/test_serve.py) to replace the Python 3.11+ contextlib.chdir, allowing end-to-end tests to run correctly on Python 3.10.
  • Robust Temporary File Handling: Refactored NamedTemporaryFile usage in ramalama/engine.py and test/unit/test_common.py to use explicit try-finally blocks for closing and unlinking temporary files, enhancing robustness and ensuring proper resource cleanup across different Python versions.
  • Dependency Updates: Updated pyproject.toml to include Python 3.14 in the list of supported programming language classifiers.
Ignored Files
  • Ignored by pattern: .github/workflows/** (1)
    • .github/workflows/ci.yml
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a 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 the new temporary file handling (e.g., test_accel_image and build_containerfile), you're manually managing NamedTemporaryFile and calling close() both in the main path and in finally; consider using a single with NamedTemporaryFile(...) as tfile: plus os.unlink(tfile.name) after the context (or only closing in finally) to avoid double-closing and make the lifetime clearer.
  • The GitHub Actions matrices for adding Python 3.10 are repeated with nearly identical variant/uv-options structures across multiple jobs; consider extracting these into a reusable pattern (e.g., YAML anchors or a composite action) to reduce duplication and keep Python version support easier to maintain.
  • On the Windows E2E job you switched to uv run tox -e e2e -- -v but dropped the explicit tox/dev-dependency installation; double-check that tox is resolvable via uv run from your project metadata or reintroduce a minimal step to ensure tox is available without relying on global state.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the new temporary file handling (e.g., `test_accel_image` and `build_containerfile`), you're manually managing `NamedTemporaryFile` and calling `close()` both in the main path and in `finally`; consider using a single `with NamedTemporaryFile(...) as tfile:` plus `os.unlink(tfile.name)` after the context (or only closing in `finally`) to avoid double-closing and make the lifetime clearer.
- The GitHub Actions matrices for adding Python 3.10 are repeated with nearly identical `variant`/`uv-options` structures across multiple jobs; consider extracting these into a reusable pattern (e.g., YAML anchors or a composite action) to reduce duplication and keep Python version support easier to maintain.
- On the Windows E2E job you switched to `uv run tox -e e2e -- -v` but dropped the explicit tox/dev-dependency installation; double-check that tox is resolvable via `uv run` from your project metadata or reintroduce a minimal step to ensure tox is available without relying on global state.

## Individual Comments

### Comment 1
<location> `ramalama/engine.py:251-258` </location>
<code_context>
         Return the ID of the built image.
         """
-        with NamedTemporaryFile(delete_on_close=False) as tfile:
+        tfile = NamedTemporaryFile(delete=False)
+        try:
             tfile.write(content.encode("utf-8"))
             tfile.close()
             return self.build(tfile.name, context, tag=tag)
+        finally:
+            tfile.close()
+            os.unlink(tfile.name)


</code_context>

<issue_to_address>
**issue (bug_risk):** Handle potential errors when unlinking an already-removed temporary file and avoid double-closing

If `self.build(...)` (or another process) removes the temp file, `os.unlink(tfile.name)` will raise `FileNotFoundError` and can hide the original error. Also, `tfile.close()` is called both in the `try` block and in `finally`, which is redundant. A safer pattern is:

```python
        tfile = NamedTemporaryFile(delete=False)
        try:
            tfile.write(content.encode("utf-8"))
        finally:
            tfile.close()

        try:
            return self.build(tfile.name, context, tag=tag)
        finally:
            with contextlib.suppress(FileNotFoundError):
                os.unlink(tfile.name)
```

This keeps cleanup robust, avoids double-closing, and ensures the temp file is removed even on error without masking exceptions.
</issue_to_address>

### Comment 2
<location> `ramalama/compat.py:9` </location>
<code_context>
+except ImportError:
+    from enum import Enum
+
+    class StrEnum(str, Enum):  # type: ignore[no-redef]
+        """StrEnum class for Python 3.10."""
+
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Backported StrEnum does not fully match stdlib StrEnum semantics (notably str() behavior)

The stdlib `enum.StrEnum` has different `str()` semantics than a plain `Enum`: `str(Member)` returns the value, not `Class.Member`. With this backport, `str(MyStrEnum.FOO)` will still be `'MyStrEnum.FOO'`, which can cause behavioral differences between 3.10 and 3.11+ if code relies on the real `StrEnum`. Consider overriding `__str__` (and possibly `__repr__`) to match:

```python
class StrEnum(str, Enum):
    def __str__(self) -> str:  # type: ignore[override]
        return str(self.value)
```
</issue_to_address>

### Comment 3
<location> `test/unit/test_common.py:158` </location>
<code_context>
+def test_accel_image(accel_env: str, env_override, config_override: str, expected_result, monkeypatch: pytest.MonkeyPatch):
</code_context>

<issue_to_address>
**suggestion (testing):** Add tests for the new Python 3.10 `StrEnum` compatibility layer

The PR adds `ramalama.compat.StrEnum` for Python 3.10, but there are no tests for it. Please add a small test module (e.g. `test_compat.py`) that imports `StrEnum`, defines a sample enum subclass, and verifies that members are instances of both `str` and `Enum`, that equality and `__str__` behave correctly, and that it imports correctly on both 3.10 and 3.11+ so CI actually validates the compat layer.
</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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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 successfully adds compatibility for Python 3.10 by introducing shims for features from newer Python versions, such as StrEnum and contextlib.chdir. The changes to temporary file handling correctly address potential resource leaks. I have a couple of suggestions to refine the new temporary file logic to make it more idiomatic and less redundant, which will improve code clarity and maintainability.

@rhatdan
Copy link
Member

rhatdan commented Dec 11, 2025

LGTM

@rhatdan rhatdan merged commit fd04388 into containers:main Dec 11, 2025
35 of 37 checks passed
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.

2 participants