Skip to content

feat(streaming): meter query prewhere - #3430

Merged
hekike merged 1 commit into
mainfrom
feat/meter-query-prewhere
Sep 25, 2025
Merged

hekike merged 1 commit into
mainfrom
feat/meter-query-prewhere

Conversation

@hekike

@hekike hekike commented Sep 25, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Added configurable ClickHouse meter query settings.
    • Added optional PREWHERE optimization for meter queries to improve query performance.
  • Chores
    • Upgraded ClickHouse to 24.10 across pinned versions, Helm chart, Docker Compose, and example collector setups.

@hekike
hekike requested a review from tothandras September 25, 2025 17:33
@hekike
hekike requested a review from a team as a code owner September 25, 2025 17:33
@hekike hekike added area/processor release-note/feature Release note: Exciting New Features labels Sep 25, 2025
@coderabbitai

coderabbitai Bot commented Sep 25, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Update ClickHouse version pins and container images to 24.10. Add MeterQuerySettings and EnablePrewhere to aggregation config and connector config; propagate them through the streaming connector. Extend ClickHouse meter query construction to support PREWHERE and SETTINGS. Minor test refactor for named subtests.

Changes

Cohort / File(s) Summary
Version pinning
.dagger/versions_pinned.go
Update pinned ClickHouse version constant from "24.5.5.78" to "24.10".
Deployment images
deploy/charts/openmeter/templates/clickhouse.yaml, docker-compose.base.yaml, examples/collectors/database/docker-compose.yaml
Bump ClickHouse server image tags to 24.10 / 24.10-alpine across Helm chart and Docker Compose examples.
Config surface: aggregation
app/config/aggregation.go
Add MeterQuerySettings map[string]string and EnablePrewhere bool fields to AggregationConfiguration.
Config propagation: streaming
app/common/streaming.go
Pass MeterQuerySettings and EnablePrewhere into clickhouseconnector.Config when creating the streaming connector.
Connector config
openmeter/streaming/clickhouse/connector.go
Add MeterQuerySettings map[string]string and EnablePrewhere bool to connector Config and propagate them into meter query construction.
Query construction logic
openmeter/streaming/clickhouse/meter_query.go
Add QuerySettings map[string]string and EnablePrewhere bool to queryMeter; implement conditional PREWHERE placement and append SETTINGS from QuerySettings into generated SQL.
Tests
openmeter/streaming/clickhouse/meter_query_test.go
Add name field to table-driven tests and use t.Run() with descriptive subtest names; core assertions unchanged.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • (none referenced in this diff)

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title follows a clear conventional commit format and directly indicates the primary enhancement of adding prewhere support for meter queries in the streaming connector. It is concise, specific to the main feature introduced, and matches the central changes observed in configuration and SQL-building logic. A reviewer scanning the history would immediately understand the key improvement being merged.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/meter-query-prewhere

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

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

131-149: Set an explicit default for EnablePrewhere

Make the default visible in config to ease discoverability and operational consistency.

 func ConfigureAggregation(v *viper.Viper) {
   v.SetDefault("aggregation.eventsTableName", "om_events")
   v.SetDefault("aggregation.asyncInsert", false)
   v.SetDefault("aggregation.asyncInsertWait", false)
+  // Query construction defaults
+  v.SetDefault("aggregation.enablePrewhere", false)
 
   v.SetDefault("aggregation.clickhouse.address", "127.0.0.1:9000")
openmeter/streaming/clickhouse/meter_query_test.go (4)

16-22: Time precision mismatch (ms vs seconds)

from is parsed with millisecond precision (00:00:00.001Z) but assertions use from.Unix() (seconds), silently widening the range. Align the test to second precision or switch to UnixMilli throughout.

- from, _ := time.Parse(time.RFC3339, "2023-01-01T00:00:00.001Z")
+ from, _ := time.Parse(time.RFC3339, "2023-01-01T00:00:00Z")

378-380: Duplicate subject IN filters

You have "subject IN (?) AND subject IN (?)". Consider intersecting once to a single IN to simplify the query.


157-176: Nit: fix typos in test names

“groupped” → “grouped”.


466-487: Nit: fix typo in test name

Double “with” in name.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f3de627 and aeb14f8.

📒 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.base.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 (18 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
openmeter/streaming/clickhouse/meter_query_test.go (1)
openmeter/meter/meter.go (2)
  • Meter (139-148)
  • MeterAggregationSum (19-19)
⏰ 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). (7)
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Lint
  • GitHub Check: Migration Checks
  • GitHub Check: Build
  • GitHub Check: Code Generators
  • GitHub Check: Analyze (go)
🔇 Additional comments (11)
examples/collectors/database/docker-compose.yaml (1)

51-51: ClickHouse image bump looks good

Line 51’s move to 24.10-alpine keeps the example stack aligned with the newly pinned version. LGTM.

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

24-24: Helm chart image tag aligned

Line 24 mirrors the global ClickHouse upgrade to 24.10, keeping Helm deployments consistent. All good.

.dagger/versions_pinned.go (1)

5-5: Pinned version update checks out

Line 5’s bump to 24.10 matches the image updates throughout the stack. Looks solid.

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

36-40: Config wiring for meter-query options looks correct

Passing through MeterQuerySettings and EnablePrewhere at Lines 36‑40 gives the connector the knobs it needs without disturbing existing validation. Nicely done.


159-161: Query construction now receives the new toggles

Lines 159‑161 ensure the meter query builder sees the new settings. This keeps the data path consistent with the config additions.

docker-compose.base.yaml (1)

28-28: Base Compose aligns with ClickHouse 24.10

Line 28’s image tag bump harmonizes local dev with the rest of the ecosystem changes. LGTM.

app/common/streaming.go (1)

38-40: Config propagation is complete

Lines 38‑40 correctly forward the new meter-query controls into the connector, so runtime config stays authoritative. Looks good.

app/config/aggregation.go (2)

31-36: Good addition: explicit meter-query settings hook

MeterQuerySettings aligns with ClickHouse SETTINGS usage and keeps insert/query settings separate. Looks good.


37-38: Prewhere toggle addition looks good

Clear, opt-in switch for PREWHERE handling in meter queries.

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

307-309: Deterministic order for WITH map()

If subject_to_customer_id is built from a map, ensure stable ordering when rendering SQL to keep tests non-flaky (e.g., sort keys).


23-28: Nice coverage expansion

Broad cases for aggregation, windows, subjects/customers/groups, PREWHERE, and settings. This will catch regressions.

@hekike
hekike force-pushed the feat/meter-query-prewhere branch from aeb14f8 to 9f4ea1e Compare September 25, 2025 17:48
@hekike
hekike merged commit 5b8dab9 into main Sep 25, 2025
@hekike
hekike deleted the feat/meter-query-prewhere branch September 25, 2025 18:00

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (2)
app/config/aggregation.go (1)

32-39: Expose safe defaults for new meter query options

Add Viper defaults for the new fields so configs remain deterministic and nil-safe across environments.

 func ConfigureAggregation(v *viper.Viper) {
   v.SetDefault("aggregation.eventsTableName", "om_events")
   v.SetDefault("aggregation.asyncInsert", false)
   v.SetDefault("aggregation.asyncInsertWait", false)
+  // Meter query defaults
+  v.SetDefault("aggregation.enablePrewhere", false)
+  v.SetDefault("aggregation.meterQuerySettings", map[string]string{})
 
   v.SetDefault("aggregation.clickhouse.address", "127.0.0.1:9000")
openmeter/streaming/clickhouse/meter_query.go (1)

309-317: Deterministic and safe SETTINGS emission

  • Map iteration order is random; sort keys for deterministic SQL (important for tests and caching).
  • Clarify value quoting. Currently values are emitted raw; string settings must be pre-quoted (e.g., 'UTC'). Either document this or auto-quote if value lacks quotes and isn’t numeric/boolean.
-  for key, value := range d.QuerySettings {
-    settings = append(settings, fmt.Sprintf("%s = %s", key, value))
-  }
+  if len(d.QuerySettings) > 0 {
+    keys := make([]string, 0, len(d.QuerySettings))
+    for k := range d.QuerySettings {
+      keys = append(keys, k)
+    }
+    sort.Strings(keys)
+    for _, key := range keys {
+      value := d.QuerySettings[key]
+      settings = append(settings, fmt.Sprintf("%s = %s", key, value)) // value should be a valid CH literal
+    }
+  }

Optionally add a short comment near QuerySettings field: “Values must be valid ClickHouse literals (quote strings as needed).”

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aeb14f8 and 9f4ea1e.

📒 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.base.yaml (1 hunks)
  • examples/collectors/database/docker-compose.yaml (1 hunks)
  • openmeter/streaming/clickhouse/connector.go (2 hunks)
  • openmeter/streaming/clickhouse/meter_query.go (5 hunks)
  • openmeter/streaming/clickhouse/meter_query_test.go (18 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/collectors/database/docker-compose.yaml
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-03-07T12:17:43.129Z
Learnt from: GAlexIHU
PR: openmeterio/openmeter#2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like `openmeter/entitlement/metered/lateevents_test.go` may use variables like `meterSlug` and `namespace` without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.

Applied to files:

  • openmeter/streaming/clickhouse/meter_query_test.go
🧬 Code graph analysis (1)
openmeter/streaming/clickhouse/meter_query_test.go (1)
openmeter/meter/meter.go (1)
  • Meter (139-148)
⏰ 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). (7)
  • GitHub Check: Lint
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Code Generators
  • GitHub Check: Migration Checks
  • GitHub Check: Build
  • GitHub Check: Test
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
openmeter/streaming/clickhouse/meter_query_test.go (1)

484-486: Still interpolating group filter literals exposes SQL injection

This test still expects the query builder to inline FilterGroupBy values directly into the SQL text. These values ultimately come from user input, so emitting them as 'g1v1'/'g1v2'/… keeps the injection vector wide open—exactly what we flagged in the earlier review. The fix is to parameterize every JSON_VALUE comparison and push the corresponding values into wantArgs, then update queryMeter.toSQL() to bind those parameters instead of concatenating literals.

-			wantSQL:  "SELECT tumbleStart(min(om_events.time), toIntervalMinute(1)) AS windowstart, tumbleEnd(max(om_events.time), toIntervalMinute(1)) AS windowend, sum(ifNotFinite(toFloat64OrNull(JSON_VALUE(om_events.data, '$.value')), null)) AS value FROM openmeter.om_events PREWHERE om_events.namespace = ? AND om_events.type = ? WHERE (JSON_VALUE(om_events.data, '$.group1') = 'g1v1' OR JSON_VALUE(om_events.data, '$.group1') = 'g1v2') AND (JSON_VALUE(om_events.data, '$.group2') = 'g2v1' OR JSON_VALUE(om_events.data, '$.group2') = 'g2v2') SETTINGS optimize_move_to_prewhere = 1, allow_reorder_prewhere_conditions = 1",
-			wantArgs: []interface{}{"my_namespace", "event1"},
+			wantSQL:  "SELECT tumbleStart(min(om_events.time), toIntervalMinute(1)) AS windowstart, tumbleEnd(max(om_events.time), toIntervalMinute(1)) AS windowend, sum(ifNotFinite(toFloat64OrNull(JSON_VALUE(om_events.data, '$.value')), null)) AS value FROM openmeter.om_events PREWHERE om_events.namespace = ? AND om_events.type = ? WHERE (JSON_VALUE(om_events.data, '$.group1') = ? OR JSON_VALUE(om_events.data, '$.group1') = ?) AND (JSON_VALUE(om_events.data, '$.group2') = ? OR JSON_VALUE(om_events.data, '$.group2') = ?) SETTINGS optimize_move_to_prewhere = 1, allow_reorder_prewhere_conditions = 1",
+			wantArgs: []interface{}{"my_namespace", "event1", "g1v1", "g1v2", "g2v1", "g2v2"},

Please apply the same parameterization pattern to every group-filter test case so the builder never concatenates user strings into SQL.

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

36-40: Config surface extension looks good

Adding MeterQuerySettings and EnablePrewhere to Config is consistent with the new query features.


159-161: Propagation LGTM

Passing MeterQuerySettings and EnablePrewhere through to queryMeter is correct.

Please confirm that settings values are expected as raw ClickHouse literals (e.g., 1, 0, 10, 'UTC'). If strings must be quoted, add a brief comment to the struct or enforce quoting at build time (see related comment in meter_query.go).

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

35-37: New fields on query struct are appropriate

QuerySettings and EnablePrewhere are correctly scoped per-query.


101-123: Double-check window end semantics (inclusive vs. exclusive)

tumbleEnd is used without adding the interval (minute/hour/day). If your expected window model is [start, end) (common for reporting) or you want the end to be the start of the next bucket, you may need + INTERVAL 1 <unit> like in the earlier review. Please confirm desired semantics and make it consistent for all granularities and for the no-window branch.

If you confirm [start, end) is desired, apply:

-                fmt.Sprintf("tumbleEnd(%s, toIntervalMinute(1), '%s') AS windowend", timeColumn, tz),
+                fmt.Sprintf("tumbleEnd(%s, toIntervalMinute(1), '%s') + INTERVAL 1 MINUTE AS windowend", timeColumn, tz),
...
-                fmt.Sprintf("tumbleEnd(%s, toIntervalHour(1), '%s') AS windowend", timeColumn, tz),
+                fmt.Sprintf("tumbleEnd(%s, toIntervalHour(1), '%s') + INTERVAL 1 HOUR AS windowend", timeColumn, tz),
...
-                fmt.Sprintf("tumbleEnd(%s, toIntervalDay(1), '%s') AS windowend", timeColumn, tz),
+                fmt.Sprintf("tumbleEnd(%s, toIntervalDay(1), '%s') + INTERVAL 1 DAY AS windowend", timeColumn, tz),
...
-        selectColumn := fmt.Sprintf("tumbleStart(min(%s), toIntervalMinute(1)) AS windowstart, tumbleEnd(max(%s), toIntervalMinute(1)) AS windowend", timeColumn, timeColumn)
+        selectColumn := fmt.Sprintf("tumbleStart(min(%s), toIntervalMinute(1)) AS windowstart, tumbleEnd(max(%s), toIntervalMinute(1)) + INTERVAL 1 MINUTE AS windowend", timeColumn, timeColumn)

Also applies to: 150-157

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

24-24: Chart image bump aligns with the repo-wide ClickHouse upgrade

The operator manifest now points at 24.10, matching the other deployment surfaces.

.dagger/versions_pinned.go (1)

5-5: Pinned toolchain tracks the new ClickHouse release

Updating the dagger constant keeps local pipelines in sync with the 24.10 rollout.

docker-compose.base.yaml (1)

28-28: Compose environment follows the same 24.10-alpine image

Dev tooling stays aligned with production after this version bump.

app/common/streaming.go (1)

38-40: New connector options are propagated correctly

Passing through MeterQuerySettings and EnablePrewhere makes the new query controls available without altering existing call sites.

Comment on lines +293 to +307
// Move wheres to prewhere if enabled and there are non prewhere filters
if d.EnablePrewhere && sqlBeforeApplyingDataWheres != "" {
settings = append(settings, "optimize_move_to_prewhere = 1")
settings = append(settings, "allow_reorder_prewhere_conditions = 1")

sqlParts := strings.Split(sql, sqlBeforeApplyingDataWheres)
sqlAfter := sqlParts[1]

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid potential panic on string split and make PREWHERE rewrite robust

strings.Split(...)[1] will panic if the prefix isn’t found, and the current replace targets bare "WHERE". Use strings.Cut, guard the case, and replace the token with surrounding spaces to avoid accidental matches.

-    sqlParts := strings.Split(sql, sqlBeforeApplyingDataWheres)
-    sqlAfter := sqlParts[1]
-
-    if strings.HasPrefix(sqlAfter, " AND") {
-      sqlAfter = strings.Replace(sqlAfter, "AND", "WHERE", 1)
-    }
-
-    sqlBeforeApplyingDataWheres = strings.Replace(sqlBeforeApplyingDataWheres, "WHERE", "PREWHERE", 1)
-    sql = fmt.Sprintf("%s%s", sqlBeforeApplyingDataWheres, sqlAfter)
+    _, sqlAfter, found := strings.Cut(sql, sqlBeforeApplyingDataWheres)
+    if found {
+      if strings.HasPrefix(sqlAfter, " AND ") {
+        sqlAfter = " WHERE " + strings.TrimPrefix(sqlAfter, " AND ")
+      }
+      prewherePrefix := strings.Replace(sqlBeforeApplyingDataWheres, " WHERE ", " PREWHERE ", 1)
+      sql = prewherePrefix + sqlAfter
+    }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In openmeter/streaming/clickhouse/meter_query.go around lines 293 to 307, avoid
a possible panic from strings.Split(...)[1] and make the PREWHERE rewrite
robust: use strings.Cut(sql, sqlBeforeApplyingDataWheres) and check the boolean
"found" before proceeding; if not found skip the rewrite. When adjusting the
trailing part, handle a leading " AND" by trimming the prefix and prefixing
"WHERE " (rather than replacing bare "AND"), and when converting the original
WHERE to PREWHERE replace only the token with surrounding spaces (e.g. replace "
WHERE " with " PREWHERE ") and only the first occurrence to avoid accidental
matches. Ensure you only append the prewhere-related settings and recompose sql
when the cut succeeds.

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

Labels

area/processor release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants