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

feat(clp-package): Let clp-config objects check against unexpected fields. #676

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

haiqi96
Copy link
Contributor

@haiqi96 haiqi96 commented Jan 18, 2025

Description

Currently clp-config doesn't enforce what fields are allowed in the config object.
This could be error prone when user specifies a value with None as default.

For example, if user forgets to indent the "credentials" config, clp_config will sliently ignore it and assign a default=None to the credentials under the s3_config. As a result, the package returns an no credentials error at later stage of compression/search.

Similarly, user could make a typo in the field name and as a result the field will be silently ignored.

This PR introduces a new base class with config that forbids extra field, so that all other config objects can simply inherit from this bass class and automatically check against unexpected field.

Known issue:
The error message can gets confusing if user makes a mistake under storage config.

For example, given the following config with a typo in "access_secret_key" field:

storage:
  type: "s3"
  staging_directory: "var/data/my_staging_archives"
  s3_config:
    region_code: "us-west-1"
    bucket: "private-clp-test-bucket"
    key_prefix: "compression_output/"
    credentials:
      access_key_id: "12345567"
      access_key_sect: "ABCDEFG"

User will see error message:

pydantic.error_wrappers.ValidationError: 5 validation errors for CLPConfig
# First 3
archive_output -> storage -> type
  unexpected value; permitted: 'fs' (type=value_error.const; given=s3; permitted=('fs',))
archive_output -> storage -> s3_config
  extra fields not permitted (type=value_error.extra)
archive_output -> storage -> staging_directory
  extra fields not permitted (type=value_error.extra)
#Latter 2
archive_output -> storage -> s3_config -> credentials -> secret_access_key
  field required (type=value_error.missing)
archive_output -> storage -> s3_config -> credentials -> access_key_sect
  extra fields not permitted (type=value_error.extra)

While I don't entirely understand the behavior, here is my guess:
The latter 2 messages are printed when pydantic maps the storage config into S3Storage config, and it found that secret_access_key is missing, and access_key_sect is an unexpected field

Then, pydantic tries to map the storage config into FsStorage, where it prints the first 3 messages, because:

  1. The supplied type is "s3"
  2. There are two unexpected fields.

Validation performed

Manually validated.

Summary by CodeRabbit

  • Refactor
    • Enhanced data validation by introducing a new base model that forbids extra fields for multiple configuration classes
    • Updated inheritance for configuration classes to use stricter Pydantic model validation
    • Improved data integrity by preventing unintended field additions during object instantiation

Copy link
Contributor

coderabbitai bot commented Jan 18, 2025

Walkthrough

The changes involve introducing a new BaseModelForbidExtra class in the clp_config.py module, which extends Pydantic's BaseModel with a configuration that forbids extra fields. Multiple existing classes that previously inherited from BaseModel are now updated to inherit from this new BaseModelForbidExtra. This modification enhances data validation by ensuring that any attempt to include undefined fields will raise a validation error, while maintaining the original structure and functionality of the classes.

Changes

File Change Summary
components/clp-py-utils/clp_py_utils/clp_config.py Added BaseModelForbidExtra class and updated inheritance for multiple configuration classes including Package, Database, CompressionScheduler, QueryScheduler, CompressionWorker, QueryWorker, Redis, Reducer, ResultsCache, Queue, S3Credentials, S3Config, FsStorage, S3Storage, ArchiveOutput, StreamOutput, WebUi, LogViewerWebUi, CLPConfig, and WorkerConfig

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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

🧹 Nitpick comments (3)
components/clp-py-utils/clp_py_utils/clp_config.py (3)

Line range hint 318-334: Consider enhancing error messages for credential validation.

While the validation is robust, the error messages could be more helpful when dealing with credential configurations. For example, when a user mistypes "access_secret_key" instead of "secret_access_key", they should receive a clear message suggesting the correct field name.

 class S3Credentials(BaseModelForbidExtra):
     access_key_id: str
     secret_access_key: str
 
     @validator("access_key_id")
     def validate_access_key_id(cls, field):
         if field == "":
-            raise ValueError("access_key_id cannot be empty")
+            raise ValueError("S3 access_key_id cannot be empty")
         return field
 
     @validator("secret_access_key")
     def validate_secret_access_key(cls, field):
         if field == "":
-            raise ValueError("secret_access_key cannot be empty")
+            raise ValueError("S3 secret_access_key cannot be empty. Note: If you specified 'access_secret_key', this is a typo - the correct field name is 'secret_access_key'")
         return field

Also applies to: 335-367


Line range hint 546-685: Consider consolidating validation methods in CLPConfig.

The class has multiple separate validation methods that are called independently. Consider creating a single validate_all() method that ensures all validations are performed in the correct order.

 class CLPConfig(BaseModelForbidExtra):
     # ... existing code ...
+
+    def validate_all(self, clp_home: pathlib.Path):
+        """
+        Performs all validations in the correct order.
+        Raises ValueError if any validation fails.
+        """
+        self.make_config_paths_absolute(clp_home)
+        self.validate_input_logs_dir()
+        self.validate_archive_output_config()
+        self.validate_stream_output_dir()
+        self.validate_data_dir()
+        self.validate_logs_dir()

Line range hint 1-700: Consider reorganizing the configuration classes for better maintainability.

The file has grown quite large with many configuration classes. Consider:

  1. Moving shared validation logic (e.g., _validate_logging_level, _validate_host) to a separate validators.py module
  2. Grouping related configurations (e.g., storage-related, worker-related) into separate modules

This would improve maintainability and make the codebase more modular.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 774ba19 and 082211c.

📒 Files selected for processing (1)
  • components/clp-py-utils/clp_py_utils/clp_config.py (20 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: lint-check (ubuntu-latest)
  • GitHub Check: lint-check (macos-latest)
  • GitHub Check: build (macos-latest)
🔇 Additional comments (1)
components/clp-py-utils/clp_py_utils/clp_config.py (1)

60-63: Well-designed base class implementation!

The BaseModelForbidExtra class effectively implements the validation of unexpected fields, which will help catch configuration errors early and prevent silent failures.

@haiqi96
Copy link
Contributor Author

haiqi96 commented Jan 18, 2025

Actually it might be an overkill to let all config object to inherit this new class BaseClassForbitExtra.
Perhaps we only need to let the config with optional field to inherit from BaseClassForbitExtra

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.

1 participant