Skip to content

Support simple PromQL over-time reducers - #104486

Closed
BadLiveware wants to merge 27 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-simple-over-time
Closed

BadLiveware wants to merge 27 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-simple-over-time

Conversation

@BadLiveware

@BadLiveware BadLiveware commented May 9, 2026 •

Copy link
Copy Markdown

Expands ClickHouse TimeSeries native PromQL-to-SQL lowering for simple over-time reducers.

The implementation adds direct streaming aggregate support for sum_over_time, avg_over_time, min_over_time, max_over_time, count_over_time, stddev_over_time, stdvar_over_time, and present_over_time. It avoids the generic per-grid arrayFilter path and uses dedicated time-series aggregate functions while preserving empty-window behavior and metric-name dropping.

Split out from the integration draft #104271; shared base #104484.

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Added native PromQL-to-SQL lowering for simple over-time reducers over ClickHouse TimeSeries data, including sum_over_time, avg_over_time, min_over_time, max_over_time, count_over_time, stddev_over_time, stdvar_over_time, and present_over_time.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

BadLiveware added 13 commits May 9, 2026 13:52
Add the common PromQL compliance reporting and developer notes used by the follow-up TimeSeries PromQL lowering slices. Keep the parser compliance corpus expectation explicit for selectors Prometheus rejects.
Add focused Prometheus protocol tests for user-facing native lowering errors: unsupported-but-parseable functions and invalid date-function arity. These are semantic guardrails for clear errors, not broad coverage padding.
Add native PromQL lowering for the simple over-time reducers and route them directly through streaming time-series aggregate functions instead of the generic per-grid array filtering path. This covers sum, avg, min, max, count, stddev, stdvar, and present_over_time while preserving empty-window behavior and metric-name dropping.

Add direct aggregate coverage for Float32, state merge, and representative type/parameter errors alongside the Prometheus protocol evaluation cases.
Avoid fork-local wording in the PromQL review base. These are ClickHouse PromQL regression cases and evidence requirements, not fork-specific artifacts.
Avoid fork-local wording in the PromQL review base. These are ClickHouse PromQL regression cases and evidence requirements, not fork-specific artifacts.
Remove the standalone native histogram discovery Markdown note from the PromQL split branches.
Remove the standalone native histogram discovery Markdown note from the PromQL split branches.
Remove downstream promshim-specific evidence and non-goal language from the native PromQL lowering README so the note stays focused on ClickHouse review guidance.
Remove downstream promshim-specific evidence and non-goal language from the native PromQL lowering README so the note stays focused on ClickHouse review guidance.
Rewrite the native PromQL lowering notes around external SQL-transpiler measurements. Document measured and mixed SQL patterns with target PromQL shapes, pseudocode, and the ClickHouse-side validation expected for in-tree changes.
Rewrite the native PromQL lowering notes around external SQL-transpiler measurements. Document measured and mixed SQL patterns with target PromQL shapes, pseudocode, and the ClickHouse-side validation expected for in-tree changes.
Replace external corpus row names with concrete PromQL expressions and query-range context in the native PromQL lowering notes.
Replace external corpus row names with concrete PromQL expressions and query-range context in the native PromQL lowering notes.
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e421965]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_msan, WasmEdge, parallel, 1/2) FAIL
02875_parallel_replicas_remote FAIL cidb
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) FAIL
01548_query_log_query_execution_ms FAIL cidb

AI Review

Summary

This PR adds native PromQL lowering for simple over-time reducers and wires new timeSeries*OverTimeToGrid aggregate functions into the converter. Current HEAD still has one live correctness/safety issue: stale-window eviction in the new aggregate can signed-overflow on extreme but representable DateTime64 inputs, which can cause undefined behavior and incorrect sample eviction.

Findings

❌ Blockers

  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesSimpleOverTime.h:283] The check samples_in_window.front().first + Base::window <= current_timestamp performs signed addition before comparison. Near INT64_MAX, this overflows and can incorrectly drop samples from the active window.
    Suggested fix: perform this comparison with overflow-safe arithmetic (common::addOverflow-guarded addition or an equivalent unsigned-delta formulation), matching the overflow-safe approach already used around Base::timestampAtIndex(i).
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: make stale-window eviction overflow-safe in AggregateFunctionTimeseriesSimpleOverTime.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label May 10, 2026
Match Prometheus parser behavior by requiring vector selectors to contain at
least one matcher that cannot match an empty label value. This prevents broad
selectors like `{job=~".*"}` or `{__name__=~".*"}` from silently selecting every
metric when the user likely intended an explicit non-empty constraint.

Users who intentionally want all real metrics can still use `{__name__=~".+"}`,
and empty-matching label matchers remain valid when combined with that explicit
metric-name matcher.
Deduplicate expanded compliance cases by query text before checking the
`should_fail` expectation. A query listed once as expected success and once as
expected failure is now reported as conflicting metadata instead of slipping
through as two separate cases.
The nested aggregate function can canonicalize its parameter list during factory
creation. Wrap the nested function with that canonical parameter set instead of
the original parser parameters so the Array wrapper and nested aggregate keep the
same definition.
Mirror the upstream PromQL compliance corpus for label transformation invalid
label-name cases. These cases should remain should-fail entries so ClickHouse
acceptance of invalid destination labels stays visible as a rejection mismatch
rather than being counted as expected coverage.
The Array combinator now keeps the nested aggregate's canonical parameters, so
it no longer reads the original factory parameter list. Leave the argument
unnamed to satisfy warning-as-error builds while preserving the override
signature.
Move the simple over-time aggregate factory and documentation into a separate
translation unit so the shared time-series helpers file no longer carries those
template instantiations. Keep the common base header self-contained now that the
new translation unit includes the simple over-time aggregate directly.

Validation:
- cmake --build build_debug --target clickhouse
- build_debug/programs/clickhouse local --allow_experimental_time_series_aggregate_functions=1 -q "SELECT timeSeriesSumOverTimeToGrid(0, 10, 5, 5)(toUInt32(number), toFloat64(number)) FROM numbers(3)"
Some Prometheus builds format equivalent floating point results with different
shortest-roundtrip strings. The evaluation helper already accepts an epsilon for
ClickHouse SQL and HTTP comparisons, so use the same tolerance when comparing the
Prometheus reference response with the expected JSON.

Validation:
- python3 -m py_compile tests/integration/test_prometheus_protocols/test_evaluation.py tests/integration/test_prometheus_protocols/prometheus_test_utils.py
- imported `http_api_response_close_to` with stubbed optional modules and checked the `1.6875` vs `1.6875000000000002` matrix response passes with `eps=1e-9` and fails with `eps=0`
Use the shortest exact decimal for the `stdvar_over_time` expected JSON value,
matching the ClickHouse-side expected result. The tolerant comparison still
covers equivalent floating point formatting differences from Prometheus.
Compute the output grid timestamp through `timestampAtIndex` in `AggregateFunctionTimeseriesSimpleOverTime` so extreme `DateTime64` ranges avoid signed-overflow UB, matching the other `timeSeries*ToGrid` implementations.
}
}

while (!samples_in_window.empty() && samples_in_window.front().first + Base::window <= current_timestamp)

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.

This stale-sample eviction check can still signed-overflow on extreme DateTime64 inputs: samples_in_window.front().first + Base::window is evaluated in signed arithmetic before the comparison, so values near INT64_MAX trigger UB and may evict valid samples incorrectly.

We already fixed the neighboring current_timestamp overflow by switching to Base::timestampAtIndex(i); this condition needs the same treatment. Please rewrite the comparison in an overflow-safe form (for example with common::addOverflow, or via an unsigned-delta check) so representable boundary values are handled deterministically.

@vitlibar vitlibar self-assigned this May 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.20% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 92.33% (325/352) · Uncovered code

Full report · Diff report

@BadLiveware

Copy link
Copy Markdown
Author

Closing in favour of in review PR #101355

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

Labels

can be tested Allows running workflows for external contributors pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants