Skip to content

Implement PromQL functions max_over_time() and min_over_time() - #112354

Merged
vitlibar merged 2 commits into
ClickHouse:masterfrom
valerypetrov:promql/max-min-over-time
Sep 9, 2026
Merged

vitlibar merged 2 commits into
ClickHouse:masterfrom
valerypetrov:promql/max-min-over-time

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Related: #57545

Changelog category (leave one):

  • Experimental Feature

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

PromQL: implemented functions max_over_time() and min_over_time().

Description

Implements max_over_time(v range-vector) and min_over_time(v range-vector), previously reported as not implemented.

Unlike sum/count, max/min are not invertible monoids, but they are commutative and associative (merge = max(a, b)/min(a, b)), so the new header (AggregateFunctionTimeseriesExtremumOverTime.h, templated on a bool is_max_) reuses AggregateFunctionTimeseriesSlidingSum's existing non-invertible sliding-window fallback (the same two-stacks/recompute machinery already shipped and tested via deriv/predict_linear) — no new windowing logic was needed. Bucket == Summary directly, following AggregateFunctionTimeseriesToGridSparse's (last_over_time's) simplest-case shape, since max/min don't depend on sample order. The comparison is NaN-aware (candidate > current || isnan(current)), matching Prometheus's own "a NaN currently held as the running extremum is unconditionally overwritten by the next sample" semantics.

Registered timeSeriesMaxToGrid/timeSeriesMinToGrid in AggregateFunctionTimeseriesHelpers.cpp and added the two impl_map entries in applyFunctionOverRange.cpp with drop_metric_name = true, matching rate/increase/delta's convention.

Verified against Prometheus 3.5.0.

Testing: new SQL-level test (04628_max_min_over_time_timeseries_functions.sql) including an AggregatingMergeTree serialize/deserialize/merge round-trip, plus cases in tests/integration/test_prometheus_protocols/test_evaluation.py covering both functions over a series with decreases (so results differ meaningfully from last_over_time), including a more complex nested query. This flips 13 queries of the PromQL compliance suite from unsupported to passed.


Workflow [PR]
Sync PR [sync-upstream/pr/112354]

Version info

  • Merged into: 26.9.1.1018 (included in 26.9 and later)

@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Jul 28, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [108d3ae]

Summary: ✅


AI Review

Summary

This PR adds PromQL support for max_over_time, min_over_time, ts_of_max_over_time, and ts_of_min_over_time, including new timeSeries*ToGrid aggregates, parser wiring, structured docs, and end-to-end tests. The main range-function plumbing looks complete, but timeSeriesMaxToGrid still has an order-dependent equal-timestamp merge path, so I would not merge this as-is.

PR Metadata
  • Changelog category: Experimental Feature matches the current surface.
  • Changelog entry: required and currently incomplete, because the diff also adds ts_of_max_over_time and ts_of_min_over_time. Suggested replacement: PromQL: implemented functions max_over_time(), min_over_time(), ts_of_max_over_time(), and ts_of_min_over_time().
Missing context / blind spots
  • ⚠️ On 2026-09-08 the only available Praktika report is Build profile diff; full stateless and integration CI results are not available yet.
Findings

❌ Blockers

  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesMax.h:60-84] Equal-timestamp samples are still collapsed through timeseriesMaxValueForDuplicateTimestamp, which is not bitwise commutative for -0.0 / +0.0 or distinct NaN payloads. mergeImpl combines bucket states in arbitrary hash-map order, so timeSeriesMaxToGridMerge and parallel aggregation can return different raw bits for the same duplicate-timestamp input depending on state-partition order. Suggested fix: apply a canonical total order for the equal-timestamp path instead of delegating to std::max / “take rhs NaN”.
Tests
  • ⚠️ Add a focused stateless regression that drives duplicate same-timestamp -0.0 / +0.0 (and ideally distinct NaN payloads via reinterpretAsFloat64) through timeSeriesMaxToGrid and timeSeriesMaxToGridMerge, so the merge-order tie-break is pinned.
Final Verdict

Changes requested. The equal-timestamp merge path in timeSeriesMaxToGrid is still order-dependent, and the PR metadata should describe the full four-function surface being added.

LLVM Coverage Report

Measured on commit 108d3ae.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 478/482 (99.17%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 28, 2026
@valerypetrov
valerypetrov force-pushed the promql/max-min-over-time branch from 08c61c0 to 8977fc9 Compare July 29, 2026 00:03
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.30% -0.10%
Functions 91.90% 91.80% -0.10%
Branches 78.50% 78.40% -0.10%

Changed lines: Changed C/C++ lines covered: 209/213 (98.12%) · Uncovered code

Full report · Diff report

@vitlibar vitlibar self-assigned this Aug 4, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 108d3aebd with master a63831d1f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

7 object files changed (+2.04 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/TimeSeries/AggregateFunctionTi… 6.45 MiB 8.43 MiB +1.98 MiB (+30.80%)
src/Examples/CMakeFiles/clickhouse-examples.dir/__/AggregateFunctions/examples/timeseries_to_grid_t… 81.19 KiB 132.89 KiB +51.70 KiB (+63.68%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

14 translation units recompiled, 61 s compile time in total, 14 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +12.1 s (+25%) in total before that adjustment.

Translation unit Master PR Δ vs median
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesHelpers.cpp 26.2 s 37.3 s +9.7 s (+35%)

Slowest changed entities of src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesHelpers.cpp:

  • InstantiateFunction DB::(anonymous namespace)::createAggregateFunctionTimeseries<(lambda at /ClickHouse/src/AggregateFu…: +0.9 s
  • InstantiateFunction DB::(anonymous namespace)::createWithTimestampAndValueTypes<(lambda at /ClickHouse/src/AggregateFun…: +0.8 s
  • InstantiateFunction DB::(anonymous namespace)::createAggregateFunctionTimeseries<(lambda at /ClickHouse/src/AggregateFu…: -0.9 s (-100%)
  • InstantiateFunction DB::(anonymous namespace)::createWithTimestampAndValueTypes<(lambda at /ClickHouse/src/AggregateFun…: -0.8 s (-100%)
  • InstantiateFunction DB::(anonymous namespace)::createAggregateFunctionTimeseries<(lambda at /ClickHouse/src/AggregateFu…: +0.6 s
  • InstantiateFunction DB::(anonymous namespace)::createWithTimestampAndValueTypes<(lambda at /ClickHouse/src/AggregateFun…: +0.6 s
  • InstantiateFunction DB::(anonymous namespace)::createAggregateFunctionTimeseries<(lambda at /ClickHouse/src/AggregateFu…: +0.6 s
  • InstantiateFunction DB::(anonymous namespace)::createWithTimestampAndValueTypes<(lambda at /ClickHouse/src/AggregateFun…: +0.6 s

Job report

@valerypetrov

Copy link
Copy Markdown
Contributor Author

Update on the duplicate-timestamp thread:

Duplicate-timestamp samples now collapse to the greatest value before the over-time extremum — Bucket was switched to AggregateFunctionTimeseriesSamples, mirroring LinearRegression/ExtrapolatedValue, on both add and merge. The same-timestamp tie-break in timeseriesMaxValueForDuplicateTimestamp is now a strict total order over raw bits (1266344, 746643e).

Regressions in 04628 pin (100,1),(100,2) → 2 for both max and min, plus the merge path.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Dear @vitlibar, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@vitlibar vitlibar self-assigned this Sep 7, 2026
valerypetrov and others added 2 commits September 8, 2026 20:46
…raits for the maximum and the minimum.

Implement PromQL functions ts_of_max_over_time and ts_of_min_over_time.
@vitlibar
vitlibar force-pushed the promql/max-min-over-time branch from 8b5ffaa to 108d3ae Compare September 8, 2026 21:39
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Sep 8, 2026
/* drop_metric_name = */ true,
}},

{"ts_of_max_over_time",

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 hunk also exposes ts_of_max_over_time and ts_of_min_over_time, but the PR title, description, and changelog entry still only mention max_over_time and min_over_time. Please update the PR metadata so the contract, backport surface, and changelog cover all four user-visible PromQL functions added here.

@vitlibar

vitlibar commented Sep 8, 2026

Copy link
Copy Markdown
Member

I improved the solution in this PR, my changes:

  • Added aggregate functions timeSeriesTimestampOfMaxToGrid and timeSeriesTimestampOfMinToGrid, which implement the PromQL functions ts_of_max_over_time and ts_of_min_over_time to them
  • Splitted AggregateFunctionTimeseriesExtremumOverTime into separate traits for the maximum and the minimum. The maximum keeps a preaggregated summary per bucket, because the duplicate-timestamp rule keeps the greatest value anyway. The minimum keeps raw samples, because that rule may raise the minimum after the fact.
  • Simplified timeseriesMaxValueForDuplicateTimestamp: dropped the raw-bit tie-break, now a NaN loses to any real value and otherwise std::max decides.

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master a63831d1f

Metric Baseline Current Δ
Score 81.82% 84.23% +2.41%
Passed 441 454 +13
Failed 3 3 +0
Unsupported 95 82 -13

Uploaded compliance JSON for this PR commit

Baseline update

This run reports 84.23% vs master baseline 81.82% (a63831d1f). Merging to master will publish a new S3 object from the integration job that runs test_promql_compliance, which becomes the baseline for later PRs.

@vitlibar
vitlibar added this pull request to the merge queue Sep 9, 2026
Merged via the queue into ClickHouse:master with commit 5805a6b Sep 9, 2026
174 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 9, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@valerypetrov @vitlibar — title/description suggestions:

Description (currently misleading):

  • Why: The body describes code that was not shipped. It claims a single new header AggregateFunctionTimeseriesExtremumOverTime.h templated on bool is_max_; the diff ships AggregateFunctionTimeseriesMax.h and AggregateFunctionTimeseriesMin.h, each templated on bool return_timestamp_. It claims Bucket == Summary directly for both, since max/min don't depend on sample order -- but only Max does that; Min uses Bucket = Samples (AggregateFunctionTimeseriesMin.h:134) precisely because sample order does matter under the duplicate-timestamp rule, as that header's own comment explains. It names the test as 04628_max_min_over_time_timeseries_functions.sql, which is not in the diff (shipped: 05141_... and 05142_...). And it never mentions ts_of_max_over_time/ts_of_min_over_time or the ResultType change to the shared base, so a reviewer reading the body would not know why the ANTLR lexer and five unrelated traits headers are touched.

  • Suggested addition:

    Update the Description to match what shipped:

    • Four PromQL functions, not two: max_over_time, min_over_time, ts_of_max_over_time, ts_of_min_over_time. The last two required two new FUNCTION alternatives in contrib/antlr4-grammars/promql/PromQLLexer.g4 and the regenerated lexer.
    • Two headers, not one: AggregateFunctionTimeseriesMax.h and AggregateFunctionTimeseriesMin.h, each templated on bool return_timestamp_ so one traits class serves both the value and the ts_of_* variant.
    • The bucket shapes differ on purpose. Max stores a preaggregated Summary (max-of-dedup == max-of-raw, so collapsing duplicates cannot change the answer). Min stores raw Samples, because the duplicate-timestamp rule keeps the greatest value at a timestamp and can raise the minimum: for (1,1),(2,3),(1,5) the deduplicated minimum is 3@2, which a running minimum that already took 1@1 cannot recover.
    • AggregateFunctionTimeseriesBase gains Traits::ResultType, splitting the input-value column type (ColVecValueType) from the result column type (ColVecResultType) so ts_of_* can return Float64 seconds regardless of the value type. Every traits header in the family declares it; that is why five otherwise-untouched headers appear in the diff.
    • Tests: 05141_max_min_over_time_timeseries_functions.sql, 05142_timeseries_timestamp_of_min_max_functions.sql, new cases in 04319_timeseries_two_stacks.sql, and four PromQL cases in test_evaluation.py.

Ignore if intentional.

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 comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... manual approve Manual approve required to run CI pr-experimental Experimental Feature pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants