Skip to content

ci: auto-detect Python version from HA Core for test matrix#1

Merged
florianhorner merged 2 commits into
mainfrom
florianhorner/rocky-balboa
Apr 12, 2026
Merged

ci: auto-detect Python version from HA Core for test matrix#1
florianhorner merged 2 commits into
mainfrom
florianhorner/rocky-balboa

Conversation

@florianhorner
Copy link
Copy Markdown
Owner

@florianhorner florianhorner commented Apr 12, 2026

Summary

Test plan

  • Run python scripts/update-test-matrix.py and verify it fetches versions correctly
  • CI matrix should resolve correct Python versions for each HA Core release

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores
    • Updated CI test matrix configuration with more precise Python patch versions to better align with supported core versions.
    • Added test coverage for newly supported core versions: 2025.12.5, 2026.1.3, and 2026.2.2, all using Python 3.13.2.
    • Enhanced test infrastructure to dynamically fetch Python version requirements from Home Assistant Core repositories with built-in error handling.

ademuri added 2 commits April 12, 2026 21:02
This changes the update-test-matrix.py script to fetch the required
Python version for a given HA Core version by fetching the
`pyproject.toml` for that version. It also update the test matrix with
the updated script.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 12, 2026

📝 Walkthrough

Walkthrough

The GitHub Actions test workflow and its update script were enhanced to use more precise Python patch versions across Home Assistant core versions. The workflow matrix now specifies exact versions (e.g., 3.12.0, 3.13.2), and the update script was improved to fetch Python version requirements from the HA Core repository with network error handling and caching.

Changes

Cohort / File(s) Summary
CI Test Matrix Configuration
.github/workflows/pytest.yaml
Updated Python version specifications per core version: 3.123.12.0 for older cores, 3.133.13.0 or 3.13.2 depending on core version, added entries for 2025.12.5, 2026.1.3, 2026.2.2 with 3.13.2, and updated dev core to use 3.14.2.
Test Matrix Update Script
scripts/update-test-matrix.py
Added functools.cache decorator to get_python_version(), implemented network-based Python version detection via pyproject.toml fetching from HA Core repository, added urllib.error.URLError handling with fallback to hardcoded version mappings, updated fallback logic for 2025.* and 2026 versions, and made dev matrix entry use dynamic version computation.

Sequence Diagram

sequenceDiagram
    actor User
    participant Script as update-test-matrix.py
    participant Network as HA Core Repository
    participant Fallback as Version Mapping Logic
    
    User->>Script: Run script
    Script->>Script: Call get_python_version(ha_version)
    Script->>Script: Check cache (functools.cache)
    alt Cache hit
        Script-->>Script: Return cached version
    else Cache miss
        Script->>Network: Fetch pyproject.toml
        alt Success
            Network-->>Script: Return pyproject.toml
            Script->>Script: Parse requires-python field
            Script-->>Script: Extract min Python version
        else URLError (network failure)
            Network-->>Script: Connection error
            Script->>Fallback: Use hardcoded fallback logic
            Fallback-->>Script: Return mapped version
        end
    end
    Script->>Script: Cache result
    Script-->>User: Generate pytest matrix with Python version
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 With Python versions now precise and clear,
Our CI matrix springs to cheer!
Fetching versions from the repo's heart,
With caches built and logic smart—
From 3.12 to 3.14, we leap with glee,
Testing futures far as we can see! 🚀

🚥 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 clearly and accurately summarizes the main change: auto-detecting Python versions from HA Core for the test matrix instead of hardcoding them.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch florianhorner/rocky-balboa

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

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@scripts/update-test-matrix.py`:
- Around line 86-116: The function get_python_version silently returns "3.13"
for unknown/future ha_version values; change it to fail loudly instead: after
the fetch and fallback logic (inside get_python_version) remove the hardcoded
return "3.13" and raise a clear exception (e.g., RuntimeError or ValueError)
that includes the ha_version so CI will fail and prompt updating the mapping;
ensure the exception message mentions get_python_version and the problematic
ha_version so callers can surface the failure.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 09fb8381-542e-4d6e-9ecb-076acebc43bf

📥 Commits

Reviewing files that changed from the base of the PR and between 4b53088 and d7b749d.

📒 Files selected for processing (2)
  • .github/workflows/pytest.yaml
  • scripts/update-test-matrix.py

Comment on lines +86 to 116
@functools.cache
def get_python_version(ha_version: str) -> str:
"""Determine Python version based on HA Core version."""
"""Determine Python version based on HA Core version by fetching from GitHub."""
url = f"https://raw.githubusercontent.com/home-assistant/core/{ha_version}/pyproject.toml"
try:
with urllib.request.urlopen(url, timeout=10) as response: # noqa: S310
content = response.read().decode()
# Look for requires-python = ">=3.14.2"
match = re.search(r'requires-python\s*=\s*">=(\d+\.\d+(?:\.\d+)?)', content)
if match:
return match.group(1)
except urllib.error.URLError as e:
print(f"Warning: Could not fetch python version for {ha_version}: {e}")

# Fallback to hardcoded logic if fetch fails
parts = ha_version.split(".")
year, month = int(parts[0]), int(parts[1])
# 2024.x and 2025.1 use Python 3.12, 2025.2+ use Python 3.13
if year == 2024 or (year == 2025 and month == 1):
return "3.12"
if len(parts) >= 2:
try:
year, month = int(parts[0]), int(parts[1])
# 2024.x and 2025.1 use Python 3.12, 2025.2 to 2026.2 use Python 3.13
if year == 2024 or (year == 2025 and month == 1):
return "3.12"
if year == 2025 or (year == 2026 and month <= 2):
return "3.13"
except ValueError:
pass

if ha_version == "dev":
return "3.14"

return "3.13"
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid silent fallback to 3.13 for unknown/future versions.

If network fetch fails, Line 116 currently defaults to "3.13" for unmatched versions (e.g., newer HA releases), which can silently produce an incorrect CI matrix.

Proposed fix
@@
 def get_python_version(ha_version: str) -> str:
@@
-    try:
+    fetch_failed = False
+    try:
         with urllib.request.urlopen(url, timeout=10) as response:  # noqa: S310
             content = response.read().decode()
@@
     except urllib.error.URLError as e:
         print(f"Warning: Could not fetch python version for {ha_version}: {e}")
+        fetch_failed = True
@@
-    if ha_version == "dev":
+    if ha_version == "dev":
         return "3.14"
 
-    return "3.13"
+    if fetch_failed:
+        raise RuntimeError(
+            f"Unable to determine Python version for HA Core {ha_version}: "
+            "remote fetch failed and no fallback mapping matched."
+        )
+    return "3.13"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/update-test-matrix.py` around lines 86 - 116, The function
get_python_version silently returns "3.13" for unknown/future ha_version values;
change it to fail loudly instead: after the fetch and fallback logic (inside
get_python_version) remove the hardcoded return "3.13" and raise a clear
exception (e.g., RuntimeError or ValueError) that includes the ha_version so CI
will fail and prompt updating the mapping; ensure the exception message mentions
get_python_version and the problematic ha_version so callers can surface the
failure.

@florianhorner florianhorner merged commit 0efec34 into main Apr 12, 2026
6 of 26 checks passed
@florianhorner florianhorner deleted the florianhorner/rocky-balboa branch April 12, 2026 19:13
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