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

Optimize validation layout updates #8789

Merged
merged 41 commits into from
Dec 19, 2024

Conversation

zhiltsov-max
Copy link
Contributor

@zhiltsov-max zhiltsov-max commented Dec 6, 2024

Motivation and context

Fixes #8686

Includes #8689

  • Optimized task validation layout updates
  • Refactored take_by and chunked_list uses in the server code
  • Fixed response values and reroll logic when both disabled_frames and frame_selection_method are used simultaneously in PATCH /tasks/id/validation_layout
  • Fixed missing context image chunks cleanup on honeypot changes in jobs and tasks
  • Fixed invalid context image chunk cache keys

How has this been tested?

Checklist

  • I submit my changes into the develop branch
  • I have created a changelog fragment
  • I have updated the documentation accordingly
  • I have added tests to cover my changes
  • I have linked related issues (see GitHub docs)
  • I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced honeypot task functionality for improved validation frame selection and randomization.
    • Introduced a new class for managing frame selection, ensuring uniform usage across tasks.
  • Bug Fixes

    • Improved error handling and validation checks in task management and annotation processes.
  • Tests

    • Expanded test coverage for task creation, validation frame management, and annotation import/export, ensuring robust functionality.
  • Documentation

    • Updated internal documentation to reflect new features and changes in task management processes.

@zhiltsov-max zhiltsov-max marked this pull request as draft December 6, 2024 18:41
Copy link
Contributor

coderabbitai bot commented Dec 6, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes in this pull request enhance various functionalities within the CVAT application. Key updates include improvements to honeypot task management, type hint modifications for better type safety in dataset handling, and the introduction of new classes and methods for cache management and validation frame selection. Additionally, the test suite has been expanded with new test cases to ensure robust validation frame handling and annotation management. Overall, the updates aim to standardize processes, improve error handling, and enhance the clarity of code.

Changes

File Path Change Summary
changelog.d/20241205_161129_mzhiltso_update_honeypot_selection.md Enhanced validation frames distribution and random honeypot rerolls in honeypot tasks.
cvat/apps/dataset_manager/bindings.py Updated add_prefetch_info method signature to specify QuerySet[Label] for input and output.
cvat/apps/dataset_manager/task.py Updated add_prefetch_info method signature to specify QuerySet[models.Job] for input and output.
cvat/apps/engine/cache.py Added _bulk_delete_cache_items and remove_segment_chunks methods for improved cache item management.
cvat/apps/engine/quality_control.py Introduced HoneypotFrameSelector class for uniform and random frame selection.
cvat/apps/engine/serializers.py Added _TaskValidationLayoutBulkUpdateContext class and refactored update methods for bulk operations in serializers.
cvat/apps/engine/task.py Integrated HoneypotFrameSelector into _create_thread function for structured validation frame selection.
cvat/apps/engine/views.py Modified validation_layout method to include type casting and validation checks for task layouts.
dev/format_python_code.sh Added cvat/apps/engine/quality_control.py to formatting paths for black and isort.
tests/python/rest_api/test_tasks.py Added multiple new test cases focusing on validation frames and annotation handling, enhancing test coverage.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant TaskViewSet
    participant HoneypotFrameSelector
    participant JobAnnotation

    User->>TaskViewSet: Request to create task
    TaskViewSet->>HoneypotFrameSelector: Initialize frame selector
    HoneypotFrameSelector->>HoneypotFrameSelector: Select frames
    TaskViewSet->>JobAnnotation: Add frames to job
    JobAnnotation-->>TaskViewSet: Return job with frames
    TaskViewSet-->>User: Task created successfully
Loading

🐰 In the garden where frames do play,
A selector hops in a random way.
With honeypots and tasks in a dance,
Validation frames take their chance.
Errors handled, all is bright,
A joyful code, a coder's delight! 🌼


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 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 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.

@zhiltsov-max zhiltsov-max marked this pull request as ready for review December 6, 2024 19:56
@zhiltsov-max zhiltsov-max changed the title Optimize validation layout updates [Dependent] Optimize validation layout updates Dec 6, 2024
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: 3

🧹 Outside diff range and nitpick comments (5)
tests/python/rest_api/test_tasks.py (2)

2268-2276: Prevent Potential ValueError When validation_frame_counts Is Empty

If validation_frame_counts is empty, calling max() and min() on an empty sequence will raise a ValueError. Consider adding a check to ensure that validation_frame_counts is not empty before performing these operations.


4480-4488: Prevent Potential ValueError When validation_frame_counts Is Empty

Similarly, ensure that validation_frame_counts is not empty before calling max() and min() to avoid a ValueError.

changelog.d/20241205_161129_mzhiltso_update_honeypot_selection.md (1)

3-4: Improve Grammar in Change Description

Consider rephrasing the sentence for grammatical correctness:

- Improved the uniformity of validation frame distribution in honeypot tasks and random honeypot rerolls
cvat/apps/dataset_manager/bindings.py (1)

53-53: LGTM! Type hints improve code clarity and type safety.

The addition of type hints QuerySet[Label] for both the input parameter and return type makes the method signature more explicit and helps catch type-related issues early.

Consider adding a docstring to describe the method's purpose and parameters:

def add_prefetch_info(cls, queryset: QuerySet[Label]) -> QuerySet[Label]:
    """
    Add prefetch related fields to the label queryset.
    
    Args:
        queryset: The label queryset to prefetch related fields for
        
    Returns:
        The queryset with prefetched related fields
    """
cvat/apps/engine/views.py (1)

1775-1775: Improved validation and error handling for task validation layout.

The changes enhance robustness by:

  1. Using type casting to ensure type safety
  2. Adding validation check for layout existence
  3. Providing clear error message when validation is not configured

Consider extracting the validation logic into a separate method for better code organization:

def _validate_layout_exists(self, db_task: models.Task) -> models.ValidationLayout:
    validation_layout = getattr(db_task.data, 'validation_layout', None)
    if not validation_layout:
        raise ValidationError(
            "Task has no validation setup configured. "
            "Validation must be initialized during task creation"
        )
    return validation_layout
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between caff6ee and f55595d.

📒 Files selected for processing (10)
  • changelog.d/20241205_161129_mzhiltso_update_honeypot_selection.md (1 hunks)
  • cvat/apps/dataset_manager/bindings.py (1 hunks)
  • cvat/apps/dataset_manager/task.py (1 hunks)
  • cvat/apps/engine/cache.py (3 hunks)
  • cvat/apps/engine/quality_control.py (1 hunks)
  • cvat/apps/engine/serializers.py (10 hunks)
  • cvat/apps/engine/task.py (3 hunks)
  • cvat/apps/engine/views.py (1 hunks)
  • dev/format_python_code.sh (1 hunks)
  • tests/python/rest_api/test_tasks.py (2 hunks)
🧰 Additional context used
🪛 GitHub Check: SonarCloud
cvat/apps/engine/quality_control.py

[notice] 19-19: Results that depend on random number generation should be reproducible

Provide a seed for this random generator.

See more on SonarQube Cloud

🔇 Additional comments (6)
cvat/apps/engine/quality_control.py (1)

18-21: 🛠️ Refactor suggestion

Provide a seed for reproducibility when initializing the random generator

The random number generator is initialized without a seed when rng is not provided. This can lead to non-reproducible results in frame selection. To ensure consistent and reproducible behavior, consider adding an optional seed parameter to the constructor and use it to initialize the random generator.

🧰 Tools
🪛 GitHub Check: SonarCloud

[notice] 19-19: Results that depend on random number generation should be reproducible

Provide a seed for this random generator.

See more on SonarQube Cloud

cvat/apps/engine/serializers.py (2)

1514-1514: Verify if setting db_image.real_frame = -1 is appropriate

Assigning -1 to db_image.real_frame may have unintended consequences if real_frame is expected to be a non-negative integer representing a valid frame index. Verify that this assignment correctly represents the intended logic and that downstream code handles this value appropriately.


1566-1572: Ensure compatibility of bulk_create with update_conflicts parameter

The use of bulk_create with update_conflicts=True and update_fields parameters requires Django 2.2 or higher. Confirm that the project's Django version supports these parameters to prevent runtime errors.

Run the following script to check the Django version:

✅ Verification successful

Django version is compatible with bulk_create parameters

The project uses Django 4.2.16, which fully supports bulk_create with update_conflicts, update_fields, and unique_fields parameters, as these features were introduced in Django 2.2. The code is safe to use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that Django version is 2.2 or higher.

# Expected result: The Django version should be 2.2.0 or higher.

# Command to get the installed Django version
python -c "import django; print(django.get_version())"

Length of output: 153


Script:

#!/bin/bash
# Let's check the requirements files for Django version
rg "django[>=<]" -i --no-filename

Length of output: 92

dev/format_python_code.sh (1)

33-33: LGTM!

The addition of cvat/apps/engine/quality_control.py to the formatting script is appropriate.

cvat/apps/engine/cache.py (1)

68-68: LGTM!

The import of format_list is appropriate for use in logging messages.

cvat/apps/dataset_manager/task.py (1)

87-87: LGTM!

The updated type annotations for the add_prefetch_info method enhance type safety and clarity.

cvat/apps/engine/task.py Outdated Show resolved Hide resolved
cvat/apps/engine/task.py Outdated Show resolved Hide resolved
cvat/apps/engine/cache.py Outdated Show resolved Hide resolved
@codecov-commenter
Copy link

codecov-commenter commented Dec 6, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 44 lines in your changes missing coverage. Please review.

Project coverage is 73.88%. Comparing base (289ad43) to head (68d1771).
Report is 25 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #8789      +/-   ##
===========================================
- Coverage    73.93%   73.88%   -0.06%     
===========================================
  Files          409      408       -1     
  Lines        43930    44086     +156     
  Branches      3986     3986              
===========================================
+ Hits         32478    32571      +93     
- Misses       11452    11515      +63     
Components Coverage Δ
cvat-ui 78.36% <ø> (+0.02%) ⬆️
cvat-server 70.06% <80.00%> (-0.10%) ⬇️

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@Marishka17 Marishka17 self-assigned this Dec 9, 2024
cvat/apps/engine/serializers.py Show resolved Hide resolved
cvat/apps/engine/serializers.py Show resolved Hide resolved
cvat/apps/engine/serializers.py Outdated Show resolved Hide resolved
cvat/apps/engine/cache.py Outdated Show resolved Hide resolved
@zhiltsov-max
Copy link
Contributor Author

/check

Copy link
Contributor

github-actions bot commented Dec 10, 2024

❌ Some checks failed
📄 See logs here

@Marishka17
Copy link
Contributor

@zhiltsov-max, need to fix remark issue

changelog.d/20241213_192726_mzhiltso_optimize_validation_layout_updates.md
  1:1  warning  Missing newline character at end of file  final-newline  remark-lint

cvat/apps/engine/cache.py Outdated Show resolved Hide resolved
cvat/apps/engine/cache.py Outdated Show resolved Hide resolved
cvat/apps/engine/models.py Show resolved Hide resolved
cvat/apps/engine/serializers.py Show resolved Hide resolved
cvat/apps/engine/serializers.py Outdated Show resolved Hide resolved
cvat/apps/engine/serializers.py Outdated Show resolved Hide resolved
cvat/apps/engine/serializers.py Show resolved Hide resolved
cvat/apps/engine/serializers.py Outdated Show resolved Hide resolved
cvat/apps/engine/serializers.py Outdated Show resolved Hide resolved
cvat/apps/engine/serializers.py Outdated Show resolved Hide resolved
Copy link
Contributor

@Marishka17 Marishka17 left a comment

Choose a reason for hiding this comment

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

@zhiltsov-max, please fix this comment: #8789 (comment)
LGTM

@zhiltsov-max zhiltsov-max marked this pull request as draft December 19, 2024 13:33
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
5.3% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@zhiltsov-max zhiltsov-max marked this pull request as ready for review December 19, 2024 15:29
@zhiltsov-max zhiltsov-max merged commit b2a8c1b into develop Dec 19, 2024
42 of 43 checks passed
@zhiltsov-max zhiltsov-max deleted the zm/optimize-validation-layout-updates branch December 19, 2024 16:52
@cvat-bot cvat-bot bot mentioned this pull request Dec 20, 2024
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.

Issues related to tasks with honeypots
4 participants