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

Fixed floating point data type check in knowledge vault #1648

Merged

Conversation

himanshugt16
Copy link
Contributor

@himanshugt16 himanshugt16 commented Dec 12, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced validation logic for metadata and payloads, ensuring validated data is accurately reflected in the payload.
    • Improved error handling with clearer messages for data type validation failures.
  • Bug Fixes

    • Adjusted methods to ensure proper handling of float and integer values in payload uploads and updates.
  • Tests

    • Added new tests to validate API functionality for uploading and updating payloads with float fields.

Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The changes in this pull request primarily enhance the CognitionDataProcessor class in kairon/shared/cognition/processor.py. Modifications include improved validation logic for metadata and payloads, with updated method signatures and enhanced error handling. New test functions were added to tests/integration_test/services_test.py to verify the handling of float fields in payload uploads and updates. The overall structure of the methods remains consistent, but the updates improve data validation and robustness.

Changes

File Path Change Summary
kairon/shared/cognition/processor.py - Enhanced validate_metadata_and_payload method to assign validated column values to data.
- Modified save_cognition_data and update_cognition_data to update payload['data'] directly.
- Improved validate_column_values to raise specific exceptions for data type validation failures.
- Updated method signatures for validate_metadata_and_payload, save_cognition_data, and update_cognition_data.
tests/integration_test/services_test.py - Added test_payload_upload_api_with_float_field, test_payload_upload_api_with_float_field_value_integer, and test_update_payload_upload_api_with_float_field_value_integer to test float field handling in payloads.

Possibly related PRs

Suggested reviewers

  • hiteshghuge
  • sfahad1414

Poem

In the land of code where rabbits play,
We've polished our checks, come what may.
Float fields now dance, integers too,
With validations strong, our data is true!
Hopping through tests, we leap with delight,
For every new change makes our future bright! 🐇✨


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. (Experiment)
  • @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.

Copy link

@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

🧹 Outside diff range and nitpick comments (6)
tests/integration_test/services_test.py (6)

1382-1423: Consider enhancing test coverage with edge cases.

The test has good structure with proper setup and cleanup, but could be strengthened by:

  1. Adding test cases for edge cases (e.g., max/min float values, scientific notation)
  2. Including descriptive messages in assertions for better debugging

Example improvement:

-    assert data_dict['data']['price'] == 54.02
+    assert data_dict['data']['price'] == 54.02, f"Expected price to be 54.02 but got {data_dict['data']['price']}"

1459-1459: Remove debug print statement.

Debug print statement should be removed before committing.

-    print(data_dict)

1424-1468: Consider refactoring common setup code and adding negative number test.

The test has duplicate setup code that could be moved to a fixture. Also consider adding test cases for negative integers.

Example fixture:

@pytest.fixture
def setup_bot_settings():
    bot_settings = BotSettings.objects(bot=pytest.bot).get()
    bot_settings.content_importer_limit_per_day = 10
    bot_settings.cognition_collections_limit = 20
    bot_settings.llm_settings['enable_faq'] = True
    bot_settings.save()
    yield
    bot_settings = BotSettings.objects(bot=pytest.bot).get()
    bot_settings.llm_settings['enable_faq'] = False
    bot_settings.save()

1505-1505: Remove debug print statements.

Multiple debug print statements should be removed.

-    print(data_dict)

Also applies to: 1529-1529


1510-1511: Remove excessive blank lines.

Multiple consecutive blank lines should be removed to maintain consistent spacing.


1469-1538: Consider adding error case tests.

While the happy path is well tested, consider adding tests for error cases such as:

  1. Attempting to update with invalid data types
  2. Testing boundary conditions
  3. Testing malformed requests

Example error case:

def test_update_payload_upload_api_with_invalid_float(monkeypatch):
    # ... setup code ...
    update_payload = {
        "data": {"item": "Box", "price": "invalid_float"},
        "content_type": "json",
        "collection": "update_with_float_field_value_integer"
    }
    response = client.put(
        url=f"/api/bot/{pytest.bot}/data/cognition/{pytest.payload_id}",
        json=update_payload,
        headers={"Authorization": pytest.token_type + " " + pytest.access_token},
    )
    actual = response.json()
    assert actual["error_code"] != 0
    assert "invalid float value" in actual["message"].lower()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5e40c45 and 4f7076c.

📒 Files selected for processing (2)
  • kairon/shared/cognition/processor.py (3 hunks)
  • tests/integration_test/services_test.py (1 hunks)
🔇 Additional comments (4)
kairon/shared/cognition/processor.py (3)

271-274: Assigning validated values back to data

The code correctly updates data with validated column values, ensuring data integrity.


295-295: Updating payload with validated data

Assigning the validated data back to payload['data'] ensures that any transformations or validations are reflected when saving cognition data.


322-322: ⚠️ Potential issue

Critical issue: Unvalidated data being saved

After validating payload['data'], the variable data still holds the unvalidated data. Consequently, payload_obj.data = data assigns unvalidated data to the object. Update data with the validated data to ensure consistency.

Apply this diff to fix the issue:

     if content_type == CognitionDataType.json.value:
         payload['data'] = CognitionDataProcessor.validate_metadata_and_payload(bot, payload)
+        data = payload['data']
     payload_obj.data = data

Likely invalid or redundant comment.

tests/integration_test/services_test.py (1)

1382-1538: Overall good test coverage with room for improvement.

The tests provide good coverage of float field handling in the knowledge vault, including:

  1. Direct float value storage
  2. Integer to float conversion
  3. Update functionality

However, consider the following improvements:

  1. Move common setup/teardown code to fixtures
  2. Add error case testing
  3. Remove debug print statements
  4. Add edge case testing

Copy link
Collaborator

@hiteshghuge hiteshghuge left a comment

Choose a reason for hiding this comment

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

reviewed

@hiteshghuge hiteshghuge merged commit 3586fe9 into digiteinfotech:master Dec 12, 2024
8 checks passed
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.

2 participants