Skip to content

Conversation

@mdegat01
Copy link
Contributor

@mdegat01 mdegat01 commented Jan 13, 2025

Proposed change

Add create date time field to jobs in API and sort them based on that. Probably not needed anymore for cloud backup but seemed to make the job list API more useful so thought I'd add it anyway.

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

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

Release Notes

  • New Features

    • Added creation timestamp for jobs.
    • Enhanced job sorting mechanism to display most recent jobs first.
  • Improvements

    • Updated job listing API to provide chronologically sorted job information.
    • Improved job metadata representation with creation time details.
    • Enhanced backup message structure to include creation timestamps.
  • Tests

    • Added new test to validate job sorting functionality.
    • Enhanced tests to include creation timestamps in job notifications.

These changes improve the job management system by providing more precise and time-aware job tracking and presentation.

@mdegat01 mdegat01 added the new-feature A new feature label Jan 13, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 13, 2025

📝 Walkthrough

Walkthrough

The changes enhance job management and sorting within the supervisor's job system. A created timestamp is introduced to the SupervisorJob class, the job listing method is updated to sort jobs chronologically, and a corresponding test is added to verify this sorting behavior. The modifications ensure jobs are presented in a consistent, time-based order, with newer jobs appearing first in the API response.

Changes

File Changes
supervisor/jobs/__init__.py - Added created field to SupervisorJob class
- Updated @define decorator with order=True
- Modified as_dict() method to include creation timestamp
supervisor/api/jobs.py - Updated _list_jobs() method docstring
- Modified job processing logic to ensure jobs are sorted before iteration
- Added sorting of root jobs in reverse order when added to the queue
tests/api/test_jobs.py - Added test_jobs_sorted() test method
- Updated job assertions to include created field
tests/jobs/test_job_decorator.py - Updated execute_default() method to include created field in notifications
tests/jobs/test_job_manager.py - Added created field to assertions in test_notify_on_change
tests/backups/test_manager.py - Updated backup message structure to include created field
- Modified tests to assert against the new message format

Sequence Diagram

sequenceDiagram
    participant Job as SupervisorJob
    participant JobManager as SystemJobs
    participant API as APIJobs

    Job->>Job: Create with timestamp
    Job->>JobManager: Add job to job list
    JobManager->>JobManager: Sort jobs by creation time
    JobManager->>API: Provide sorted job list
    API->>API: Process jobs in chronological order
    API-->>Client: Return jobs (newest first)
Loading

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7a6b91d and a79951f.

📒 Files selected for processing (3)
  • supervisor/api/jobs.py (2 hunks)
  • tests/api/test_jobs.py (5 hunks)
  • tests/backups/test_manager.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • supervisor/api/jobs.py
⏰ 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.12.8
🔇 Additional comments (3)
tests/backups/test_manager.py (1)

1069-1069: LGTM! Addition of created field to backup message.

The addition of the "created": ANY field to the backup message structure aligns with the job system changes for tracking creation timestamps.

tests/api/test_jobs.py (2)

Line range hint 105-156: LGTM! Addition of created field to job assertions.

The addition of the "created": ANY field to job assertions is consistent with the changes to include creation timestamps in the job system.


Line range hint 189-199: LGTM! Addition of created field to manual cleanup test assertions.

The addition of the "created": ANY field to manual cleanup test assertions maintains consistency with the job system changes.

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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

🧹 Nitpick comments (1)
tests/api/test_jobs.py (1)

239-319: Strengthen the job sorting test.

While the test verifies the structure of sorted jobs, it could be more robust by:

  1. Adding explicit delays between job creation to ensure distinct timestamps
  2. Verifying that the created timestamps are actually in descending order
 async def test_jobs_sorted(api_client: TestClient, coresys: CoreSys):
     """Test jobs are sorted by datetime in results."""
     test = TestClass(coresys)
     await test.test_jobs_sorted_1()
+    await asyncio.sleep(0.1)  # Ensure distinct timestamps
     await test.test_jobs_sorted_2()
 
     resp = await api_client.get("/jobs/info")
     result = await resp.json()
+    
+    # Verify descending order of creation timestamps
+    jobs = result["data"]["jobs"]
+    timestamps = [job["created"] for job in jobs]
+    assert timestamps == sorted(timestamps, reverse=True), "Jobs not in descending order"
+    
     assert result["data"]["jobs"] == [
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b07236b and 6e21f0c.

📒 Files selected for processing (3)
  • supervisor/api/jobs.py (2 hunks)
  • supervisor/jobs/__init__.py (3 hunks)
  • tests/api/test_jobs.py (6 hunks)
🔇 Additional comments (5)
supervisor/api/jobs.py (2)

34-40: LGTM! Clear documentation of job ordering logic.

The docstring clearly explains the rationale behind job ordering, both for child jobs (chronological) and the main list (reverse chronological).


65-65: LGTM! Correct implementation of reverse chronological ordering.

Using insert(0, job_dict) effectively places newer jobs at the start of the list, which aligns with the goal of prioritizing recent jobs in the API response.

supervisor/jobs/__init__.py (2)

87-88: LGTM! Well-implemented creation timestamp field.

The created field is correctly implemented with:

  • Immutable value (frozen)
  • Automatic initialization (factory=utcnow)
  • Proper placement before UUID field

124-124: LGTM! Proper ISO format for timestamp serialization.

The created timestamp is correctly serialized using ISO 8601 format, which is the standard for date/time representation in APIs.

tests/api/test_jobs.py (1)

Line range hint 105-189: LGTM! Test assertions properly updated for new field.

Existing test assertions correctly updated to expect the created field, using ANY matcher appropriately for timestamp values.

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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e21f0c and 7a6b91d.

📒 Files selected for processing (5)
  • supervisor/api/jobs.py (2 hunks)
  • supervisor/jobs/__init__.py (3 hunks)
  • tests/api/test_jobs.py (6 hunks)
  • tests/jobs/test_job_decorator.py (1 hunks)
  • tests/jobs/test_job_manager.py (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • supervisor/api/jobs.py
  • supervisor/jobs/init.py
🧰 Additional context used
🪛 GitHub Check: Run tests Python 3.12.8
tests/api/test_jobs.py

[failure] 273-273:
test_jobs_sorted

AssertionError: assert [{'child_jobs...rs': [], ...}] == [{'child_jobs...rs': [], ...}]

At index 1 diff: {'name': 'test_jobs_sorted_1', 'reference': None, 'uuid': '570cfe0680bb444ab1247884f4d6f6c8', 'progress': 0, 'stage': None, 'done': True, 'errors': [], 'created': '2025-01-14T22:04:50.304738+00:00', 'child_jobs': [{'name': 'test_jobs_sorted_inner_2', 'reference': None, 'uuid': '5b05fde09cba4b73abcdf69e32107cd8', 'progress': 0, 'stage': None, 'done': True, 'errors': [], 'created': '2025-01-14T22:04:50.305044+00:00', 'child_jobs': []}, {'name': 'test_jobs_sorted_inner_1', 'reference': None, 'uuid': 'b0e946d7a2474f75b1a5181a90fd4add', 'progress': 0, 'stage': None, 'done': True, 'errors': [], 'created': '2025-01-14T22:04:50.304903+00:00', 'child_jobs': []}]} != {'created': , 'name': 'test_jobs_sorted_1', 'reference': None, 'uuid': , 'progress': 0, 'stage': None, 'done': True, 'errors': [], 'child_jobs': [{'created': , 'name': 'test_jobs_sorted_inner_1', 'reference': None, 'uuid': , 'progress': 0, 'stage': None, 'done': True, 'errors': [], 'child_jobs': []}, {'created': , 'name': 'test_jobs_sorted_inner_2', 'reference': None, 'uuid': , 'progress': 0, 'stage': None, 'done': True, 'errors': [], 'child_jobs': []}]}

Full diff:
[
{
'child_jobs': [],

  •     'created': <ANY>,
    
  •     'created': '2025-01-14T22:04:50.305231+00:00',
        'done': True,
        'errors': [],
        'name': 'test_jobs_sorted_2',
        'progress': 0,
        'reference': None,
        'stage': None,
    
  •     'uuid': <ANY>,
    
  •     'uuid': '0c7ea0d934d443609fa2e447df8ec7ac',
    },
    {
        'child_jobs': [
            {
                'child_jobs': [],
    
  •             'created': <ANY>,
    
  •             'created': '2025-01-14T22:04:50.305044+00:00',
    
  •             'done': True,
    
  •             'errors': [],
    
  •             'name': 'test_jobs_sorted_inner_2',
    
  •             'progress': 0,
    
  •             'reference': None,
    
  •             'stage': None,
    
  •             'uuid': '5b05fde09cba4b73abcdf69e32107cd8',
    
  •         },
    
  •         {
    
  •             'child_jobs': [],
    
  •             'created': '2025-01-14T22:04:50.304903+00:00',
                'done': True,
                'errors': [],
                'name': 'test_jobs_sorted_inner_1',
                'progress': 0,
                'reference': None,
                'stage': None,
    
  •             'uuid': 'b0e946d7a2474f75b1a5181a90fd4add',
    
  •             'uuid': <ANY>,
    
  •         },
    
  •         {
    
  •             'child_jobs': [],
    
  •             'created': <ANY>,
    
  •             'done': True,
    
  •             'errors': [],
    
  •             'name': 'test_jobs_sorted_inner_2',
    
  •             'progress': 0,
    
  •             'reference': None,
    
  •             'stage': None,
    
  •             'uuid': <ANY>,
            },
        ],
    
  •     'created': <ANY>,
    
  •     'created': '2025-01-14T22:04:50.304738+00:00',
        'done': True,
        'errors': [],
        'name': 'test_jobs_sorted_1',
        'progress': 0,
        'reference': None,
        'stage': None,
    
  •     'uuid': <ANY>,
    
  •     'uuid': '570cfe0680bb444ab1247884f4d6f6c8',
    },
    
    ]
🔇 Additional comments (3)
tests/jobs/test_job_manager.py (1)

107-107: LGTM! Test assertions updated for new job field.

The test assertions have been consistently updated to include the new created field in job data structures.

Also applies to: 129-129, 151-151, 173-173, 200-200, 226-226

tests/api/test_jobs.py (1)

239-241: LGTM! New test added for job sorting functionality.

The test verifies that jobs are sorted by creation datetime in the API response, which aligns with the PR objective.

tests/jobs/test_job_decorator.py (1)

1000-1000: LGTM! Test assertion updated for new job field.

The test assertion has been updated to include the new created field in job data structure.

@agners agners merged commit 600bf91 into main Jan 16, 2025
20 checks passed
@agners agners deleted the sorted-jobs branch January 16, 2025 08:51
@github-actions github-actions bot locked and limited conversation to collaborators Jan 18, 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.

3 participants