Skip to content
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

Avoid reordering add-on repositories on Backup load #5595

Merged
merged 8 commits into from
Jan 31, 2025

Conversation

agners
Copy link
Member

@agners agners commented Jan 31, 2025

Proposed change

The ensure_builtin_repositories function uses a set to deduplicate items, which sometimes led to a change of order in elements. This is problematic when deduplicating Backups.

Simply avoid mangling the list of add-on repositories on load. Instead rely on update_repositories which uses the same function to ensure built-in repositories when loading the store configuration and restoring a backup file.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (which adds functionality to the supervisor)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:
  • Link to cli pull request:
  • Link to client library pull request:

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • The code has been formatted using Ruff (ruff format supervisor tests)
  • Tests have been added to verify that the new code works.

If API endpoints or add-on configuration are added/changed:

Summary by CodeRabbit

  • Documentation

    • Updated documentation for repositories property in Backup class to clarify its purpose.
    • Improved clarity of repository-related method descriptions.
  • New Features

    • Added a new function to ensure built-in repositories are included in addon repositories list.
  • Logging

    • Modified logging level in backup equality check method from debug to info.
  • Tests

    • Introduced a new asynchronous test for consolidating backups with varied encryption settings.
    • Updated validation tests to allow for flexible input repository list validation.
    • Removed the test for default configuration of repositories.

The `ensure_builtin_repositories` function uses a set to deduplicate
items, which sometimes led to a change of order in elements. This is
problematic when deduplicating Backups.

Simply avoid mangling the list of add-on repositories on load. Instead
rely on `update_repositories` which uses the same function to ensure
built-in repositories when loading the store configuration and restoring
a backup file.
@agners agners added the bugfix A bug fix label Jan 31, 2025
Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

Warning

Rate limit exceeded

@agners has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 12 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 370e3e1 and da79709.

📒 Files selected for processing (1)
  • tests/store/test_validate.py (2 hunks)
📝 Walkthrough

Walkthrough

The pull request introduces modifications to four files across the supervisor and tests modules. In backup.py, the documentation for the repositories property and its setter in the Backup class has been updated to clarify their purpose related to add-on store repositories. A new function, ensure_builtin_repositories, has been added in validate.py to manage add-on repositories, replacing a previous implementation and adjusting the validation process. Additionally, new tests have been added, and existing tests have been modified to reflect these changes.

Changes

File Change Summary
supervisor/backups/backup.py - Updated docstrings for repositories property and setter to clarify their purpose
- Changed logging level in __eq__ method from debug to info
supervisor/store/validate.py - Added new ensure_builtin_repositories function
- Removed previous implementation of the function
- Modified repositories validation to exclude ensure_builtin_repositories
tests/backups/test_backup.py - Added new asynchronous test test_consolidate for backup consolidation with varied encryption settings
tests/store/test_validate.py - Removed test_default_config function
- Modified assertions in test_repository_validate to allow flexible validation based on input

Sequence Diagram

sequenceDiagram
    participant Caller
    participant ensure_builtin_repositories
    participant BUILTIN_REPOSITORIES

    Caller->>ensure_builtin_repositories: Call with addon repositories
    ensure_builtin_repositories->>BUILTIN_REPOSITORIES: Combine repositories
    ensure_builtin_repositories-->>Caller: Return unique repository list
Loading

The sequence diagram illustrates the new ensure_builtin_repositories function, showing how it combines the input addon repositories with built-in repositories and returns a unique list of repositories.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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: 2

🔭 Outside diff range comments (1)
tests/store/test_validate.py (1)

Line range hint 9-15: Add test cases for order preservation and empty list.

The current test cases don't verify that repository order is maintained. Additionally, the empty list case was removed.

Add these test cases to the parametrize decorator:

 @pytest.mark.parametrize(
     "repo_list,valid",
     [
         (["core", "local"], True),
         (["https://github.com/hassio-addons/repository"], True),
         (["not_a_url"], False),
         (["https://fail.com/duplicate", "https://fail.com/duplicate"], False),
+        ([], True),  # Empty list should be valid
+        (["core", "local", "https://github.com/hassio-addons/repository"], True),  # Test order preservation
     ],
 )
🧹 Nitpick comments (2)
tests/store/test_validate.py (1)

Line range hint 17-17: Rename test function for clarity.

The current test name test_repository_validate could be more descriptive about what aspects of validation it's testing.

Consider renaming to better reflect the test's purpose:

-async def test_repository_validate(repo_list: list[str], valid: bool):
+async def test_repository_validation_preserves_order_and_content(repo_list: list[str], valid: bool):
tests/backups/test_backup.py (1)

50-57: Enhance test name and documentation.

Consider making the test name and docstring more descriptive to better reflect the test's purpose:

-async def test_consolidate(
+async def test_consolidate_backups_in_different_locations(
     coresys: CoreSys,
     tmp_path: Path,
     tmp_supervisor_data: Path,
     caplog: pytest.LogCaptureFixture,
 ):
-    """Test consolidate with two backups in different location and varied encryption."""
+    """Test consolidation of backups in different locations with varied encryption settings.
+
+    Verifies that:
+    1. Backups in different locations don't trigger conflict messages
+    2. The consolidated backup correctly tracks paths and protection status
+    3. Encrypted and unencrypted backups can coexist in different locations
+    """
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd7dd59 and 74d5232.

📒 Files selected for processing (2)
  • tests/backups/test_backup.py (1 hunks)
  • tests/store/test_validate.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
tests/backups/test_backup.py

68-68: f-string without any placeholders

Remove extraneous f prefix

(F541)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Build i386 supervisor
  • GitHub Check: Build amd64 supervisor
  • GitHub Check: Build armv7 supervisor
  • GitHub Check: Build armhf supervisor
  • GitHub Check: Build aarch64 supervisor
  • GitHub Check: Run tests Python 3.13.1

tests/store/test_validate.py Outdated Show resolved Hide resolved
tests/backups/test_backup.py Outdated Show resolved Hide resolved
Copy link
Contributor

@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: 0

♻️ Duplicate comments (1)
tests/store/test_validate.py (1)

22-23: ⚠️ Potential issue

Replace set comparison with direct list comparison.

The current assertions using set() explicitly discard order information, which contradicts the PR's objective of avoiding repository reordering.

Apply this diff to fix the assertions:

-        assert len(processed) == len(repo_list)
-        assert set(repositories(repo_list)) == set(repo_list)
+        assert repositories(repo_list) == repo_list
🧹 Nitpick comments (2)
tests/store/test_validate.py (1)

Line range hint 8-15: Add test cases to verify repository order preservation.

Given that the PR aims to avoid reordering repositories, consider adding test cases that specifically verify order preservation:

  1. Mixed repository types (local and remote)
  2. Multiple valid URLs in different orders

Add these test cases to the parametrize decorator:

 @pytest.mark.parametrize(
     "repo_list,valid",
     [
         (["core", "local"], True),
         (["https://github.com/hassio-addons/repository"], True),
+        (["core", "https://github.com/hassio-addons/repository", "local"], True),
+        (["https://github.com/repo1", "https://github.com/repo2"], True),
         (["not_a_url"], False),
         (["https://fail.com/duplicate", "https://fail.com/duplicate"], False),
     ],
 )
tests/backups/test_backup.py (1)

50-56: Enhance test name and docstring for clarity.

The test name and docstring could be more descriptive to better indicate the specific scenario being tested.

Apply this diff to improve clarity:

-async def test_consolidate(
+async def test_consolidate_across_locations(
     coresys: CoreSys,
     tmp_path: Path,
     tmp_supervisor_data: Path,
     caplog: pytest.LogCaptureFixture,
 ):
-    """Test consolidate with two backups in different location and varied encryption."""
+    """Test backup consolidation across different mount locations with varied encryption.
+
+    Verifies that:
+    1. Backups in different locations are properly consolidated
+    2. Encryption status is preserved for each backup
+    3. No conflict messages are generated for valid consolidation
+    """
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 74d5232 and 370e3e1.

📒 Files selected for processing (2)
  • tests/backups/test_backup.py (1 hunks)
  • tests/store/test_validate.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build armv7 supervisor
  • GitHub Check: Build armhf supervisor
  • GitHub Check: Build aarch64 supervisor
  • GitHub Check: Run tests Python 3.13.1
🔇 Additional comments (2)
tests/backups/test_backup.py (2)

67-70: Fix f-string and enhance assertions.

  1. The string doesn't use any interpolation.
  2. Consider adding more assertions to verify the backup consolidation behavior.

71-74: 🛠️ Refactor suggestion

Add assertions to verify backup integrity.

The test should verify that both backup files still exist and maintain their encryption status after consolidation.

Add these assertions after line 74:

     assert enc_backup.all_locations == {
         None: {"path": enc_tar, "protected": True},
         "backup_test": {"path": unc_tar, "protected": False},
     }
+    # Verify backup files exist and maintain their status
+    assert enc_tar.exists(), "Encrypted backup file should still exist"
+    assert unc_tar.exists(), "Unencrypted backup file should still exist"
+    assert enc_backup.protected, "Encrypted backup should maintain protected status"
+    assert not unc_backup.protected, "Unencrypted backup should maintain unprotected status"

Likely invalid or redundant comment.

agners and others added 2 commits January 31, 2025 16:40
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@mdegat01 mdegat01 merged commit 9491b1f into main Jan 31, 2025
20 checks passed
@mdegat01 mdegat01 deleted the avoid-repository-reordering-on-load branch January 31, 2025 17:10
@github-actions github-actions bot locked and limited conversation to collaborators Feb 2, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants