Skip to content

Implement PromQL histogram_quantile function - #103477

Merged
grantholly-clickhouse merged 14 commits into
ClickHouse:masterfrom
Yasumoto:promql-histogram-quantile-clean
Jun 12, 2026
Merged

grantholly-clickhouse merged 14 commits into
ClickHouse:masterfrom
Yasumoto:promql-histogram-quantile-clean

Conversation

@Yasumoto

@Yasumoto Yasumoto commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

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

Added support for the PromQL histogram_quantile function in prometheusQuery and prometheusQueryRange table functions. This enables computing quantiles over classic Prometheus histogram buckets identified by the le label.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Documentation has been added to docs/en/sql-reference/table-functions/prometheusQuery.md:

  • Added histogram_quantile to the list of supported functions
  • Included note about linear interpolation on classic histogram buckets
  • Noted that native histograms are not yet supported

Implementation Details

This PR implements support for the histogram_quantile PromQL function using the existing quantilePrometheusHistogramForEach aggregate function. The implementation:

  • Extracts bucket boundaries from the le label
  • Groups by all labels except le and __name__
  • Applies linear interpolation to compute quantiles
  • Follows Prometheus semantics for edge cases (e.g., +Inf bucket handling)

Key files:

  • New: src/Storages/TimeSeries/PrometheusQueryToSQL/applyHistogramQuantile.{h,cpp}
  • Modified: src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunction.cpp
  • Modified: docs/en/sql-reference/table-functions/prometheusQuery.md
  • Modified: tests/integration/test_prometheus_protocols/test_evaluation.py

Limitations:

  • Currently requires a constant phi (quantile level) parameter
  • Native histograms not yet supported (only classic buckets with le label)

Testing:
Integration tests added that verify behavior matches Prometheus v3.5.0 for both interpolation cases and edge cases (quantiles in +Inf bucket).

Version info

  • Merged into: 26.6.1.721

@CLAassistant

CLAassistant commented Apr 23, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@Yasumoto

Copy link
Copy Markdown
Contributor Author

@vitlibar thank you so much for working on the prometheus + TimeSeries support! I took a stab at histograms, if you have any feedback or prefer a different direction please let me know.

@nikitamikhaylov nikitamikhaylov added comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... can be tested Allows running workflows for external contributors labels Apr 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eba3a53]

Summary: ✅


AI Review

Summary

This PR adds histogram_quantile support for prometheusQuery and prometheusQueryRange, including argument validation, SQL translation for classic histogram buckets, documentation updates, and integration coverage against Prometheus behavior. I reviewed the current diff and all prior thread replies; there are no remaining unresolved correctness, safety, or contract issues in the current code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Apr 23, 2026

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.

Why have so many lines changed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@nikitamikhaylov I apologize for the bad rebase! Y'all move fast 🚀

@Yasumoto
Yasumoto force-pushed the promql-histogram-quantile-clean branch from 8ba64fa to 83a496c Compare April 23, 2026 22:32
…verter

This commit implements support for the `histogram_quantile` function in the
`prometheusQuery` and `prometheusQueryRange` table functions.

The implementation uses the existing `quantilePrometheusHistogramForEach`
aggregate function to compute quantiles over classic histogram buckets
identified by the `le` label. It follows the standard PromQL semantics:
- Extracts bucket boundaries from the `le` label
- Groups by all labels except `le` and `__name__`
- Applies linear interpolation via `quantilePrometheusHistogramForEach`

Key implementation details:
- New files: `applyHistogramQuantile.h` and `applyHistogramQuantile.cpp`
- Modified: `applyFunction.cpp` (wired in histogram_quantile dispatch)
- Modified: `prometheusQuery.md` (documented histogram_quantile support)
- Modified: `test_evaluation.py` (added histogram test data and tests)

The implementation currently requires a constant phi (quantile level)
parameter. Native histogram support is deferred to future work.
The test was expecting 1.4 for the 0.9 quantile when it falls in the +Inf
bucket, but actual Prometheus v3.5.0 returns 1.0 (the upper bound of the
last finite bucket). Updated the test to expect "1" to match Prometheus
behavior.

Verified that both Prometheus and ClickHouse now return the same value.
@Yasumoto
Yasumoto force-pushed the promql-histogram-quantile-clean branch from 83a496c to 950fa8c Compare April 23, 2026 23:37
Restores the aggregation-operator test coverage that was incorrectly
deleted (`topk`, `bottomk`, `limitk`, `stddev`, `stdvar`, `quantile`
and their by/without variants) by reverting the test file to master
and layering the `histogram_quantile` additions on top. The test file
is now purely additive against master.

Adds explicit argument-type validation in `applyHistogramQuantile` so
that invalid calls like `histogram_quantile(0.9, 1)` return
`CANNOT_EXECUTE_PROMQL_QUERY` instead of `LOGICAL_ERROR`, matching the
convention established by `applyAggregationOperatorQuantile`.

Expands `histogram_quantile` test coverage:
- First-bucket interpolation (phi=0.1) to exercise the lower-edge path
- Multi-group output to verify `le` and `__name__` are dropped while
  other labels are preserved
- Two negative tests for type validation (scalar/vector swapped)

Mirrors the "Supported PromQL Features" section into
`prometheusQueryRange.md`, adds `{#anchor}` suffixes to new subsection
headers, and adds `matchers` to the aspell dictionary to fix the
failing style check.

CI report (before this commit):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103477&sha=950fa8c019880c32a3798d5564dd5d6e458fcdd1&name_0=PR
PR: ClickHouse#103477
Addresses review comment #3134856828 on ClickHouse#103477: the implementation
currently throws `NOT_IMPLEMENTED` for non-constant `phi` arguments
(anything other than `StoreMethod::CONST_SCALAR`), so expressions
like `histogram_quantile(time() / 1000, ...)` will fail. Document the
constraint explicitly in both `prometheusQuery.md` and
`prometheusQueryRange.md` to set user expectations.

Review comment:
ClickHouse#103477 (comment)
Per the PromQL spec, `histogram_quantile` returns `-Inf` for `phi < 0`,
`+Inf` for `phi > 1`, and `NaN` for `NaN phi` — these checks happen
before looking at the histogram. The previous implementation forwarded
phi directly to `quantilePrometheusHistogramForEach`, which is defined
for `phi in [0, 1]` only and produced incorrect interpolated values
outside that range (for example `histogram_quantile(-0.5, bucket)`
returned `-0.3` instead of `-Inf`).

With `phi` required to be a constant scalar, the converter can detect
out-of-range values at SQL-build time and replace the aggregate call
with `arrayMap(x -> if(isNotNull(x), <const>, NULL), anyForEach(values))`.
This preserves the per-group grouping and per-timestep NULL positions
while emitting the correct constant.

Adds three positive tests (`phi=-0.5`, `phi=1.5`, `phi=NaN`).

Addresses review comments:
ClickHouse#103477 (comment)
ClickHouse#103477 (comment)
Rework the multi-group `histogram_quantile` test to follow the
`topk`/`bottomk`/`limitk` precedents. Prometheus's instant-vector output
is explicitly unordered per the HTTP API docs, so a multi-group instant
comparison against Prometheus is inherently flaky. Split the case into:

* a range-query assertion that compares against Prometheus (both sides
  return matrices sorted alphabetically by labels), and
* a `do_clickhouse_only_query_test` instant assertion that locks in our
  deterministic alphabetical ordering without asserting against
  Prometheus, mirroring the `limitk` precedent.

Add edge-case tests around the `quantilePrometheusHistogramForEach`
aggregate:

* single `+Inf` bucket (size < 2) -> NaN
* missing `+Inf` bucket -> NaN
* all-zero counts -> NaN
* negative `le` upper bounds -> interpolation still works
* empty result passthrough (exercises the `StoreMethod::EMPTY` branch in
  `applyHistogramQuantile`)
* idiomatic `histogram_quantile(phi, rate(bucket[window]))` usage

Add the supporting histogram time series to `send_test_data`.
The review pass flagged comments that describe what the test data shows
(bucket layouts, interpolation arithmetic, per-metric restatements of
the NaN-on-degenerate-input rule) rather than non-obvious why. Collapse
the `send_data` preamble and the per-test narration, keeping only the
notes that reference external semantics (Prometheus degenerate-input
rules, the `StoreMethod::EMPTY` short-circuit, the multi-group ordering
precedent).
The extra `do_clickhouse_only_query_test` case asserted that ClickHouse
returns instant-vector groups in deterministic alphabetical order. That
premise is wrong: local runs returned `(writer, reader)` this time and
`(reader, writer)` previously, because the row order depends on the
underlying `MergeTree` scan and isn't guaranteed for instant queries.

The range-query variant above already covers the multi-group case and
compares against Prometheus end-to-end. Nobody asked for the instant
variant in review; remove it rather than introducing a stable-order
contract we don't actually enforce.
`histogram_quantile(0.5, rate(rate_bucket[60s]))` at t=360 evaluated
empty in ClickHouse because the only two samples sat on the boundary of
the `(300, 360]` lookback window. Prometheus incidentally included the
sample at t=300, ClickHouse did not, so rate() saw one point and
returned nothing. Add a third sample at t=330 strictly inside the
window; the linearly-scaled cumulative counts preserve the bucket
ratios, so phi=0.5 still lands on the le=0.5 bucket edge.

Verified locally: all 18 histogram_quantile assertions pass.
@Yasumoto

Copy link
Copy Markdown
Contributor Author

Hm, the test failures look like they're unrelated flakes, but if they aren't I'm happy to fix 'em up in this diff

@vitlibar vitlibar self-assigned this May 13, 2026
Yasumoto and others added 3 commits May 19, 2026 14:39
…antile-clean

# Conflicts:
#	src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunction.cpp
#	tests/integration/test_prometheus_protocols/test_evaluation.py
`aspell-dict.txt` was deleted in master along with the `aspell` and
`codespell` style checks. Removing the file here so the PR can merge
cleanly without a modify/delete conflict.
Prometheus silently drops bucket series whose `le` label is not parseable
as a float, rather than failing the whole query. Our converter was using
`toFloat64`, which throws `CANNOT_PARSE_TEXT` on inputs like `le="abc"`,
turning a single malformed bucket into an exception for the entire
`histogram_quantile` call.

Switch to `toFloat64OrNull(...)` and map `NULL` to `NaN`, the same
sentinel `quantilePrometheusHistogramForEach` already uses to ignore a
bucket sample. Missing-tag and unparseable-tag now collapse to the same
"ignore this bucket" path.

Add a regression test with a `bad_le_bucket` fixture that includes one
bucket with `le="abc"` mixed with well-formed buckets; the test fails
on the previous binary with `CANNOT_PARSE_TEXT` and passes with the
fix.

ClickHouse#103477 (comment)
…rate

The PromQL→SQL converter was dropping `__name__` *before* the GROUP BY
in `histogram_quantile`. A query that selects multiple `*_bucket`
metrics with overlapping non-name labels — for example
`{__name__=~"a_bucket|b_bucket"}` or `a_bucket or b_bucket` — would
collapse buckets from different histograms into a single synthetic
histogram and return one wrong quantile instead of one per histogram.

Keep `__name__` in the group key during the quantile computation, then
route the result through `dropMetricName`, which already exists for
exactly this purpose: it strips `__name__` after a transformation while
enforcing PromQL's no-duplicate-labelset rule via
`timeSeriesThrowDuplicateSeriesIf`.

Add a regression test with two distinct histograms (`two_hist_a_bucket`
and `two_hist_b_bucket`) selected together by name regex; each retains
a `kind` label so the post-quantile labelsets stay distinct. Pre-fix
behavior produces a single merged result; post-fix produces one result
per histogram with the correct quantile.

ClickHouse#103477 (comment)
@clickhouse-gh

clickhouse-gh Bot commented May 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 93.81% (91/97) · Uncovered code

Full report · Diff report

@Yasumoto

Copy link
Copy Markdown
Contributor Author

@vitlibar @nikitamikhaylov this should be ready for a look when y'all have time

@grantholly-clickhouse
grantholly-clickhouse added this pull request to the merge queue Jun 12, 2026
Merged via the queue into ClickHouse:master with commit 2e8e7f1 Jun 12, 2026
166 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 12, 2026
github-merge-queue Bot pushed a commit that referenced this pull request Jun 12, 2026
…antile

cppcoreguidelines-init-variables (warnings-as-errors) rejects the
uninitialized Float64 out_of_range_value introduced by #103477, breaking
the arm_tidy build on master. All three branches assign it, so it is
logically safe, but the declaration must be initialized. Initialize to
quiet_NaN() at declaration. No behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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-feature Pull request with new product 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.

7 participants