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 DB requests in project list, job list, and other endpoints #8275

Draft
wants to merge 6 commits into
base: develop
Choose a base branch
from

Conversation

zhiltsov-max
Copy link
Contributor

@zhiltsov-max zhiltsov-max commented Aug 7, 2024

Motivation and context

  • Added an option to use the organization instance from the object in question, if provided (many viewsets prefetch this)
  • Removed .first() calls, leading to extra db requests for projects
  • Added prefetch for source and target storages of jobs
  • 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)
  • Optimized unnecessary DB requests to related models in IAM requests

All this primarily affected GET /api/projects and GET /api/jobs, but other endpoints also benefited from this a little bit.

Examples:
4 projects, > 100 tasks, > 100 jobs

Before:
Screenshot from 2024-08-07 18-27-34

Screenshot from 2024-08-07 18-28-00

After:
Screenshot from 2024-08-07 18-25-54

Screenshot from 2024-08-07 18-24-19

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

  • New Features

    • Enhanced performance of data retrieval in views by optimizing related fields in the JobViewSet.
    • Improved handling of organization data in permissions, ensuring more robust checks and reducing unnecessary database queries.
  • Bug Fixes

    • Refined output of serialized data to include only valid task subsets and handle dimensions correctly.
  • Documentation

    • Updates made to improve clarity on serialized responses and organization permission handling.

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 Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.35%. Comparing base (4a21352) to head (ddfee14).
Report is 1 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #8275      +/-   ##
===========================================
- Coverage    83.38%   83.35%   -0.03%     
===========================================
  Files          389      389              
  Lines        41526    41530       +4     
  Branches      3856     3856              
===========================================
- Hits         34626    34619       -7     
- Misses        6900     6911      +11     
Components Coverage Δ
cvat-ui 79.64% <ø> (-0.04%) ⬇️
cvat-server 86.65% <100.00%> (-0.03%) ⬇️

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

Comment on lines +1716 to +1718
).prefetch_related(
'segment__task__organization',
'segment__task__owner',
Copy link
Member

@bsekachev bsekachev Aug 7, 2024

Choose a reason for hiding this comment

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

May you explain why using prefetch_related is better here? (I see that it is according to experiments, but interesting why prefetch_related is quicker). And why exactly these two fields

From my expectations it just makes extra requests (what in general requires more time) to the database and does not have benefits in comparison with select_related

IMHO we just need to define queryset "per view", leaving in defaults only those fields, necessary to IAM logic (e.g. organization, owner)

Copy link
Contributor Author

@zhiltsov-max zhiltsov-max Aug 7, 2024

Choose a reason for hiding this comment

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

May you explain why using prefetch_related is better here?
From my opinion it just makes extra requests (what in general requires more time) to the database and does not have benefits in comparison with select_related

Yes, it does extra requests and does joining on the server side instead of doing it on the DB side, like in select_related. There are 2 "opposite" sides of prefetching - prefetch and join everything on the DB side and prefetch everything separately and join on the server side. Basically yes, we'd always prefer joining on the DB side, but separation can help in the following case: there is a small table, and its results are expected to be reused in many results. In this case it may be beneficial to fetch this small table separately and join it on the server side. Doing it on the DB side would significantly increase the DB response by populating it with repeated entries. Probably, it's the case in my setup - I have just several users and orgs. I think the best strategy for optimizing this is actually measure the changes on the production server. Or, at least, take the statistics from it, to make the split decisions informed.

IMHO we just need to define queryset "per view", leaving in defaults only those fields, necessary to IAM logic (e.g. organization, owner)

Probably, you meant "per endpoint usecase"? Ok, it makes sense, I agree.

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

sonarcloud bot commented Aug 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.

3 participants