Skip to content

Conversation

tothandras
Copy link
Contributor

@tothandras tothandras commented Jun 23, 2025

Rebased #2974

Summary by CodeRabbit

  • New Features

    • Added support for custom query settings for meter queries, allowing advanced configuration and optimization of ClickHouse queries.
  • Improvements

    • Enhanced SQL query construction for meter queries, including optimized time window calculations and improved filtering performance.
    • Updated default ClickHouse server versions in deployment and example configurations for improved compatibility and performance.
  • Bug Fixes

    • Adjusted placement of filtering conditions in SQL queries to improve efficiency and correctness.
  • Tests

    • Updated test cases to reflect new SQL query structure and settings.

@tothandras tothandras requested a review from hekike June 23, 2025 14:05
@tothandras tothandras requested a review from a team as a code owner June 23, 2025 14:05
Copy link
Contributor

coderabbitai bot commented Jun 23, 2025

📝 Walkthrough

Walkthrough

The changes introduce support for custom query settings for meter queries in the ClickHouse connector by extending configuration structures and updating SQL query construction. Additionally, ClickHouse image versions are updated across deployment and development configurations. Unit tests are adjusted to reflect the revised SQL generation logic, including prewhere clause optimization and new settings.

Changes

Files/Paths Change Summary
.dagger/versions_pinned.go
deploy/charts/openmeter/templates/clickhouse.yaml
docker-compose.yaml
examples/collectors/database/docker-compose.yaml
Updated ClickHouse version strings/tags in pinned versions, Helm chart, and Docker Compose files.
app/config/aggregation.go
openmeter/streaming/clickhouse/connector.go
Added MeterQuerySettings map[string]string field to configuration structs for meter-specific query settings.
app/common/streaming.go Passed MeterQuerySettings to ClickHouse streaming connector initialization.
openmeter/streaming/clickhouse/meter_query.go Enhanced SQL construction: added QuerySettings to queryMeter, optimized prewhere clauses, and appended SETTINGS clause.
openmeter/streaming/clickhouse/meter_query_test.go Updated test expectations for SQL queries to match new window logic, prewhere handling, and SETTINGS clause.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@tothandras tothandras added the release-note/feature Release note: Exciting New Features label Jun 23, 2025
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: 2

🧹 Nitpick comments (2)
app/config/aggregation.go (1)

31-34: Add default for new MeterQuerySettings.

You introduced MeterQuerySettings in the struct but didn't add a default in ConfigureAggregation. Consider adding:

 func ConfigureAggregation(v *viper.Viper) {
   // existing defaults...
   v.SetDefault("aggregation.clickhouse.blockBufferSize", 10)
+  // Default settings for meter queries
+  v.SetDefault("aggregation.meterQuerySettings", map[string]string{})
 }
openmeter/streaming/clickhouse/connector.go (1)

173-173: Consider validating MeterQuerySettings.

The QuerySettings are passed directly without validation. Invalid ClickHouse settings could cause query failures at runtime.

Consider adding validation for the query settings to catch configuration errors early. You could validate against a whitelist of known ClickHouse settings or at least ensure the values don't contain SQL injection risks.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5334011 and 7cddba5.

📒 Files selected for processing (9)
  • .dagger/versions_pinned.go (1 hunks)
  • app/common/streaming.go (1 hunks)
  • app/config/aggregation.go (1 hunks)
  • deploy/charts/openmeter/templates/clickhouse.yaml (1 hunks)
  • docker-compose.yaml (1 hunks)
  • examples/collectors/database/docker-compose.yaml (1 hunks)
  • openmeter/streaming/clickhouse/connector.go (2 hunks)
  • openmeter/streaming/clickhouse/meter_query.go (6 hunks)
  • openmeter/streaming/clickhouse/meter_query_test.go (14 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Commit hooks
  • GitHub Check: E2E
  • GitHub Check: Quickstart
  • GitHub Check: CI
  • GitHub Check: Developer environment
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
.dagger/versions_pinned.go (1)

5-6: Bump ClickHouse version to align with other configurations.

The ClickHouse version constant has been updated from "24.5.5.78" to "24.10", matching the image tags in deployment and Docker Compose files.

deploy/charts/openmeter/templates/clickhouse.yaml (1)

24-24: Confirm use of non-alpine ClickHouse image.

The chart now pins clickhouse-server:24.10, whereas Docker Compose uses the alpine variant. This is acceptable if deliberate, but please verify that the standard image is intended here (vs. 24.10-alpine).

examples/collectors/database/docker-compose.yaml (1)

51-51: Inconsistent ClickHouse image version compared to main Docker Compose.

This example uses 24.0-alpine, while the main docker-compose.yaml and other configurations use 24.10-alpine. Please confirm whether this discrepancy is intentional or if it should be aligned.

docker-compose.yaml (1)

30-30: Align ClickHouse image tag with pinned version.

The service now uses clickhouse-server:24.10-alpine, matching the pinned version constant. Ensure this matches your production requirements.

app/common/streaming.go (1)

38-38: LGTM!

The MeterQuerySettings field is correctly propagated from the aggregation configuration to the ClickHouse connector configuration.

openmeter/streaming/clickhouse/connector.go (1)

37-37: LGTM!

The MeterQuerySettings field is correctly added to the Config struct to support custom ClickHouse query settings.

openmeter/streaming/clickhouse/meter_query_test.go (1)

46-46: Test updates correctly reflect the new query generation logic.

All test cases have been properly updated to expect:

  • The new SETTINGS clause with PREWHERE optimization flags
  • Updated window calculations using toStartOfMinute for non-windowed queries
  • PREWHERE clauses for filtered queries

Also applies to: 65-65, 83-83, 102-102, 122-122, 143-143, 165-165, 188-188, 209-209, 230-230, 251-251, 271-271, 291-291, 311-311

openmeter/streaming/clickhouse/meter_query.go (2)

8-8: LGTM!

The addition of the strings import and QuerySettings field enables custom ClickHouse query settings.

Also applies to: 30-30


155-155: Verify the impact of window calculation change.

The window calculation for non-windowed queries has changed from using tumbleStart/tumbleEnd to toStartOfMinute(min/max). This is a breaking change that affects the window boundaries returned by queries.

Please ensure that:

  1. This change is intentional and documented
  2. API consumers are aware of this behavioral change
  3. The minute-level rounding is acceptable for all use cases

Comment on lines +279 to +291
// Only add prewhere if there are filters on JSON data
if sqlPreWhere != "" {
sqlParts := strings.Split(sql, sqlPreWhere)
sqlAfter := sqlParts[1]

if strings.HasPrefix(sqlAfter, " AND") {
sqlAfter = strings.Replace(sqlAfter, "AND", "WHERE", 1)
}

sqlPreWhere = strings.Replace(sqlPreWhere, "WHERE", "PREWHERE", 1)
sql = fmt.Sprintf("%s%s", sqlPreWhere, sqlAfter)
}

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Refactor the fragile string manipulation for PREWHERE clause.

The current approach using string splitting and replacement is error-prone and could break if the query structure changes. This makes the code difficult to maintain.

Consider using a more robust approach:

  1. Build PREWHERE and WHERE clauses separately using the query builder
  2. Use a custom SQL builder that supports PREWHERE natively
  3. Or at minimum, use more robust string manipulation with proper parsing

Example approach:

// Build PREWHERE conditions separately
prewhereBuilder := sqlbuilder.ClickHouse.NewSelectBuilder()
prewhereConditions := []string{
    prewhereBuilder.Equal(getColumn("namespace"), d.Namespace),
    prewhereBuilder.Equal(getColumn("type"), d.Meter.EventType),
}

// Build WHERE conditions for filters
whereConditions := []string{}
// ... add filter conditions to whereConditions

// Construct the final query with both PREWHERE and WHERE
🤖 Prompt for AI Agents
In openmeter/streaming/clickhouse/meter_query.go around lines 279 to 291, the
current string manipulation to insert the PREWHERE clause by splitting and
replacing parts of the SQL query is fragile and error-prone. To fix this,
refactor the code to build PREWHERE and WHERE clauses separately using a query
builder that supports PREWHERE natively or at least construct the conditions as
separate lists before combining them. Avoid direct string splitting and
replacements; instead, assemble the final query by explicitly adding PREWHERE
conditions first and then WHERE conditions to ensure correctness and
maintainability.

Comment on lines +297 to +302
for key, value := range d.QuerySettings {
settings = append(settings, fmt.Sprintf("%s = %s", key, value))
}

sql = sql + fmt.Sprintf(" SETTINGS %s", strings.Join(settings, ", "))

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

Add validation for QuerySettings to prevent SQL injection.

The QuerySettings map values are directly interpolated into the SQL query without any validation or escaping, which could lead to SQL injection vulnerabilities if these settings come from untrusted sources.

Apply this diff to add basic validation:

+// Validate query settings to prevent SQL injection
+for key, value := range d.QuerySettings {
+    // Validate key contains only alphanumeric and underscore
+    if !regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(key) {
+        return "", nil, fmt.Errorf("invalid query setting key: %s", key)
+    }
+    // Validate value contains only safe characters
+    if !regexp.MustCompile(`^[a-zA-Z0-9_\s,=.]+$`).MatchString(value) {
+        return "", nil, fmt.Errorf("invalid query setting value for %s: %s", key, value)
+    }
+}

 // Add settings
 settings := []string{
     "optimize_move_to_prewhere = 1",
     "allow_reorder_prewhere_conditions = 1",
 }
 for key, value := range d.QuerySettings {
     settings = append(settings, fmt.Sprintf("%s = %s", key, value))
 }

Alternatively, consider using a whitelist of allowed ClickHouse settings.

📝 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
for key, value := range d.QuerySettings {
settings = append(settings, fmt.Sprintf("%s = %s", key, value))
}
sql = sql + fmt.Sprintf(" SETTINGS %s", strings.Join(settings, ", "))
// Validate query settings to prevent SQL injection
for key, value := range d.QuerySettings {
// Validate key contains only alphanumeric and underscore
if !regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(key) {
return "", nil, fmt.Errorf("invalid query setting key: %s", key)
}
// Validate value contains only safe characters
if !regexp.MustCompile(`^[a-zA-Z0-9_\s,=.]+$`).MatchString(value) {
return "", nil, fmt.Errorf("invalid query setting value for %s: %s", key, value)
}
}
for key, value := range d.QuerySettings {
settings = append(settings, fmt.Sprintf("%s = %s", key, value))
}
sql = sql + fmt.Sprintf(" SETTINGS %s", strings.Join(settings, ", "))
🤖 Prompt for AI Agents
In openmeter/streaming/clickhouse/meter_query.go around lines 297 to 302, the
QuerySettings map values are directly inserted into the SQL query without
validation, risking SQL injection. To fix this, add validation to ensure each
key and value conforms to expected patterns or use a whitelist of allowed
settings before appending them to the query. Reject or sanitize any entries that
do not meet these criteria to prevent injection vulnerabilities.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants