Skip to content

Implement PromQL functions absent and count_values - #112795

Merged
nikitamikhaylov merged 12 commits into
ClickHouse:masterfrom
valerypetrov:promql/absent-count-values
Sep 2, 2026
Merged

nikitamikhaylov merged 12 commits into
ClickHouse:masterfrom
valerypetrov:promql/absent-count-values

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Jul 31, 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 absent and count_values, including range queries and by/without aggregation modifiers.

Description

Implements two PromQL operations that previously returned a not-implemented error and require result construction beyond transforming a fixed per-series values array.

  • absent(v instant-vector) aggregates sample presence across all input series independently at every grid point and emits one synthetic sample with value 1 only where the input is empty. For a direct selector, including offset and @ modifiers, it performs Prometheus-compatible equality-matcher label inference while excluding __name__; complex expressions produce an unlabeled result. Label inference deliberately mirrors Prometheus's historic monotonic has map: after the first accepted equality matcher for a label name, a later matcher can delete the inferred label but cannot unlock that name for another equality matcher. An empty exact-match value is canonicalized as label absence, matching Prometheus labels.Builder::Set.
  • count_values(label, v instant-vector) unrolls each series' grid values, sets or overwrites the requested value label, groups by label set, grid point, and formatted sample value, counts each bucket, and repacks sparse counts into nullable grid arrays. Both by (...) and without (...) are supported, including removing the generated label or using __name__ as the destination. Destination label names follow Prometheus 3.x UTF-8 validation—non-empty valid UTF-8—rather than the legacy ASCII label-name pattern.

A new internal timeSeriesPrometheusValueToString function reproduces Go's fixed shortest-roundtrip formatting used by Prometheus, including -0, NaN, +Inf, and -Inf. The supported-function documentation for prometheusQuery and prometheusQueryRange is updated accordingly.

Verified against Prometheus 3.5.0 with direct response comparisons covering sparse range points, inferred labels (including equality/regex/equality ordering and empty exact-match values), grouping modifiers, empty inputs, metric-name and non-legacy UTF-8 destination labels, floating-point label strings, and result ordering.

Testing: added test_function_absent and test_aggregation_operator_count_values integration coverage in tests/integration/test_prometheus_protocols/test_evaluation.py. All six modified C++ translation units compile locally with zero warnings or errors. The focused queries were exercised against a local TimeSeries table and compared with Prometheus 3.5.0. The clean-master integration module collects all 25 tests, including both additions, but no test body ran locally because the Docker daemon was unavailable and the module-scoped cluster fixture failed during setup; containerized integration execution is left to CI.


Workflow [PR]
Sync PR [sync-upstream/pr/112795]

Version info

  • Merged into: 26.9.1.557 (included in 26.9 and later)

Implement absent by aggregating per-grid sample presence across all input series. Emit a synthetic value of 1 for empty grid points and infer labels from unambiguous equality matchers on a direct selector, while preserving Prometheus matcher-order and offset behavior.

Implement count_values with an unroll, relabel, regroup, and repack pipeline. The value-dependent label becomes part of each grid point grouping key, with full by/without handling, destination-label replacement, sparse range results, empty vectors, and __name__ support.

Add an internal float formatter matching Go fixed shortest-roundtrip representation so generated value labels preserve -0 and render NaN and infinities like Prometheus. Register both converters, add integration coverage, and update the prometheusQuery support documentation.

Local runtime results and ordering were compared with Prometheus 3.5.0. The integration module collected 28 tests, but Docker was unavailable during module fixture setup, so no pytest test body ran locally.

Related: ClickHouse#57545
Replace round with an equivalent expression built from floor and scalar arithmetic so the new count_values coverage applies directly to current master without depending on another open PromQL feature PR. The positive fixture values produce the same 0, 100, 700, and 1000 buckets.

Verified the three updated queries against Prometheus 3.5.0 and the local ClickHouse TimeSeries test binary.

Related: ClickHouse#57545
@valerypetrov
valerypetrov requested a review from a team as a code owner July 31, 2026 19:12
Document that absent label inference intentionally mirrors Prometheus historic monotonic has map: after the first accepted equality matcher, a later matcher can delete the inferred label but cannot unlock it for another equality matcher.

Cover the three-matcher equality/regex/equality sequence and confirm that Prometheus 3.x accepts non-empty UTF-8 count_values destination labels outside the legacy label-name pattern.

Both cases were compared directly with Prometheus 3.5.0 and the local ClickHouse TimeSeries test binary.
@valerypetrov
valerypetrov force-pushed the promql/absent-count-values branch from baa626a to 71adef5 Compare July 31, 2026 19:32
@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 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7685647]

Summary: ✅


AI Review

Summary

This PR adds PromQL absent and count_values support, wires in the new value-string formatter, and adds focused integration coverage. I did not find any unresolved correctness, compatibility, or safety issues in the current PR state.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.30% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 305/348 (87.64%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 31, 2026
Document and test that Prometheus treats inferred empty label values as missing labels. Value-initialize the formatting buffers to fix the arm_tidy build.
@valerypetrov

valerypetrov commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Follow-up pushed in 63a84b888ac6c2f901beaf8b273ee97e260aaa61.

I kept the existing empty-value behavior because the review's requested expectation is inverted relative to Prometheus 3.5.0:

  • createLabelsForAbsentFunction passes the exact matcher to labels.Builder::Set.
  • labels.Builder::Set calls Del when the value is empty because Prometheus treats empty and missing labels as equivalent.
  • A live Prometheus 3.5.0 query for absent(nonexistent_metric_name{job=""}) returns {"metric":{},"value":[140,"1"]}.

The follow-up adds that exact regression with {} as the expected metric and documents the canonicalization next to the implementation. It also value-initializes the two formatter buffers flagged by arm_tidy;

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

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: 302/348 (86.78%) · Uncovered code

Full report · Diff report

@nikitamikhaylov nikitamikhaylov self-assigned this Aug 3, 2026
Resolves two modify/delete conflicts caused by master's docs migration
from docs/en/**/*.md to autogenerated Mintlify docs/reference/**/*.mdx:

- docs/en/sql-reference/table-functions/prometheusQuery.md
- docs/en/sql-reference/table-functions/prometheusQueryRange.md

Both were deleted upstream in favor of their Mintlify successors
(per docs/_migration/slug-map.csv):

- docs/reference/functions/table-functions/prometheusQuery.mdx
- docs/reference/functions/table-functions/prometheusQueryRange.mdx

Ported this PR's doc changes (adding `absent` to the supported
functions table and `count_values` to the supported aggregation
operators, removing the "not yet supported" note) into the new .mdx
files, matching the existing Mintlify formatting.

All other conflicts (applyAggregationOperator.cpp, applyFunction.cpp,
TableFunctionTimeSeries.cpp) auto-merged cleanly, combining this PR's
absent/count_values dispatch entries and inline docs with master's
independent changes (new Range functions, anchor renames) in the same
file regions.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 4, 2026
valerypetrov and others added 2 commits August 5, 2026 10:34
… namespace unwind

Master's "Unwind the PQT abbreviation" PR (merged in commit 3e57eeb)
removed the `using PQT = PrometheusQueryTree;` alias from ConverterDefs.h
and renamed all `PQT::` usages elsewhere to `PrometheusQueryTree::`. This
branch's own new files (applyAggregationOperatorCountValues.cpp/.h,
applyFunctionAbsent.cpp/.h) still referenced the removed `PQT` alias, so
they failed to compile after merging master, with clang reporting
"use of undeclared identifier 'PQT'" plus cascading error-recovery
diagnostics in applyFunctionAbsent.cpp ("no member named 'getExpression'
in 'DB::PrometheusQueryTree::Node'" and a bogus `const int *` return
type mismatch) — both artifacts of the same root cause, not independent
bugs: `Offset::getExpression()` returns `const Node *` exactly as used
once `PQT::Offset` correctly resolves to `PrometheusQueryTree::Offset`.

CI report: ClickHouse#112795
The prometheusQuery/prometheusQueryRange .mdx pages regenerate their
supported-syntax sections from TableFunctionTimeSeries.cpp, which already
carries the absent/count_values updates.
count_values sets its destination label before the grouping modifier is applied. `by` implicitly keeps that label, while `without` removes only the labels listed by the user plus `__name__`. A destination label that is neither is therefore retained by `without`, whereas a `__name__` destination is not.

Pin all three shapes: `count_values("value", ...) without (shape)` keeps `value` and produces the same result as the `by (size)` form; `count_values("__name__", ...) by (size)` keeps `__name__`, so every distinct value stays its own bucket; `count_values("__name__", ...) without (shape)` drops `__name__`, so the buckets collapse into one count per remaining label set.
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7685647bd with master 887b93e16 (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 710.16 MiB 707.15 MiB -3.00 MiB (-0.42%)

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

5 object files changed (+437.95 KiB total), 3 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/TimeSeries/PrometheusQueryToSQL/applyAggregationOperatorCountValue… new 184.93 KiB +184.93 KiB
src/CMakeFiles/dbms.dir/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionAbsent.cpp.o new 140.04 KiB +140.04 KiB
src/Functions/TimeSeries/CMakeFiles/clickhouse_functions_time_series.dir/timeSeriesPrometheusValueT… new 112.35 KiB +112.35 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

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

Job report

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@nikitamikhaylov , can you please check this one? It seems to be ready for review.

checkArgumentTypes already requires arguments[0].type == ResultType::STRING,
and the only AST node that produces that result type is StringLiteral (see
PrometheusQueryTree.h and fromLiteral.cpp), so the node_type check here can
never be false.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 887b93e16

Metric Baseline Current Δ
Score 77.74% 78.29% +0.56%
Passed 419 422 +3
Failed 3 3 +0
Unsupported 117 114 -3

Uploaded compliance JSON for this PR commit

Baseline update

This run reports 78.29% vs master baseline 77.74% (887b93e16). Merging to master will publish a new S3 object from the integration job that runs test_promql_compliance, which becomes the baseline for later PRs.

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Sep 2, 2026
Merged via the queue into ClickHouse:master with commit c064f38 Sep 2, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 2, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@valerypetrov @nikitamikhaylov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

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.

4 participants