Repository navigation
Implement PromQL histogram_quantile function - #103477
grantholly-clickhouse merged 14 commits into
Conversation
|
@vitlibar thank you so much for working on the prometheus + |
|
Workflow [PR], commit [eba3a53] Summary: ✅ AI ReviewSummaryThis PR adds Final VerdictStatus: ✅ Approve |
There was a problem hiding this comment.
Why have so many lines changed?
There was a problem hiding this comment.
@nikitamikhaylov I apologize for the bad rebase! Y'all move fast 🚀
8ba64fa to
83a496c
Compare
…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.
83a496c to
950fa8c
Compare
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.
|
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 |
…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)
LLVM Coverage Report
Changed lines: 93.81% (91/97) · Uncovered code |
|
@vitlibar @nikitamikhaylov this should be ready for a look when y'all have time |
…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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added support for the PromQL
histogram_quantilefunction inprometheusQueryandprometheusQueryRangetable functions. This enables computing quantiles over classic Prometheus histogram buckets identified by thelelabel.Documentation entry for user-facing changes
Documentation has been added to
docs/en/sql-reference/table-functions/prometheusQuery.md:histogram_quantileto the list of supported functionsImplementation Details
This PR implements support for the
histogram_quantilePromQL function using the existingquantilePrometheusHistogramForEachaggregate function. The implementation:lelabelleand__name__Key files:
src/Storages/TimeSeries/PrometheusQueryToSQL/applyHistogramQuantile.{h,cpp}src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunction.cppdocs/en/sql-reference/table-functions/prometheusQuery.mdtests/integration/test_prometheus_protocols/test_evaluation.pyLimitations:
lelabel)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
26.6.1.721