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

[WIP] Mk/validation api small fixes #8816

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

Conversation

Marishka17
Copy link
Contributor

@Marishka17 Marishka17 commented Dec 11, 2024

Motivation and context

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

    • Introduced new endpoints for managing validation layouts in tasks and jobs, including retrieval and modification capabilities.
  • Bug Fixes

    • Improved error handling and validation logic for tasks and jobs, providing clearer error messages and response statuses.
  • Documentation

    • Updated OpenAPI schema to include new endpoints and refined existing ones for better clarity and usability.
  • Refactor

    • Enhanced the handling of one-to-one relationships in the data models, improving robustness and error management.

Copy link
Contributor

coderabbitai bot commented Dec 11, 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.

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

The changes involve modifications to the CVAT application, focusing on enhancing the handling of validation layouts within tasks and jobs. Key updates include the introduction of a NullableOneToOneField for the task_data field in the ValidationLayout model, improvements in error handling and validation logic in serializers, and the addition of new API endpoints for managing validation layouts. These changes aim to improve the robustness and usability of the application by allowing more flexible relationships and clearer error messaging.

Changes

File Path Change Summary
cvat/apps/engine/migrations/0087_alter_validationlayout_task_data.py Modified task_data in ValidationLayout to NullableOneToOneField with on_delete=CASCADE.
cvat/apps/engine/models.py Added ReverseNullableOneToOneDescriptor and NullableOneToOneField. Updated task_data and validation_layout fields.
cvat/apps/engine/serializers.py Enhanced validation logic, improved error handling, refactored access to validation layouts, and updated serializer methods.
cvat/apps/engine/views.py Added new endpoints for validation layouts in TaskViewSet and JobViewSet, refined response handling, and updated error handling.
cvat/schema.yml Added new endpoints and updated responses for validation layout management, refined schema definitions.

Poem

🐇 In the garden of code, we hop and play,
With layouts of validation, brightening the day.
Fields now nullable, errors caught with grace,
Our API blooms, a joyful embrace!
So let’s dance through the changes, with code as our art,
For every new feature, we celebrate with heart! 🌼


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.

@Marishka17 Marishka17 removed the request for review from SpecLad December 11, 2024 18:06
@Marishka17
Copy link
Contributor Author

Marishka17 commented Dec 11, 2024

@zhiltsov-max, I figured out when reviewing your PRs that PATCH /api/tasks/id/validation_layout returns ValidationError instead of raising it. So, I decided to normalize behavior for all cases(GET/PATH, tasks/jobs API). Then I thought that it would probably be better to allow data.validation_layout to be None instead of checking everywhere whether there is such an attribute or not. Could you please take a look and say what you think?

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3f44834 and 9edbc41.

📒 Files selected for processing (5)
  • cvat/apps/engine/migrations/0087_alter_validationlayout_task_data.py (1 hunks)
  • cvat/apps/engine/models.py (3 hunks)
  • cvat/apps/engine/serializers.py (3 hunks)
  • cvat/apps/engine/views.py (4 hunks)
  • cvat/schema.yml (4 hunks)
🔇 Additional comments (11)
cvat/apps/engine/models.py (3)

263-269: LGTM: Addition of ReverseNullableOneToOneDescriptor

The implementation correctly handles nullable reverse one-to-one relationships by returning None when the related object does not exist.


270-272: LGTM: Addition of NullableOneToOneField

The custom field appropriately sets the related_accessor_class to handle nullable relationships.


313-313: LGTM: Updated type hint for validation_layout

The type hint is updated to ValidationLayout | None, accurately reflecting that the field may be None.

cvat/schema.yml (2)

2667-2668: LGTM! Good addition of standard HTTP status codes for the job validation layout endpoint.

The addition of 204 and 400 response codes improves the API error handling and follows REST best practices:

  • 204: Clearly indicates when no validation layout exists
  • 400: Properly handles invalid requests

Also applies to: 2712-2713


6154-6155: LGTM! Good addition of standard HTTP status codes for the task validation layout endpoint.

The addition of 204 and 400 response codes maintains consistency with the job endpoint and follows REST best practices:

  • 204: Clearly indicates when no validation layout exists
  • 400: Properly handles invalid requests

Also applies to: 6210-6211

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

1749-1749: LGTM

Adding a 204 No Content response for cases when no validation layout is associated with a task appropriately reflects possible API responses.


1757-1757: LGTM

Including a 400 Bad Request response in the OpenAPI schema enhances API documentation and clarifies potential error responses.


1788-1789: LGTM

Returning 204 No Content when no validation layout exists is appropriate and aligns with RESTful practices.


2352-2352: LGTM

Adding a 204 No Content response for cases when no validation layout is associated with a job appropriately reflects possible API responses.


2360-2360: LGTM

Including a 400 Bad Request response in the OpenAPI schema enhances API documentation and clarifies potential error responses.


2396-2401: Ensure correct handling of empty content in response

The condition if content: determines whether to return 200 OK or 204 No Content. Verify that response_serializer.data accurately reflects the presence of a validation layout. Consider explicitly checking if validation_layout is None for clarity and to prevent unexpected behavior.

cvat/apps/engine/models.py Outdated Show resolved Hide resolved
cvat/apps/engine/serializers.py Show resolved Hide resolved
cvat/apps/engine/serializers.py Show resolved Hide resolved
Comment on lines +1780 to +1785
# TODO: probably it should take validation_layout instead of task
request_serializer = TaskValidationLayoutWriteSerializer(db_task, data=request.data)
request_serializer.is_valid(raise_exception=True)
validation_layout = request_serializer.save().data.validation_layout
updated_task = request_serializer.save()
validation_layout = updated_task.data.validation_layout
else:
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address the TODO comment and pass validation_layout to the serializer

The TODO comment suggests that the serializer should take validation_layout instead of db_task. Passing the correct instance ensures proper serialization and updates. Please update the code to pass validation_layout as the instance. If validation_layout is None, handle its creation accordingly.

Apply this diff to fix the issue:

if request.method == "PATCH":
-    # TODO: probably it should take validation_layout instead of task
-    request_serializer = TaskValidationLayoutWriteSerializer(db_task, data=request.data)
+    validation_layout = db_task.data.validation_layout
+    if validation_layout is None:
+        validation_layout = ValidationLayout(data=db_task.data)
+    request_serializer = TaskValidationLayoutWriteSerializer(validation_layout, data=request.data)
    request_serializer.is_valid(raise_exception=True)
-    updated_task = request_serializer.save()
-    validation_layout = updated_task.data.validation_layout
+    validation_layout = request_serializer.save()
else:
    validation_layout = db_task.data.validation_layout
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# TODO: probably it should take validation_layout instead of task
request_serializer = TaskValidationLayoutWriteSerializer(db_task, data=request.data)
request_serializer.is_valid(raise_exception=True)
validation_layout = request_serializer.save().data.validation_layout
updated_task = request_serializer.save()
validation_layout = updated_task.data.validation_layout
else:
validation_layout = db_task.data.validation_layout
if validation_layout is None:
validation_layout = ValidationLayout(data=db_task.data)
request_serializer = TaskValidationLayoutWriteSerializer(validation_layout, data=request.data)
request_serializer.is_valid(raise_exception=True)
validation_layout = request_serializer.save()
else:

@Marishka17
Copy link
Contributor Author

@coderabbitai, stop

Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

@Marishka17: Understood, I will pause the automatic reviews for this pull request.

(_/)
(._.)
(< )

✅ Actions performed

Reviews paused.

@codecov-commenter
Copy link

Codecov Report

Attention: Patch coverage is 71.87500% with 9 lines in your changes missing coverage. Please review.

Project coverage is 73.91%. Comparing base (094c62d) to head (6dce75d).
Report is 8 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #8816      +/-   ##
===========================================
- Coverage    73.92%   73.91%   -0.02%     
===========================================
  Files          409      408       -1     
  Lines        43957    43902      -55     
  Branches      3986     3986              
===========================================
- Hits         32497    32451      -46     
+ Misses       11460    11451       -9     
Components Coverage Δ
cvat-ui 78.37% <ø> (+0.01%) ⬆️
cvat-server 70.09% <71.87%> (-0.05%) ⬇️

@Marishka17
Copy link
Contributor Author

Marishka17 commented Dec 12, 2024

@SpecLad, Do you foresee any possible issues with modifying the logic of the OneToOneField.related_accessor_class slightly (in some cases e.g. for Data <-> ValidationLayout relationship)?

@SpecLad
Copy link
Contributor

SpecLad commented Dec 12, 2024

@SpecLad, Do you foresee any possible issues with modifying the logic of the OneToOneField.related_accessor_class slightly (in some cases e.g. for Data <-> ValidationLayout relationship)?

Yes. Neither related_accessor_class nor ReverseOneToOneDescriptor appear to be part of Django's public API, so this could be broken by a Django update. Also, I think it's a bad idea to modify the logic for relational fields in general, because then you can no longer rely on your existing Django knowledge and documentation for working with such fields.

Plus, it seems like there's a much simpler, non-hacky solution here: define a property on Data that implements your desired logic.

@Marishka17 Marishka17 changed the title Mk/validation api small fixes [WIP] Mk/validation api small fixes Dec 12, 2024
@Marishka17
Copy link
Contributor Author

Plus, it seems like there's a much simpler, non-hacky solution here: define a property on Data that implements your desired logic.

It is not possible to define the property with the same name and use it because Django prioritizes model field attributes over custom properties when both have the same name. However, it may be probably fixed by changing the related_name of the OneToOneField

@SpecLad
Copy link
Contributor

SpecLad commented Dec 13, 2024

It is not possible to define the property with the same name

I didn't mean a property with the same name. I just meant a helper property, side by side with the one generated by Django.

@Marishka17
Copy link
Contributor Author

I didn't mean a property with the same name. I just meant a helper property, side by side with the one generated by Django.

But is it not a bit odd that there will be 2 options for accessing the same data?

@SpecLad
Copy link
Contributor

SpecLad commented Dec 13, 2024

I didn't mean a property with the same name. I just meant a helper property, side by side with the one generated by Django.

But is it not a bit odd that there will be 2 options for accessing the same data?

Sure. I think it's just the price you pay when you provide convenience functionality.

@Marishka17
Copy link
Contributor Author

/check

Copy link
Contributor

github-actions bot commented Dec 19, 2024

✔️ All checks completed successfully
📄 See logs here

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