Skip to content

Push PromQL label matchers across binary operators - #122972

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
valerypetrov:promql-static-label-pushdown
Oct 10, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
valerypetrov:promql-static-label-pushdown

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

This PR copies the label matchers of one side of a PromQL binary operator into the selectors of the other side, for the labels the operator matches series by. For example, rate(b[5m]) / on(instance) rate(a{instance="x"}[5m]) now reads only b{instance="x"}. Matchers are not copied through or, label functions, count_values, absent, unary minus or functions without a range argument, and only from left to right for unless. When both sides become the same, the existing fused aggregation reads them once. Expressions with more than 20 binary operators are left as they are. The new setting promql_push_down_label_matchers (on by default) turns it off: a copied matcher that keeps most series of a whole-metric selector can be slower on a table with very many marks (the index_granularity = 64 rows). To keep Prometheus' errors, a matcher is not copied into the "one" side of the operator (the right side, or the left side with group_right) unless that side is an aggregation by labels that are all matched on, not into a nested operator between two vectors other than and and unless, and not through a function or operator unless its input is one metric selected by name, except a comparison without bool. The only change in errors matches Prometheus: duplicate left series of a one-to-one match in a group the right side does not have no longer fail the query.

test case query master this PR
default layout, 19,800 series, 28.5M samples, 6 h, step 30 s sum by (instance) (rate(node_cpu_seconds_total{instance="host-001:9100",mode!="idle"}[5m])) / on(instance) sum by (instance) (rate(node_cpu_seconds_total[5m])) 142 ms 32 ms
same, fused sum by (job) (rate(http_requests_total{job="node-api"}[5m])) / sum by (job) (rate(http_requests_total[5m])) 51 ms 19 ms
same, matcher keeps 75% rate(node_cpu_seconds_total[5m]) / on(instance, region) group_left node_load1{region!="ap-south-1"} 148 ms 130 ms
same, matcher keeps 75% rate(http_requests_total[5m]) / on(instance, job) group_left up{job=~"node-api|node-db|node-web"} 48 ms 44 ms
same, matcher keeps 100% rate(node_cpu_seconds_total[5m]) / on(instance, job) group_left up{job=~"node-.*"} 185 ms 181 ms
same, nothing to copy sum by (job) (rate(http_requests_total{code="500"}[5m])) / sum by (job) (rate(http_requests_total[5m])) 73 ms 68 ms
default layout, one metric with 90,000 series, 18M samples bar / on(host) baz{host="h1"} 197 ms 17 ms
same, matcher keeps 50% bar / on(env) group_left foo{env="prod"} 231 ms 180 ms
same, matcher keeps 100% bar / on(env) group_left foo{env=~"prod|dev"} 402 ms 298 ms
same data, index_granularity = 64 (281k marks) bar / on(host) baz{host="h1"} 704 ms 17 ms
same, matcher keeps 50% bar / on(env) group_left foo{env="prod"} 715 ms 851 ms
400-term chain req{a="0"} + req{a="1"} + ... 0.10 s 0.10 s
800-term chain same 0.16 s 0.16 s
200-term balanced tree ((req{a="0"} + req{a="1"}) + ...) 1.83 s 1.83 s
21 terms with 21 different labels, measured before the duplicate-series guards were added req{a0="1"} + req{a1="1"} + ... 0.26 s 0.37 s
duplicate lim series only in a group the left side lacks req{instance="i1"} / on(instance) lim error error, as Prometheus
duplicate left series only in a group the right side lacks lim / on(instance) req{instance="i1"} error result, as Prometheus

Timings are medians of 21 runs (3 interleaved rounds of 7) with clickhouse local on a laptop under load 2 to 11; "master" is the same build with promql_push_down_label_matchers = 0, and a master build gave the same times within noise. A second run of the 90,000-series rows under higher load gave the same picture (keeps 50%: 349 -> 283 ms and 1055 -> 1258 ms; keeps 100%: 437 -> 458 ms).

Related: #121107
Related: #114131

Changelog category (leave one):

  • Performance Improvement

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

PromQL: label matchers are copied across binary operators for the labels the operator matches series by, so b / on(job) a{job="x"} reads only the series of b with job="x". As in Prometheus, duplicate left series of a one-to-one match in a group the right side does not have no longer fail the query. The new setting promql_push_down_label_matchers turns this off.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2074-master (included in 26.10 and later)

A binary operator only pairs series whose matching labels are equal, so a
matcher on such a label from one side also holds for the series used from
the other side. Copying it into the selectors of the other side lets
`rate(a{instance="x"}[5m]) / on(instance) rate(b[5m])` read only
b{instance="x"} instead of every series of b. The matchers go only through
selectors, offsets, subqueries, range functions, operators with a scalar and
aggregations grouping by the label; never through `or` or label functions,
and only from the left side to the right side of `unless`.

The pass removes duplicate matchers and skips expressions with more than 20
binary operators, because its work grows fast with their number. The setting
`promql_push_down_label_matchers` turns it off: a copied matcher turns a
whole-metric selector into a filtered one, which loses the whole-metric
primary-key range of a metric-clustered id and can be slower when the matcher
keeps most series of the metric.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... external Author is not a member of the ClickHouse organization labels Sep 29, 2026
@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Sep 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0d89935]

Summary: ✅


AI Review

Summary

This PR adds a PromQL AST pass that copies label matchers across binary operators and wires it behind the new promql_push_down_label_matchers setting. The duplicate-series safeguards and the scalar-comparison case look much better now, but one material optimization gap remains: common label-preserving wrappers like unary - and simple instant-vector functions still block pushdown, so a noticeable slice of the promised optimization surface is still missing.

Findings

⚠️ Majors

  • [src/Storages/TimeSeries/PrometheusQueryToSQL/pushDownLabelMatchers.cpp:81] getLabelPreservingArgument still stops at unary operators and at ordinary instant-vector functions, so queries like -req{job="api"} / on(job) lim and abs(req{job="api"}) / on(job) lim still read all of lim. That is still a contract gap for this PR: the description only calls out or, label functions, count_values, and absent as exclusions, but these common label-preserving wrappers remain unoptimized. Suggested fix: either extend the same label-preserving / metric-name-safety logic to UnaryOperator and the simple instant-vector functions that preserve labels, or explicitly narrow the advertised surface and document these exclusions.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: either make the pass traverse the common label-preserving wrappers it still stops at, or narrow the promised/user-facing surface so the current exclusions are explicit rather than surprising.

LLVM Coverage Report

Measured on commit 0d89935.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 153/166 (92.17%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 30, 2026
const auto & function_name = static_cast<const PrometheusQueryTree::Function *>(node)->function_name;
bool is_function_over_range = isFunctionOverRange(function_name) || isFunctionQuantileOverTime(function_name)
|| isFunctionPredictLinear(function_name);
if (!is_function_over_range)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This helper currently stops at any non-range Function node and has no UnaryOperator case, so common label-preserving wrappers like abs(req{job="api"}) / on(job) lim or -req{job="api"} / on(job) lim still read all of lim. That is a real gap for the feature as described here, because the PR text only calls out or, label functions, count_values, and absent as exclusions. Please either traverse unary / simple instant-vector wrappers too, or narrow the supported surface and add coverage for the intended limits.

…ushdown

The pushdown filtered out series that Prometheus still checks, so some
queries that fail in Prometheus returned a result instead. Prometheus
reports duplicate series on the "one" side of a vector match in every match
group (engine.go VectorBinop), and after a function or operator drops the
metric name (mergeSeriesWithSameLabelset), whether or not the other side
has that group.

Matchers are now copied into the "one" side only when it is an aggregation
by labels that are all matched on, which can't have duplicates, and through
a function or operator only when its input is one metric selected by name.
The many side is still filtered, which is safe: Prometheus checks it only in
matched groups. The ratio of two sums by the same labels and the fused
shapes keep the pushdown; a plain selector on the right no longer gets it.

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

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 4f55e56c-b8b2-4d83-b980-b1a2abc0da2e
  • MIRAI run: 1d9217ae-8fa2-4704-9b0e-803d6db69f26
  • PR check IDs:
    • clickbench_2822892_1790902716
    • clickbench_2822898_1790902716
    • clickbench_2822910_1790902716
    • tpch_adapted_1_official_2822921_1790902716
    • tpch_adapted_1_official_2822949_1790902716
    • tpch_adapted_1_official_2822963_1790902716

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0d8993581 with master 016a75cbf (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 4e774e919; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

10 object files changed (+55.68 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/TimeSeries/PrometheusQueryToSQL/pushDownLabelMatchers.cpp.o new 51.27 KiB +51.27 KiB

719 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

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

Median compile-time ratio to the baselines is ×1.23 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +10.7 s (+24%) in total before that adjustment.

Job report

valerypetrov and others added 2 commits September 30, 2026 14:09
A matcher copied into a side of a binary operator went on into any
vector operator nested in that side. There it removed groups the inner
operator matches, so `(lim / on(instance) req) / on(instance)
req{instance="i1"}` returned a result, while Prometheus fails on the
duplicate `lim` series of the inner match group `instance="i3"`. Now
only `and` and `unless`, which have no duplicate checks, pass matchers
inward. 05271 checks this query fails.

05271 also failed in CI for three test-only reasons:
- It counted every EXPLAIN line containing "Join", and one of them is
  there only with `enable_join_runtime_filters`, which CI randomizes.
  It now counts the Join steps.
- Under TSan, the 20-operator query nested its SQL too deep for the
  stack limit. The operator-cap queries are now balanced `and` trees,
  which keep the 20 and 21 operator counts.
- It runs about 70 PromQL queries and took over 180s in the flaky
  check, so it is tagged `long`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Under TSan a thread may use only 5% of its stack, and analyzing the
SQL of the 20-operator cap query exceeds that even with a balanced
operator tree (TOO_DEEP_RECURSION in the TSan targeted and flaky checks).
The ASan, MSan, debug and release flaky checks pass the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A comparison with a scalar and without `bool` keeps the metric name, so its
series can't become duplicates, and the single-metric guard isn't needed there.
Before this, `({__name__=~"req|opt"} > 0) and on(job) lim{job="api"}` read all
of `req` and `opt`; now it reads only their `job="api"` series. A comparison with
`bool` drops the metric name and keeps the guard.

The setting description now also says that only functions over a range and
operators with a scalar pass the matchers, while other functions and the unary
minus stop them, as the code and the 05271 selector lines already do.

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

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 016a75cbf

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Extended support (upstream engine tests) 90.44% 90.44% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 539 (+0) 0 -> 0 (+0) 0 -> 0 (+0)
Extended support (upstream engine tests) 662 -> 662 (+0) 67 -> 67 (+0) 3 -> 3 (+0)

Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream 3da2514eff5c.

Note: Prometheus compliance score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

@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.

Looks great!

@alexey-milovidov alexey-milovidov self-assigned this Oct 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into ClickHouse:master with commit 167559f Oct 10, 2026
149 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 11, 2026
…cache

Master's PromQL label matcher pushdown (ClickHouse#122972) added a setting next to this branch's two settings and a setting declaration in PrometheusHTTPProtocolAPI.cpp. Both sides are kept; the chunks copy the evaluation settings, so they push down matchers too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 11, 2026
Resolve conflicts with ClickHouse#122972 (promql_push_down_label_matchers) in
Settings.cpp, StoragePrometheusQuery.cpp and PrometheusHTTPProtocolAPI.cpp
by keeping both sides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 11, 2026
Resolve conflicts with ClickHouse#122972 (promql_push_down_label_matchers) in
Settings.cpp, PrometheusHTTPProtocolAPI.cpp and
PrometheusQueryEvaluationSettings.h by keeping both settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
0xTheProDev pushed a commit to 0xTheProDev/ClickHouse that referenced this pull request Oct 11, 2026
The test timed out at the 600 s per-test limit in 3 of the 6 master runs
of `Stateless tests (amd_msan, parallel, 2/3)` since it was added in
ClickHouse#122972 (ed166bd, 28bdac1, db91952). The no-random-settings diagnosis
reruns timed out as well, so it is not a randomized setting.

The failing jobs' query_log shows where the time goes: each of the 37
comparison queries spends 15-31 s of single-threaded CPU in analysis and
plan building under MSan, while reading 473 rows. The whole test takes
at most 189 s under ASan+UBSan and 29 s in release builds. Splitting the
file would keep the total MSan time, and each part would still be far
above the 60 s MSan cutoff of ClickHouse#115050.

Tag it `no-msan` like `01721_join_implicit_cast_long` (0d02623).
The test still runs on debug, release and ASan+UBSan builds, and other
PromQL tests keep the pushdown covered under MSan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 12, 2026
…out arguments

The PromQL parser builds an aggregation with any number of arguments,
including none, and the converter checks the arity only in `visitNode`.
Since ClickHouse#122972, `Converter::getSQL` runs `pushDownLabelMatchers` before
`visitNode`, and `getCommonMatchers` / `addMatchers` took
`aggregation.children.back()` unchecked. A query such as
`sum() / on(job) up{job="a"}` therefore called `back()` on an empty vector,
and the libc++ hardening assertion aborted the server (every build type
enables it: EXTENSIVE in Debug, FAST otherwise).

Add `getAggregatedArgument`, which returns nullptr for an aggregation
without arguments (and, as before, for `count_values`), and use it at both
sites. Such an aggregation now neither contributes nor receives matchers,
the tree is left as it is, and `visitNode` reports the existing
`CANNOT_EXECUTE_PROMQL_QUERY` arity error, exactly as with
`promql_push_down_label_matchers = 0`.

The test covers five routes to the empty `back()`: the left operand, a
`topk by` on the right, `quantile` under `and`, an aggregation nested in an
enclosing aggregation under `unless`, and a range function over a subquery.

Closes ClickHouse#125254

Co-Authored-By: Claude Opus 5.5 <[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... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements 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