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

cognition upload fix #1674

Merged
merged 1 commit into from
Dec 20, 2024
Merged

Conversation

hasinaxp
Copy link
Contributor

@hasinaxp hasinaxp commented Dec 19, 2024

fixed download failure for multiple content type
added cognition collection count validation for upload

Summary by CodeRabbit

  • New Features

    • Introduced enhanced validation for bot content uploads, including checks for collection limits during mass uploads.
    • Added a new method for handling collection limit checks for mass uploads.
  • Bug Fixes

    • Improved error handling and reporting for validation failures related to bot content uploads.
  • Tests

    • Added new test cases to improve coverage for validation and processing logic, including scenarios for collection limit checks.
  • Chores

    • Cleaned up unused code in the data processing logic.

Copy link

coderabbitai bot commented Dec 19, 2024

Walkthrough

The pull request introduces enhanced validation mechanisms for bot content uploads, focusing on collection limit checks during mass uploading. The changes span multiple files, including the TrainingDataValidator, CognitionDataProcessor, and MongoProcessor classes. A new method is_collection_limit_exceeded_for_mass_uploading is added to validate collection limits, and corresponding updates are made to validation and processing methods to incorporate these checks. The modifications aim to improve data integrity and provide more robust error handling during bot content imports.

Changes

File Change Summary
kairon/importer/validator/file_validator.py - Added validation for collection limits in validate_content and validate_bot_content methods
- Integrated CognitionDataProcessor checks for mass upload limits
kairon/shared/cognition/processor.py - Added new static method is_collection_limit_exceeded_for_mass_uploading
- Implemented logic to check collection limits during mass uploads
kairon/shared/data/processor.py - Added get_error_report_file_path method
- Modified __prepare_cognition_data_for_bot to conditionally format JSON data
- Removed commented-out code in download_files method
tests/unit_test/validator/training_data_validator_test.py - Added new test test_validate_content_collection_limit_exceeded
- Imported patch for mocking test scenarios
tests/unit_test/data_processor/data_processor2_test.py - Added new test cases for collection limit validation

Sequence Diagram

sequenceDiagram
    participant User
    participant TrainingDataValidator
    participant CognitionDataProcessor
    
    User->>TrainingDataValidator: Upload bot content
    TrainingDataValidator->>CognitionDataProcessor: Check collection limit
    alt Limit Exceeded
        CognitionDataProcessor-->>TrainingDataValidator: Return limit error
        TrainingDataValidator-->>User: Reject upload with error
    else Limit Not Exceeded
        TrainingDataValidator->>TrainingDataValidator: Continue validation
        TrainingDataValidator-->>User: Allow content upload
    end
Loading

Possibly related PRs

Suggested reviewers

  • hiteshghuge
  • sfahad1414

Poem

🐰 Validation's dance, a rabbit's delight,
Checking limits with algorithmic might!
Collections counted, errors kept at bay,
Code leaps forward in a playful array.
Hop, hop, hooray for robust design! 🎉


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.

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

🧹 Nitpick comments (3)
kairon/importer/validator/file_validator.py (1)

1061-1065: Collection limit validation added for mass uploading

The code adds validation to check if collection limits are exceeded during mass uploading. This is a good addition to prevent resource abuse.

Consider adding error handling for potential exceptions that could occur during the collection limit validation:

+try:
    if CognitionDataProcessor.is_collection_limit_exceeded_for_mass_uploading(bot, user, new_collection_names, overwrite):
        bot_content_errors.append('Collection limit exceeded!')
+except Exception as e:
+    logger.error(f"Error validating collection limits: {str(e)}")
+    bot_content_errors.append(f'Error validating collection limits: {str(e)}')
kairon/shared/data/processor.py (1)

Line range hint 4183-4201: Secure file path handling implemented

The code implements secure file path handling with proper validation. This is good for preventing path traversal attacks.

Consider adding these additional security checks:

 @staticmethod
 def get_error_report_file_path(bot: str, event_id: str) -> str:
     if not event_id.isalnum():
         raise HTTPException(status_code=400, detail="Invalid event ID")
+    if not bot.isalnum():
+        raise HTTPException(status_code=400, detail="Invalid bot ID")
 
     base_dir = os.path.join('content_upload_summary', bot)
+    if not os.path.exists(base_dir):
+        raise HTTPException(status_code=404, detail="Bot directory not found")
 
     file_name = f'failed_rows_with_errors_{event_id}.csv'
     file_path = os.path.join(base_dir, file_name)
 
+    # Use realpath to resolve any symlinks
+    real_path = os.path.realpath(file_path)
+    real_base = os.path.realpath(base_dir)
+    if not real_path.startswith(real_base):
+        raise HTTPException(status_code=400, detail="Invalid file path")

     if not os.path.exists(file_path) or not file_path.startswith(base_dir):
         raise HTTPException(status_code=404, detail="Error Report not found")
 
     return file_path
tests/unit_test/data_processor/data_processor2_test.py (1)

157-171: Add test cases for edge cases

The test suite should include additional test cases for input validation.

Consider adding these test cases:

@patch('kairon.shared.cognition.processor.MongoProcessor')
@patch('kairon.shared.cognition.processor.CognitionSchema')
def test_is_collection_limit_exceeded_for_mass_uploading_empty_collections(mock_cognition_schema, mock_mongo_processor):
    bot = "test_bot"
    user = "test_user"
    collection_names = []

    with pytest.raises(AppException, match="Collection names cannot be empty!"):
        CognitionDataProcessor.is_collection_limit_exceeded_for_mass_uploading(bot, user, collection_names)

@patch('kairon.shared.cognition.processor.MongoProcessor')
@patch('kairon.shared.cognition.processor.CognitionSchema')
def test_is_collection_limit_exceeded_for_mass_uploading_empty_bot(mock_cognition_schema, mock_mongo_processor):
    bot = ""
    user = "test_user"
    collection_names = ["collection1"]

    with pytest.raises(AppException, match="Bot and user are required!"):
        CognitionDataProcessor.is_collection_limit_exceeded_for_mass_uploading(bot, user, collection_names)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 45a5000 and b850f95.

📒 Files selected for processing (5)
  • kairon/importer/validator/file_validator.py (1 hunks)
  • kairon/shared/cognition/processor.py (1 hunks)
  • kairon/shared/data/processor.py (1 hunks)
  • tests/unit_test/data_processor/data_processor2_test.py (2 hunks)
  • tests/unit_test/validator/training_data_validator_test.py (2 hunks)
🔇 Additional comments (2)
kairon/shared/data/processor.py (1)

693-694: Conditional formatting for JSON type data

The code now only formats entries if the type is "json", which is a good optimization to avoid unnecessary processing.

tests/unit_test/validator/training_data_validator_test.py (1)

914-925: LGTM!

The test case properly validates the collection limit exceeded scenario and verifies the correct error message is returned.

kairon/shared/cognition/processor.py Show resolved Hide resolved
Copy link
Collaborator

@sfahad1414 sfahad1414 left a comment

Choose a reason for hiding this comment

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

Approved

@sfahad1414 sfahad1414 merged commit c529677 into digiteinfotech:master Dec 20, 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