Repository navigation
Implement PromQL functions clamp(), clamp_min(), clamp_max() and round() - #111870
Conversation
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.
|
Workflow [PR], commit [20c9703] Summary: ✅
AI ReviewSummaryThis PR adds PromQL Findings
Final VerdictChanges are close, but the stale generated LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 134/157 (85.35%) · Uncovered code |
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.
|
Addressed the review finding in ee0c774: when non-constant bounds emit the SQL The Upgrade check failure is unrelated to this PR: |
| if (isOneArgumentMathFunction(function_name)) | ||
| return applyOneArgumentMathFunction(function_node, std::move(arguments), context); | ||
|
|
||
| if (isClampFunction(function_name)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Done in 1bb0142: added |
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.
|
Done in 7ee5701 — took the second option and updated the remaining 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 |
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.
|
Both findings addressed in 8a31885: scalar arguments that are empty at conversion time ( Two notes: (1) top-level |
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().
|
@valerypetrov Can you please resolve conflicts? |
|
@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
… namespace unwind
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
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes6 object files changed (+238.73 KiB total), 2 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units11 translation units recompiled, 16 s compile time in total, 9 of them have a recent master baseline. |
Co-Authored-By: Claude Fable 5 <[email protected]>
Related: #57545
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
PromQL: implemented functions
clamp,clamp_min,clamp_max, andround.Description
Implements four PromQL functions previously reported as not implemented:
clamp(v, min, max),clamp_min(v, min),clamp_max(v, max)— newapplyClampFunctionconverter mapping togreatest/leastSQL with explicit guards, because vectorizedleast/greatestin 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 > maxreturns an empty vector, and a NaN bound propagates NaN.round(v[, to_nearest])— newapplyRoundFunctionconverter; replicates Prometheus inverse arithmetic (floor(v * (1/to_nearest) + 0.5) / (1/to_nearest)), including ties rounding toward+Infand NaN propagation forto_nearest = 0or 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
prometheusQueryandprometheusQueryRangelist the new math functions and retain the implemented range functionsincrease,changes, andresets.Semantics verified against Prometheus 3.5.0 for bound combinations
(0, 1),(0, 1e12),(1e12, 0),(1e12, 1e12), and fractionalto_nearest.Testing: adds
test_clampandtest_round, plus conversion and aggregation regressions for empty scalar handling and a runtime scalarquantileparameter outside[0, 1].Version info
26.8.1.1566(included in26.8and later)