Repository navigation
feat(streaming): meter query prewhere - #3430
Conversation
📝 WalkthroughWalkthroughUpdate 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (5)
app/config/aggregation.go (1)
131-149: Set an explicit default for EnablePrewhereMake 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 filtersYou 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 nameDouble “with” in name.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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 goodLine 51’s move to
24.10-alpinekeeps the example stack aligned with the newly pinned version. LGTM.deploy/charts/openmeter/templates/clickhouse.yaml (1)
24-24: Helm chart image tag alignedLine 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 outLine 5’s bump to
24.10matches the image updates throughout the stack. Looks solid.openmeter/streaming/clickhouse/connector.go (2)
36-40: Config wiring for meter-query options looks correctPassing through
MeterQuerySettingsandEnablePrewhereat Lines 36‑40 gives the connector the knobs it needs without disturbing existing validation. Nicely done.
159-161: Query construction now receives the new togglesLines 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.10Line 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 completeLines 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 hookMeterQuerySettings aligns with ClickHouse SETTINGS usage and keeps insert/query settings separate. Looks good.
37-38: Prewhere toggle addition looks goodClear, 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 expansionBroad cases for aggregation, windows, subjects/customers/groups, PREWHERE, and settings. This will catch regressions.
aeb14f8 to
9f4ea1e
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
app/config/aggregation.go (1)
32-39: Expose safe defaults for new meter query optionsAdd 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
QuerySettingsfield: “Values must be valid ClickHouse literals (quote strings as needed).”
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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 injectionThis test still expects the query builder to inline
FilterGroupByvalues 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 intowantArgs, then updatequeryMeter.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 goodAdding
MeterQuerySettingsandEnablePrewhereto Config is consistent with the new query features.
159-161: Propagation LGTMPassing
MeterQuerySettingsandEnablePrewherethrough toqueryMeteris 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
QuerySettingsandEnablePrewhereare correctly scoped per-query.
101-123: Double-check window end semantics (inclusive vs. exclusive)
tumbleEndis 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 upgradeThe 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 releaseUpdating 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 imageDev tooling stays aligned with production after this version bump.
app/common/streaming.go (1)
38-40: New connector options are propagated correctlyPassing through
MeterQuerySettingsandEnablePrewheremakes the new query controls available without altering existing call sites.
| // 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) | ||
| } |
There was a problem hiding this comment.
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.
Summary by CodeRabbit