Skip to content

Fix PromQL edge cases: out-of-range quantile() phi and histogram_quantile() over series without le - #111871

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
valerypetrov:promql/quantile-hq-edge
Aug 4, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
valerypetrov:promql/quantile-hq-edge

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: quantile with a quantile level outside [0, 1] now returns -Inf/+Inf/NaN like Prometheus instead of throwing an error, and histogram_quantile now ignores input series whose le label is missing or unparsable, like Prometheus.

Description

Two Prometheus compatibility fixes in the PromQL-to-SQL layer:

  1. quantile(phi, v) aggregation with phi outside [0, 1]: previously failed with Quantile level is out of range [0..1] (thrown by the underlying quantileExactInclusive). Prometheus instead returns -Inf for phi < 0, +Inf for phi > 1 and NaN for phi = NaN for every group. For constant out-of-range/NaN phi the converter now emits a constant grid-aligned array (same pattern as the existing histogram_quantile out-of-range short-circuit) instead of calling the quantile function. In-range SQL generation is byte-identical to before. Applies to plain, by (...) and without (...) forms.

  2. histogram_quantile(phi, v) over series without a parsable le label: Prometheus drops such series (strconv.ParseFloat failure leads to the series being skipped); ClickHouse passed them through, e.g. histogram_quantile(0.9, <gauge without le>) returned all input series where Prometheus returns an empty result. Added a filter on toFloat64OrNull(timeSeriesExtractTag(group, 'le')) to the bucket aggregation query, applied to both the normal and the out-of-range-phi branches — the filter must run before the short-circuit, which also fixes histogram_quantile(-0.5, <non-histogram>) returning -Inf series instead of an empty result.

Series with a valid le (real buckets) flow through unchanged: histogram_quantile(0.9/-0.5/1.5, rate(..._bucket[1m])) results are identical before and after.

Semantics verified against Prometheus 3.5.0, including mixed inputs where only the series carrying le survive.

Testing: 10 new cases in tests/integration/test_prometheus_protocols/test_evaluation.py (6 for aggregation quantile, 4 for histogram_quantile). This flips 3 queries of the PromQL compliance suite from failed to passed.

Version info

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

…tile() over series without le

PromQL evaluates quantile(phi, v) with phi outside [0, 1] to a constant
(with a warning) instead of failing the query: phi < 0 -> -Inf, phi > 1 -> +Inf,
NaN -> NaN for every group. ClickHouse used to throw "Quantile level is out of
range [0..1]". For a constant out-of-range phi we now emit a constant-valued
array aligned to the time grid, the same way histogram_quantile already
handles an out-of-range phi.

histogram_quantile() now excludes input series whose le label is missing or
cannot be parsed as a float, matching Prometheus which silently drops such
series: a pure non-histogram input yields an empty result. The filter applies
before the out-of-range phi short-circuit, also matching Prometheus.
@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 [e903a8b]

Summary: ✅


AI Review

Summary

This PR fixes two PromQL compatibility gaps: out-of-range or NaN quantile levels now return the Prometheus constants instead of throwing, and histogram_quantile now drops series whose le label is missing before the out-of-range short-circuit. I reviewed the current diff, the touched helper paths, the prior bot threads, and the current PR discussion/CI state. The earlier StoreMethod::SINGLE_SCALAR correctness and coverage concerns are fixed in the current code, the histogram_quantile filter is applied in the right place, and I did not find a remaining blocker or major issue.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 69/70 (98.57%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 25, 2026
…of range

Initialize out_of_range_value at declaration (cppcoreguidelines-init-variables).

Extend the out-of-range quantile level handling to runtime scalar levels
like quantile(scalar(vector(-0.5)), v): clamp the aggregate function
parameter into [0, 1] and substitute -Inf/+Inf/NaN in the result when the
original level is out of range or NaN, matching Prometheus.
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Both findings addressed in 35fb986:

  1. Build (arm_tidy): out_of_range_value is now initialized at declaration (cppcoreguidelines-init-variables), same pattern as the existing code in applyHistogramQuantile.cpp.
  2. Runtime scalar quantile levels: the out-of-range handling now also covers StoreMethod::SINGLE_SCALAR, e.g. quantile(scalar(vector(-0.5)), v): the aggregate parameter is clamped into [0, 1] and the result is substituted with -Inf/+Inf/NaN at runtime when the original level is out of range or NaN. Verified against Prometheus 3.5.0 including by (...) grouping and the NaN case; constant-level and in-range paths generate byte-identical SQL as before. Added four regression tests.

…lar phi path

clang-tidy (bugprone-use-after-move): std::move(phi) and phi->clone() were
unsequenced arguments of the same multiIf() call, so replace the move with
one more clone().

The scalar(vector(<literal>)) tests added earlier are converted to a constant
phi before the query runs, so they never reached the new runtime out-of-range
check. Add tests whose phi provably stays a scalar subquery at runtime:
binary scalar arithmetic (never constant-folded by the converter) and
scalar() over a stored series, covering phi < 0, phi > 1, NaN and in-range
values for instant and multi-step evaluation.
Stateless tests failure is unrelated: server died while running
03915_exchange_tables_race (known flaky, see ClickHouse#110133), same pattern
as on other PRs in this series.
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.40% +0.10%

Changed lines: Changed C/C++ lines covered: 69/70 (98.57%) · Uncovered code

Full report · Diff report

valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Jul 27, 2026
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 added a commit to valerypetrov/ClickHouse that referenced this pull request Jul 29, 2026
The previous commit fixed the implicit 0-argument branch of
applyDateTimeFunction() (e.g. minute()) to synthesize the evaluation time
via makeTimeQueryPieceNative(), avoiding Float32 precision loss on a
TimeSeries table with a Float32-typed value column. The PromQL spec says
f() is equivalent to f(vector(time())), but the explicit vector(time())
carrier still went through the generic conversion path (fromFunctionTime()
-> makeTimeQueryPiece()), which casts the evaluation time down to
context.scalar_data_type. So on a Float32 table, minute(vector(time()))
still rounded 1770582700 to 1770582656 and returned 30, disagreeing with
minute() returning 31 - two equivalent PromQL spellings with different
answers.

Add asVectorOfTime() to detect the vector(time()) argument shape at the
AST level, and, when detected, rebuild that argument with
makeTimeQueryPieceNative() (the same helper the 0-argument branch already
uses) instead of the lossy piece the generic path already built.

Extend the existing Float32-table regression test with sibling assertions
for minute(vector(time())), both instant and range, expecting the same
answer as the zero-argument form.

Verified against the built binary: minute()/minute(vector(time())) and
hour()/hour(vector(time())) now agree (31 and 20 respectively) at
timestamp 1770582700 on a Float32-valued TimeSeries table, both as
instant and range queries. The standalone compliance harness shows no
regressions from this change (390 pass / 4 fail / 143 unsupported / 2
ref_mismatch); all non-passing queries are quantile()/histogram_quantile()/
label_replace()/label_join() cases fixed by the unrelated PR ClickHouse#111871,
which this branch forked before and does not include.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm afraid if it makes the expression heavier for little benefit. The logic does not sound logical, but rather like something just happened to be so in Prometheus. Do we aim for 100% bug-compatibility with Prometheus?

@alexey-milovidov alexey-milovidov self-assigned this Aug 3, 2026
@valerypetrov

Copy link
Copy Markdown
Contributor Author

I'm afraid if it makes the expression heavier for little benefit. The logic does not sound logical, but rather like something just happened to be so in Prometheus. Do we aim for 100% bug-compatibility with Prometheus?

I'm agree, that it is a hacky thing. I think it's your call, whether do you want the CH to have the 100% compatibility with Prometheus(even, when the design is pretty wacky). But from user perspective, I'd like to have as close as possible compatibility to Prometheus. Because I don't want to change any implemented Grafana dashboards & alerting that's been in place.

If the goal for CH is to achieve the 100% compatibility here:
What do you think, if we group these strange & buggy Prometheus methods(I think there will be more, especially if the target is a 100% here) into some "bucket" that could be enabled disabled globally via settings? Something like 'enable_full_prometheus_compatibility'

@alexey-milovidov

Copy link
Copy Markdown
Member

Okay. While Prometheus is still in active development, we can merge it and decide on a compatibility switch later.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 4, 2026
Merged via the queue into ClickHouse:master with commit f098c31 Aug 4, 2026
180 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 5, 2026
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 6, 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.
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... 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.

4 participants