Skip to content

Conversation

@tisnik
Copy link
Contributor

@tisnik tisnik commented Oct 15, 2025

Description

LCORE-741: quota handlers config

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement

Related Tickets & Documents

  • Related Issue #LCORE-741

Summary by CodeRabbit

  • New Features

    • Added a new "quota_handlers" configuration section for managing quota handling, offering optional SQLite or PostgreSQL backends and a toggle to enable token history. Defaults preserve existing behavior (disabled).
  • Tests

    • Updated configuration serialization tests to include the new "quota_handlers" section and verify default values.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 15, 2025

Walkthrough

Adds a new QuotaHandlersConfig model (fields: sqlite, postgres, enable_token_history) and a new quota_handlers field on Configuration with a default factory. Updates unit tests and documentation to include the new configuration surface. No existing behavior or other fields removed.

Changes

Cohort / File(s) Summary of Changes
Configuration model
src/models/config.py
Added QuotaHandlersConfig model with sqlite: Optional[SQLiteDatabaseConfiguration] = None, postgres: Optional[PostgreSQLDatabaseConfiguration] = None, and enable_token_history: bool = False. Added quota_handlers: QuotaHandlersConfig field to Configuration with a default factory.
Unit tests
tests/unit/models/config/test_dump_configuration.py
Updated expected dumped configuration JSON to include top-level quota_handlers with defaults: sqlite: None, postgres: None, enable_token_history: False. Adjusted assertions to check presence and exact structure.
Documentation / UML
docs/config.puml
Added QuotaHandlersConfig to public model diagram and linked it as a field on Configuration; documented fields (sqlite, postgres, enable_token_history) and inheritance from ConfigurationBase.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

In my burrow of bytes I hop and sing,
A quota patch makes the config spring.
Postgres naps and SQLite dreams,
Token tales toggled at the seams.
Tests nibble carrots — all green things. 🥕🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly identifies the Jira ticket and succinctly describes the primary change of adding the quota handlers configuration, directly aligning with the new QuotaHandlersConfig model and its integration into the Configuration class. It is concise, specific, and gives team members a clear understanding of the change at a glance. There is no extraneous detail or ambiguity.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d7a826 and 5bff9ba.

⛔ Files ignored due to path filters (2)
  • docs/config.png is excluded by !**/*.png
  • docs/config.svg is excluded by !**/*.svg
📒 Files selected for processing (3)
  • docs/config.puml (3 hunks)
  • src/models/config.py (2 hunks)
  • tests/unit/models/config/test_dump_configuration.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/models/config.py
  • tests/unit/models/config/test_dump_configuration.py
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-18T16:46:33.353Z
Learnt from: CR
PR: lightspeed-core/lightspeed-stack#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-18T16:46:33.353Z
Learning: Applies to src/{models/config.py,configuration.py} : All configuration uses Pydantic models extending ConfigurationBase

Applied to files:

  • docs/config.puml
📚 Learning: 2025-09-18T16:46:33.353Z
Learnt from: CR
PR: lightspeed-core/lightspeed-stack#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-18T16:46:33.353Z
Learning: Applies to src/models/**/*.py : Pydantic models: use BaseModel for data models and extend ConfigurationBase for configuration

Applied to files:

  • docs/config.puml
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build-pr
  • GitHub Check: e2e_tests (ci)
  • GitHub Check: e2e_tests (azure)
🔇 Additional comments (1)
docs/config.puml (1)

48-48: LGTM! Documentation accurately reflects the new configuration model.

The PlantUML diagram correctly documents the new QuotaHandlersConfig class and its integration into the Configuration model. The changes follow established patterns in the codebase:

  • QuotaHandlersConfig extends ConfigurationBase (line 187), consistent with the learning that all configuration models extend this base
  • Field types and structure mirror similar configuration classes like ConversationCacheConfiguration
  • The quota_handlers field on Configuration is properly typed as Optional[QuotaHandlersConfig]
  • The enable_token_history field is typed as bool (not Optional[bool]), which aligns with test expectations that it defaults to False

Based on learnings.

Also applies to: 138-142, 187-187


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (1)
src/models/config.py (1)

567-573: Consider adding validation for database configuration consistency.

Similar configuration classes like DatabaseConfiguration (lines 113-127) and ConversationCacheConfiguration (lines 521-551) include @model_validator methods to ensure configuration consistency. Consider whether QuotaHandlersConfig should validate:

  • Whether both sqlite and postgres can be configured simultaneously
  • Whether at least one backend must be configured when quota handlers are enabled
  • Whether enable_token_history requires a specific backend

Example validation pattern:

@model_validator(mode="after")
def check_quota_handlers_configuration(self) -> Self:
    """Check quota handlers configuration."""
    # Add validation logic based on your requirements
    # For example, if only one backend should be configured:
    backends_configured = sum([
        self.sqlite is not None,
        self.postgres is not None
    ])
    if backends_configured > 1:
        raise ValueError("Only one database backend can be configured for quota handlers")
    return self
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 721c9f0 and 6d7a826.

📒 Files selected for processing (2)
  • src/models/config.py (2 hunks)
  • tests/unit/models/config/test_dump_configuration.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
src/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

Use absolute imports for internal modules (e.g., from auth import get_auth_dependency)

Files:

  • src/models/config.py
**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.py: All modules start with descriptive module-level docstrings explaining purpose
Use logger = logging.getLogger(name) for module logging after import logging
Define type aliases at module level for clarity
All functions require docstrings with brief descriptions
Provide complete type annotations for all function parameters and return types
Use typing_extensions.Self in model validators where appropriate
Use modern union syntax (str | int) and Optional[T] or T | None consistently
Function names use snake_case with descriptive, action-oriented prefixes (get_, validate_, check_)
Avoid in-place parameter modification; return new data structures instead of mutating arguments
Use appropriate logging levels: debug, info, warning, error with clear messages
All classes require descriptive docstrings explaining purpose
Class names use PascalCase with conventional suffixes (Configuration, Error/Exception, Resolver, Interface)
Abstract base classes should use abc.ABC and @AbstractMethod for interfaces
Provide complete type annotations for all class attributes
Follow Google Python docstring style for modules, classes, and functions, including Args, Returns, Raises, Attributes sections as needed

Files:

  • src/models/config.py
  • tests/unit/models/config/test_dump_configuration.py
src/{models/config.py,configuration.py}

📄 CodeRabbit inference engine (CLAUDE.md)

src/{models/config.py,configuration.py}: All configuration uses Pydantic models extending ConfigurationBase
Configuration base models must set model_config with extra="forbid" to reject unknown fields

Files:

  • src/models/config.py
src/{models/**/*.py,configuration.py}

📄 CodeRabbit inference engine (CLAUDE.md)

src/{models/**/*.py,configuration.py}: Use @field_validator and @model_validator for custom validation in Pydantic models
Use precise type hints in configuration (e.g., Optional[FilePath], PositiveInt, SecretStr)

Files:

  • src/models/config.py
src/models/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

src/models/**/*.py: Pydantic models: use BaseModel for data models and extend ConfigurationBase for configuration
Use @model_validator and @field_validator for Pydantic model validation

Files:

  • src/models/config.py
tests/{unit,integration}/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

tests/{unit,integration}/**/*.py: Use pytest for all unit and integration tests
Do not use unittest in tests; pytest is the standard

Files:

  • tests/unit/models/config/test_dump_configuration.py
tests/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

tests/**/*.py: Use pytest-mock to create AsyncMock objects for async interactions in tests
Use the shared auth mock constant: MOCK_AUTH = ("mock_user_id", "mock_username", False, "mock_token") in tests

Files:

  • tests/unit/models/config/test_dump_configuration.py
🪛 GitHub Actions: Black
tests/unit/models/config/test_dump_configuration.py

[error] 1-1: Black formatting check failed. Run 'black' to reformat the file.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build-pr
  • GitHub Check: e2e_tests (azure)
  • GitHub Check: e2e_tests (ci)
🔇 Additional comments (4)
src/models/config.py (1)

594-594: LGTM!

The quota_handlers field is properly added to the Configuration class with an appropriate default factory, following the established pattern used by other configuration fields like conversation_cache (line 590-592).

tests/unit/models/config/test_dump_configuration.py (3)

92-92: LGTM!

The assertion correctly verifies that the new quota_handlers field is present in the serialized configuration.


175-179: LGTM!

The expected JSON structure correctly reflects the default values for the QuotaHandlersConfig model. The test properly validates serialization of the new configuration field.

Note: If the field name is changed from storage to postgres as suggested in the review of src/models/config.py, this test expectation will need to be updated accordingly (see the note in that review comment).


1-1: Install and run Black to fix formatting. CI is failing due to Black formatting errors. Ensure Black is installed in your environment (pip install black), then run:

black tests/unit/models/config/test_dump_configuration.py

Commit the reformatted file and re-run the pipeline to confirm the issue is resolved.

Comment on lines 567 to 573
class QuotaHandlersConfig(ConfigurationBase):
"""Quota limiter configuration."""

sqlite: Optional[SQLiteDatabaseConfiguration] = None
storage: Optional[PostgreSQLDatabaseConfiguration] = None
enable_token_history: bool = False

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 | 🟡 Minor

Inconsistent field naming: use postgres instead of storage.

The field storage holds a PostgreSQLDatabaseConfiguration but doesn't follow the naming pattern established in similar configuration classes. Both DatabaseConfiguration (line 111) and ConversationCacheConfiguration (line 519) use postgres for their PostgreSQL fields.

Apply this diff to align with the established naming pattern:

 class QuotaHandlersConfig(ConfigurationBase):
     """Quota limiter configuration."""
 
     sqlite: Optional[SQLiteDatabaseConfiguration] = None
-    storage: Optional[PostgreSQLDatabaseConfiguration] = None
+    postgres: Optional[PostgreSQLDatabaseConfiguration] = None
     enable_token_history: bool = False

Note: This change will also require updating the test expectations in tests/unit/models/config/test_dump_configuration.py at line 177:

     "quota_handlers": {
         "sqlite": None,
-        "storage": None,
+        "postgres": None,
         "enable_token_history": False
     },
📝 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
class QuotaHandlersConfig(ConfigurationBase):
"""Quota limiter configuration."""
sqlite: Optional[SQLiteDatabaseConfiguration] = None
storage: Optional[PostgreSQLDatabaseConfiguration] = None
enable_token_history: bool = False
class QuotaHandlersConfig(ConfigurationBase):
"""Quota limiter configuration."""
sqlite: Optional[SQLiteDatabaseConfiguration] = None
postgres: Optional[PostgreSQLDatabaseConfiguration] = None
enable_token_history: bool = False
🤖 Prompt for AI Agents
In src/models/config.py around lines 567 to 573, the field named `storage`
should be renamed to `postgres` to match existing naming patterns; change the
attribute to `postgres: Optional[PostgreSQLDatabaseConfiguration] = None`
(keeping the same type and default), update any imports/typing if necessary, and
then update all references across the codebase and tests (notably
tests/unit/models/config/test_dump_configuration.py at line 177) to use
`postgres` instead of `storage`.

@tisnik tisnik merged commit b70eba7 into lightspeed-core:main Oct 15, 2025
18 of 20 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.

1 participant