Skip to content

Implement PromQL functions clamp(), clamp_min(), clamp_max() and round() - #111870

Merged
nikitamikhaylov merged 26 commits into
ClickHouse:masterfrom
valerypetrov:promql/clamp-round
Aug 17, 2026
Merged

nikitamikhaylov merged 26 commits into
ClickHouse:masterfrom
valerypetrov:promql/clamp-round

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Jul 25, 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 clamp, clamp_min, clamp_max, and round.

Description

Implements four PromQL functions previously reported as not implemented:

  • clamp(v, min, max), clamp_min(v, min), clamp_max(v, max) — new applyClampFunction converter mapping to greatest/least SQL with explicit guards, because vectorized least/greatest in ClickHouse treat NaN as the largest value and ignore NULLs, which would corrupt NaN sample values and missing points. Prometheus special cases are reproduced exactly: min > max returns an empty vector, and a NaN bound propagates NaN.
  • round(v[, to_nearest]) — new applyRoundFunction converter; replicates Prometheus inverse arithmetic (floor(v * (1/to_nearest) + 0.5) / (1/to_nearest)), including ties rounding toward +Inf and NaN propagation for to_nearest = 0 or NaN.

Both drop the metric name from results, matching Prometheus. Non-constant scalar bounds (for example, clamp(v, time()*0-1, 2)) are supported. No parser changes were needed; arity is enforced by each converter.

The embedded support matrices for prometheusQuery and prometheusQueryRange list the new math functions and retain the implemented range functions increase, changes, and resets.

Semantics verified against Prometheus 3.5.0 for bound combinations (0, 1), (0, 1e12), (1e12, 0), (1e12, 1e12), and fractional to_nearest.

Testing: adds test_clamp and test_round, plus conversion and aggregation regressions for empty scalar handling and a runtime scalar quantile parameter outside [0, 1].

Version info

  • Merged into: 26.8.1.1566 (included in 26.8 and later)

clamp(v, min, max) is translated to greatest(min, least(max, v)) with
extra checks reproducing Prometheus semantics: NaN values and NaN bounds
propagate to the result (vectorized least()/greatest() don't guarantee
that), and clamp() returns an empty vector if max < min (constant bounds
are checked during conversion, non-constant bounds in the SQL expression).

round(v, to_nearest) replicates Prometheus arithmetic exactly:
floor(v * inv + 0.5) / inv with inv = 1 / to_nearest, so ties are
rounded up and results match Prometheus bit for bit.
@nikitamikhaylov nikitamikhaylov added can be tested Allows running workflows for external contributors comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... labels Jul 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20c9703]

Summary: ✅


AI Review

Summary

This PR adds PromQL clamp, clamp_min, clamp_max, and round, plus the follow-up fixes around scalar/quantile edge cases that came up during review. The converter logic and regression coverage look good overall, but the published prometheusQuery* reference pages are still stale and still understate the supported math surface.

Findings

⚠️ Majors

  • [docs/reference/functions/table-functions/prometheusQuery.mdx:49, docs/reference/functions/table-functions/prometheusQueryRange.mdx:51] The public Supported PromQL Features tables still stop the Math row at deg, even though the source registration already advertises round, clamp, clamp_min, and clamp_max in src/TableFunctions/TableFunctionTimeSeries.cpp and src/TableFunctions/TableFunctionTimeSeries.cpp. After merge, users reading the committed Mintlify pages will still be told those functions are unsupported.
    Suggested fix: regenerate the prometheusQuery and prometheusQueryRange reference pages from the updated FunctionDocumentation source so the published docs match the implementation.
Final Verdict

Changes are close, but the stale generated prometheusQuery* docs should be regenerated before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 134/157 (85.35%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 25, 2026
When clamp() bounds are non-constant expressions, the max < min check is
done in the generated SQL and may convert values to NULL to encode an
empty result. That encoding is only handled by the VECTOR_GRID finalizer,
so scalar-backed vectors like clamp(vector(5), time() * 0 + 1, -1)
surfaced a NULL row instead of an empty vector. Cast the vector argument
to VECTOR_GRID whenever that SQL branch is emitted, the same way
comparison operators already do.
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Addressed the review finding in ee0c774: when non-constant bounds emit the SQL max < min check, the vector argument is now forced through toVectorGrid() (same as comparison operators), so scalar-backed vectors return an empty result instead of surfacing a NULL row. Verified against Prometheus 3.5.0: clamp(vector(5), time() * 0 + 1, -1) → [], dynamic non-empty and clamp_min/clamp_max cases unchanged. Added two regression tests.

The Upgrade check failure is unrelated to this PR: upgrade_error_messages.txt shows the known corrupted txn_version.txt part-loading error from test_7.t_plt_rb_contains (see #111053, hitting master and unrelated PRs since 2026-07-19).

if (isOneArgumentMathFunction(function_name))
return applyOneArgumentMathFunction(function_node, std::move(arguments), context);

if (isClampFunction(function_name))

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 adds support for clamp, clamp_min, clamp_max, and round, but the published Supported PromQL Features tables still don't mention any of them. After merge, users reading docs/en/sql-reference/table-functions/prometheusQuery.md and docs/en/sql-reference/table-functions/prometheusQueryRange.md will still be told those functions are unsupported. Please update that public support matrix in the same PR so the documented PromQL surface matches the implementation.

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.

The current tree still has this docs gap: docs/en/sql-reference/table-functions/prometheusQuery.md:48-49 lists the Math functions for prometheusQuery, and that row still stops at deg. applyFunction enables round, clamp, clamp_min, and clamp_max for instant queries too, so users of prometheusQuery are still told those functions are unsupported.

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.

The current tree still has the public docs gap, just in the Mintlify pages now. src/TableFunctions/TableFunctionTimeSeries.cpp:267-268 and src/TableFunctions/TableFunctionTimeSeries.cpp:337-338 advertise round, clamp, clamp_min, and clamp_max, but the committed English docs at docs/reference/functions/table-functions/prometheusQuery.mdx:46-49 and docs/reference/functions/table-functions/prometheusQueryRange.mdx:48-51 still have the Math row stopping at deg.

Since those AUTOGENERATED .mdx files are the pages users actually read, the documented PromQL surface is still understated until they are regenerated in the same PR.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

Done in 1bb0142: added round, clamp, clamp_min, clamp_max to the Supported PromQL Features function tables in both docs/en/sql-reference/table-functions/prometheusQuery.md and prometheusQueryRange.md, so the documented surface matches the implementation.

Casting a tag-less vector to a vector grid generated the group #0
constant as a plain literal 0 which ClickHouse types as UInt8, while
timeSeries* functions require UInt64. The clamp() empty-result path for
non-constant bounds converts scalar-backed vectors through toVectorGrid,
so clamp(vector(5), time() * 0 + 1, -1) failed with
'Argument ClickHouse#1 of function timeSeriesGroupToTags has wrong type UInt8'.

Same fix as in ClickHouse#111872 (which covers the remaining converter sites);
the identical hunks will merge cleanly whichever PR lands first.
Apply the same UInt64 cast to the no-tags group constant emitted by
applyLabelManipulationFunction and transformGroupASTForBinaryOperator
(empty on()), and teach the group #0 short-circuit to recognize the
CAST form, so constructs like label_replace(vector(1), ...) work with
the functions added by this PR. Byte-identical to the fix in ClickHouse#111872.
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Done in 7ee5701 — took the second option and updated the remaining 0u producers in the same change: applyLabelManipulationFunction (group argument of timeSeriesReplaceTag/timeSeriesJoinTags) and transformGroupASTForBinaryOperator (bare 0u for empty on()), plus the group #0 short-circuit now recognizes the CAST form. label_replace(vector(1), "x", "y", "", "") and empty-on() matching work now; verified against Prometheus 3.5.0.

All three producer hunks are byte-identical to #111872, so the two PRs merge cleanly in either order. A shared helper for the no-tags group constant is a good idea, but doing it in either open PR would break that identical-hunk property — proposing it as a small follow-up cleanup once one of them lands (it can also absorb the pre-existing inline CAST in transformGroupASTForAggregationOperator).

In PromQL scalar() returns NaN when its argument is an empty vector, so
a clamp()/clamp_min()/clamp_max() bound or a round() to_nearest argument
which is known to be empty at conversion time (e.g.
scalar(clamp(vector(1), 1, -1))) must produce NaN values instead of an
empty result. Convert such StoreMethod::EMPTY scalar arguments to
CONST_SCALAR NaN before applySimpleFunction() so that the existing NaN
handling applies to them. An empty vector (first) argument still makes
the result empty.
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Both findings addressed in 8a31885: scalar arguments that are empty at conversion time (StoreMethod::EMPTY, e.g. scalar(clamp(vector(1), 1, -1))) are now normalized to a constant NaN before dispatch, in both applyClampFunction and applyRoundFunction — funneling them into the same code paths as literal NaN bounds. clamp(vector(5), scalar(clamp(vector(1), 1, -1)), 10) and the round counterpart now return a NaN sample; an empty vector argument still yields an empty result (anchored by a test). Verified against Prometheus 3.5.0 on min/max/clamp_min/clamp_max/round variants; regression tests added for all of them.

Two notes: (1) top-level scalar(<empty vector>) currently fails at finalize (Cannot finalize expression ... store method: EMPTY) — a pre-existing gap in applyFunctionScalar/finalizeSQL outside this PR's files, worth a follow-up; the same EMPTY-propagation exists in the pre-existing quantile/topk scalar parameters. (2) The Stateless 04612_join_runtime_filters_index_analysis_multi_key_anti failure is unrelated to this PR (join runtime filters; this PR touches only PromQL conversion).

In PromQL scalar(<empty vector>) is NaN, so an argument which is known
to be empty at conversion time (e.g. scalar(clamp(vector(1), 1, -1)))
must produce a NaN constant instead of leaking StoreMethod::EMPTY into
finalizeSQL() (which threw a LOGICAL_ERROR) or into other consumers
(e.g. vector(scalar(...)) returned an empty result).

Handle this generically in applyFunctionScalar() and drop the
equivalent per-caller normalization from clamp() and round(): with the
generic fix a scalar argument can only be empty when its evaluation
range is empty, and then the result must stay empty anyway.
Upgrade check failure on the previous run is unrelated: metadata loading
broke on a corrupted txn_version.txt fabricated by the
04241_part_loading_tree_rollback_* tests (known issue, see ClickHouse#111053).
scalar() over a VECTOR_GRID with no rows (e.g.
scalar(clamp(nonexistent_metric, 0, 1)) evaluated over a range) made
countForEach()/anyForEach() return empty arrays instead of grid-sized
ones, and timeSeriesFromGrid() then failed with "Number of values (0)
doesn't match number of steps". Wrap the aggregation in
arrayResize(..., <count_of_time_steps>, NaN) so that an empty vector
yields NaN at each time step as PromQL requires. The single-point
branch already handles zero rows because count() over zero rows is 0.
Integration tests failure on the previous run is unrelated:
test_trace_log_memory_context/test.py::test_memory_context_in_trace_log
is known to be flaky (see ClickHouse#87995); the other 332 tests of that shard
passed.
The UInt64 casts for the no-tags group #0 constant (toVectorGrid,
label manipulation functions, empty on() in binary operators) had no
PromQL test exercising them, so the original "Argument ClickHouse#1 of function
timeSeriesGroupToTags has wrong type UInt8, it must be UInt64" failure
could regress without being noticed. Cover binary operators (including
an empty on() over tag-less vectors), label_replace(), label_join(),
topk() and the SCALAR_GRID range paths.
Stateless tests failure on the previous run is unrelated:
04612_join_runtime_filters_index_analysis_multi_key_anti timed out
under arm_asan_ubsan; this PR only changes PromQL conversion code and
integration tests, which that suite does not exercise.
scalar() of an empty vector now yields NaN, which is a PromQL-valid
quantile() parameter: quantile(NaN, ...) must return NaN (and
phi < 0 / phi > 1 must return -Inf / +Inf) with a warning instead of
failing the query. Without this, quantile(scalar(clamp(vector(1), 1,
-1)), vector(2)) failed with "Quantile level is out of range [0..1]"
thrown by quantileExactInclusiveForEach().

Short-circuit a constant out-of-range phi to a constant-valued grid,
and clamp a runtime scalar phi for the aggregate function while
substituting the Prometheus constant at runtime, the same way
histogram_quantile() already treats its phi. These are the same
changes as in ClickHouse#111871 which fixes this independently of scalar().
@nikitamikhaylov

Copy link
Copy Markdown
Member

@valerypetrov Can you please resolve conflicts?

@valerypetrov
valerypetrov requested a review from a team as a code owner August 4, 2026 02:38
@valerypetrov

Copy link
Copy Markdown
Contributor Author

@nikitamikhaylov , thank you for ping, resolved.

…atrix

prometheusQueryRange.md was updated already, but prometheusQuery.md and
both inline doc copies in TableFunctionTimeSeries.cpp still listed the
Math functions row stopping at `deg`, understating what applyFunction
actually supports for both instant and range queries.
# Conflicts:
#	docs/en/sql-reference/table-functions/prometheusQuery.md
#	docs/en/sql-reference/table-functions/prometheusQueryRange.md
#	src/TableFunctions/TableFunctionTimeSeries.cpp
…tions

The docs/en/sql-reference/table-functions/prometheusQuery(.md|Range.md)
fixes from earlier commits on this branch (96485da, 877f32a) only ever
applied to the legacy docs/en tree. When master was merged in (9d3c5a9),
master's side had already migrated those pages to the autogenerated
Mintlify docs/reference/functions/table-functions/*.mdx pages and dropped
docs/en entirely, so the merge kept the pre-fix Math row from master's
.mdx files while silently discarding the docs/en fix.

src/TableFunctions/TableFunctionTimeSeries.cpp (lines ~267-268 and
~337-338) already lists round, clamp, clamp_min, clamp_max in the Math
row of both inline FunctionDocumentation blocks -- these are the actual
source of truth for the AUTOGENERATED region in the .mdx pages, but the
.mdx pages themselves were never regenerated to match.

A full `<binary> local`-driven regen via
ci/jobs/scripts/docs/autogenerate/autogenerate_docs.py requires a built
ClickHouse binary, which isn't available here, so hand-edit the two
AUTOGENERATED Math rows to mirror the .cpp source verbatim:

- docs/reference/functions/table-functions/prometheusQuery.mdx
- docs/reference/functions/table-functions/prometheusQueryRange.mdx
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 4, 2026
Resolves the conflict reported by @nikitamikhaylov in
ClickHouse#111870.

The only conflict was in tests/integration/test_prometheus_protocols/test_evaluation.py,
where this branch's own one-off `quantile(time() * 0 - 1, vector(2))` runtime-scalar-phi
test collided with a much larger, more thorough test section that landed on `master`
via the sibling PR ClickHouse#111871 (`promql/quantile-hq-edge`, merged as `f098c3151b7`).

That sibling PR independently implemented and tested the exact same
`applyAggregationOperatorQuantile.cpp` runtime-scalar-phi clamping logic this branch's
own commit ("Handle out-of-range and NaN quantile() phi per PromQL semantics") added for
the same reason (this branch's `scalar()`-of-empty-vector -> NaN change can feed an
out-of-range/NaN phi into `quantile()` at runtime). The C++ file auto-merged with zero
remaining diff against `master`, confirming the two implementations are identical.
`master`'s test section is a strict superset of this branch's single case (it covers
phi < 0, phi > 1, NaN, `by`/`without` grouping, a nonexistent metric, and grid
preservation, via both `scalar(vector(<literal>))` and runtime arithmetic forms), so
this branch's one-off test was dropped in favor of `master`'s comprehensive version.
# Conflicts:
#	src/TableFunctions/TableFunctionTimeSeries.cpp
# Conflicts:
#	docs/reference/functions/table-functions/prometheusQuery.mdx
#	docs/reference/functions/table-functions/prometheusQueryRange.mdx
The prometheusQuery/prometheusQueryRange pages under docs/reference are
rendered from the FunctionDocumentation blocks in
TableFunctionTimeSeries.cpp, which already list round, clamp, clamp_min
and clamp_max. Editing the AUTOGENERATED regions directly duplicates
that source and is rejected by the docs check.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XvXEBdaJTCCnUdunCf8icr
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 694.63 MiB 691.63 MiB -3.00 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

6 object files changed (+238.73 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/TimeSeries/PrometheusQueryToSQL/applyClampFunction.cpp.o new 126.32 KiB +126.32 KiB
src/CMakeFiles/dbms.dir/Storages/TimeSeries/PrometheusQueryToSQL/applyRoundFunction.cpp.o new 108.18 KiB +108.18 KiB

737 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

11 translation units recompiled, 16 s compile time in total, 9 of them have a recent master baseline.

Job report

@nikitamikhaylov nikitamikhaylov self-assigned this Aug 17, 2026
@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 7604e8d Aug 17, 2026
181 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants