8000 Optimize DB requests in task list, quality conflicts list and cloudstorages by zhiltsov-max · Pull Request #8275 · cvat-ai/cvat · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
/ cvat Public
< 8000 ul class="pagehead-actions flex-shrink-0 d-none d-md-inline" style="padding: 2px 0;">
  • Notifications You must be signed in to change notification settings
  • Fork 3.2k
  • Optimize DB requests in task list, quality conflicts list and cloudstorages #8275

    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

    Merged
    merged 32 commits into from
    May 7, 2025

    Conversation

    zhiltsov-max
    Copy link
    Contributor
    @zhiltsov-max zhiltsov-max commented Aug 7, 2024

    Motivation and context

    • Optimized task list requests
    • Optimized quality conflicts requests
    • Optimized calls to related manifests in cloudstorages api (however, manifests should be either moved to a separate endpoint or should be limited in maximum number per CS)

    Notes:

    • /api/quality/conflicts/ - will be further changed in Project quality #9116, but improved for now
    • /api/requests/ - long processing for getting a list of requests
    • Try to optimize count() requests for list endpoints. Because of the filter.distinct used, we get slow requests. Potentially can be optimized inside pagination So far the chosen approach is to provide an optimized implementation in a dedicated list_serializer_class.to_representation().
    • Try to use prefetch cache for IAM checks, they request orgs and memberships several times - improved in Optimize permission checks in jobs list #9275, used here. Memberships fetches still can probably be improved

    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.

    Copy link
    Contributor
    coderabbitai bot commented Aug 7, 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

    Recent updates enhance the reliability and performance of the CVAT application by improving data serialization and query optimization. Key changes include filtering empty task subsets in serializers, refining dimension retrieval logic, and expanding related fields in database queries for the JobViewSet. Additionally, the permission logic now handles organization retrieval more efficiently, returning None when inputs are invalid and checking for existing organization associations before querying the database.

    Changes

    Files Change Summary
    cvat/apps/engine/serializers.py Updated to_representation method to filter out empty task subsets and improve dimension retrieval.
    cvat/apps/engine/views.py Enhanced JobViewSet with additional fields in select_related to optimize database queries.
    cvat/apps/iam/permissions.py Modified get_organization to return None for falsy organization_id and check for existing organization associations.

    Poem

    🐰 A hop, a skip, a change so grand,
    In serializers' heart, we take a stand.
    No empty tasks to cloud the way,
    With dimensions clear, we greet the day!
    Queries optimized, oh what a delight,
    In CVAT’s world, everything feels right! 🌟


    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>.
      • 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 generate interesting stats about this repository and render them as a table.
      • @coderabbitai show all the console.log statements in this repository.
      • @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 as 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.

    Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

    Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits

    Files that changed from the base of the PR and between ff50b46 and 4846625.

    Files selected for processing (3)
    • cvat/apps/engine/serializers.py (1 hunks)
    • cvat/apps/engine/views.py (1 hunks)
    • cvat/apps/iam/permissions.py (1 hunks)
    Additional comments not posted (3)
    cvat/apps/iam/permissions.py (1)

    51-57: LGTM! But verify the function usage in the codebase.

    The code changes are approved.

    However, ensure that all function calls to get_organization handle the new logic correctly.

    Verification successful

    The function usage is verified and no issues are found.

    The get_organization function is used correctly in the codebase, handling the new logic appropriately.

    • get_iam_context(request, obj) uses get_organization to retrieve the organization and then gets membership based on it.
    • Middleware setup uses get_organization to set request.iam_context.
    Scripts executed

    The following scripts were executed for the analysis:

    Script:

    #!/bin/bash
    # Description: Verify all function calls to `get_organization` handle the new logic correctly.
    
    # Test: Search for the function usage. Expect: Only occurrences of the new logic.
    rg --type python -A 5 $'get_organization'
    

    Length of output: 71


    Script:

    #!/bin/bash
    # Description: Verify all function calls to `get_organization` handle the new logic correctly.
    
    # Find all Python files and search for the `get_organization` function usage within them.
    fd -e py -x rg 'get_organization' {}
    

    Length of output: 498


    Script:

    #!/bin/bash
    # Description: Verify all function calls to `get_organization` handle the new logic correctly.
    
    # Find all Python files and search for the `get_organization` function usage within them, including more context lines.
    fd -e py -x rg 'get_organization' -A 10 -B 5 {}
    

    Length of output: 3618

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

    1363-1370: LGTM!

    The changes improve the robustness of the to_representation method by ensuring only valid, non-empty task subsets are included and a valid dimension is returned.

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

    1708-1719: Optimize database query performance by expanding select_related.

    The added fields in the select_related method (segment__task__source_storage, segment__task__target_storage, segment__task__organization, segment__task__project__organization, segment__task__owner, segment__task__project__owner) will help optimize database queries by pre-fetching related data. This change should improve performance when accessing these fields in the viewset.

    @bsekachev
    Copy link
    Member
    bsekachev commented Aug 7, 2024

    /api/jobs now takes longer time (on queries metric)

    Each /api/jobs/id/preview also now takes longer time (on queries metric) [significantly]
    In the second request we do not need many JOINS, so, I would suggest to reduce number of select_related arguments.

    @codecov-commenter
    Copy link
    codecov-commenter commented Aug 7, 2024

    Codecov Report

    Attention: Patch coverage is 81.81818% with 6 lines in your changes missing coverage. Please review.

    Project coverage is 73.91%. Comparing base (29cde3e) to head (04b1958).
    Report is 13 commits behind head on develop.

    Additional details and impacted files
    @@             Coverage Diff             @@
    ##           develop    #8275      +/-   ##
    ===========================================
    - Coverage    73.94%   73.91%   -0.03%     
    ===========================================
      Files          435      435              
      Lines        45595    45661      +66     
      Branches      3924     3924              
    ===========================================
    + Hits         33716    33752      +36     
    - Misses       11879    11909      +30     
    Components Coverage Δ
    cvat-ui 77.53% <ø> (-0.03%) ⬇️
    cvat-server 71.00% <81.81%> (-0.02%) ⬇️
    🚀 New features to boost your workflow:
    • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
    • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

    @zhiltsov-max
    Copy link
    Contributor Author

    I've increased the page_size to get more representative output:
    http://localhost:7000/api/jobs?page_size=1000 (in my case it returned first 1000 of 2250 jobs).

    Baseline:

    Screenshot from 2024-08-07 19-29-46

    Select_related (source_storage, target_storage, organization, owner), 12 joins:

    Screenshot from 2024-08-07 19-29-53

    Select_related (source_storage, target_storage) + prefetch_related(organization, owner), 10 joins:

    Screenshot from 2024-08-07 19-29-58

    And the same, but for 12 jobs (as UI presents):

    Screenshot from 2024-08-07 19-28-42
    Screenshot from 2024-08-07 19-29-31
    Screenshot from 2024-08-07 19-29-37

    I think, it makes sense to choose one of the 2 optimized variants. I think, the version with 10 joins is a good tradeoff for now, it provides a good balance between the two others.

    @zhiltsov-max zhiltsov-max marked this pull request as draft August 7, 2024 19:37
    Copy link

    @zhiltsov-max zhiltsov-max removed the request for review from Marishka17 January 27, 2025 10:31
    @zhiltsov-max zhiltsov-max marked this pull request as ready for review April 30, 2025 15:16
    @zhiltsov-max zhiltsov-max requested a review from SpecLad as a code owner April 30, 2025 15:16
    @zhiltsov-max zhiltsov-max changed the title Optimize DB requests in project list, job list, and other endpoints Optimize DB requests in task list, quality conflicts list and cloudstorages Apr 30, 2025
    job_counts = {
    task["id"]: task
    for task in models.Task.objects
    .filter(id__in=page_task_ids)
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    I just thought of something WRT this and similar optimizations - how well does this behave when page_size is all and there are a lot of tasks?

    Copy link
    Contributor Author

    Choose a reason for hiding this comment

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

    page_size=all must be allowed only in development deployments. It can crash the server because of OOM.


    if is_field_cached(db_task, "segment_set"):
    # Refresh segments to report actual dates if they were fetched previously
    # Doing so without a check leads to an error if the related object is not prefetched
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    FWIW, I think that's a bug, so I filed a Django bug report: https://code.djangoproject.com/ticket/36372.

    Copy link
    sonarqubecloud bot commented May 7, 2025

    @SpecLad SpecLad merged commit ba4f499 into develop May 7, 2025
    34 checks passed
    @SpecLad SpecLad deleted the zm/optimize-viewsets branch May 7, 2025 15:31
    @cvat-bot cvat-bot bot mentioned this pull request May 8, 2025
    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.

    4 participants
    0