Skip to content

perf(promql): Read only the needed tags columns for Prometheus label metadata. - #127095

Open
JTCunning wants to merge 3 commits into
ClickHouse:masterfrom
JTCunning:jtcunning/prom-label-metadata-column-scan
Open

JTCunning wants to merge 3 commits into
ClickHouse:masterfrom
JTCunning:jtcunning/prom-label-metadata-column-scan

Conversation

@JTCunning

@JTCunning JTCunning commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Each endpoint now aggregates directly over the tags table and reads only the columns it needs:

  • /api/v1/labels reads the metric_name column, the size subcolumn of each tags_to_columns column and the tags.keys subcolumn: SELECT groupUniqArrayArray(arrayConcat(if(metric_name != '', ['__name__'], []), ..., tags.keys)) FROM <tags table>. A tags table without subcolumns reads mapKeys(tags) instead.
  • /api/v1/label/__name__/values reads the metric_name column only.
  • /api/v1/label/<tag>/values reads the dedicated column of the tag, or tags[<tag>] for a tag stored in the map.

The matchers and the time bounds are applied by the same WHERE clause and time ranges join as the series ids query, through the new StorageTimeSeriesSelector::makeSelectFromTagsTable. Each selector produces one array of unique strings, so the memory used depends on the number of distinct label names or values and not on the number of matched series.

The query runs with prefer_column_name_to_alias = 1, because a tags_to_columns column may be named like the alias of the aggregated array, and with optimize_functions_to_subcolumns = 1. The query context becomes a query context of its own, so system.query_log records the tables and the columns the query reads.

Measured on one host with a TimeSeries table of 1,000,000 series (200 metric names, 8 tags per series, one part, 84.59 MiB on disk). The values are medians of 5 runs of read_bytes, memory_usage and query_duration_ms from system.query_log. The before binary is the merge base, the after binary is the head of this branch.

call before after
/api/v1/labels 196.6 MB read, 791 MB peak, 867 ms 18.0 MB read, 164 MB peak, 31 ms
/api/v1/label/name/values 196.6 MB read, 799 MB peak, 864 ms 1.0 MB read, 1.6 MB peak, 4 ms
/api/v1/label/job/values 196.6 MB read, 799 MB peak, 881 ms 9.5 MB read, 66 MB peak, 18 ms
/api/v1/label/instance/values?match[]=metric_7 3.2 MB read, 11.6 MB peak, 9 ms 0.33 MB read, 6.9 MB peak, 5 ms
/api/v1/label/instance/values?match[]=metric_7&start=...&end=... 4.0 MB read, 17.9 MB peak, 14 ms 1.6 MB read, 12.1 MB peak, 13 ms
/api/v1/labels?match[]={job="job_3"} 19.5 MB read, 67.9 MB peak, 26 ms 2.3 MB read, 1.8 MB peak, 6 ms

The bounded request reads 32,768 rows on both builds: the time ranges table is read over the id range of the selected metric, as in the series ids query. The responses of both builds were byte-identical for every call.

Changelog category (leave one):

  • Experimental Feature

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

PromQL metadata endpoints now produce purpose-built read queries from the tags table.


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

The /api/v1/labels and /api/v1/label/<name>/values endpoints of the
Prometheus HTTP API built their result from the series ids query: the inner
query registered the tags of every matched series with `timeSeriesStoreTags`
and the outer query decoded them with `timeSeriesIdToTags`. This read the
whole tags table (`id`, `metric_name`, `tags` and the dedicated columns) and
held the tags of every matched series in memory. Grafana calls these
endpoints without a selector when it loads a dashboard, so each call scanned
and materialized the whole tags table.

Each endpoint now aggregates directly over the tags table and reads only the
columns it needs:

- /api/v1/labels reads the `metric_name` column, the `size` subcolumn of
  each `tags_to_columns` column and the `tags.keys` subcolumn:
  `SELECT groupUniqArrayArray(arrayConcat(if(metric_name != '', ['__name__'], []), ..., tags.keys)) FROM <tags table>`.
  A tags table without subcolumns reads `mapKeys(tags)` instead.
- /api/v1/label/__name__/values reads the `metric_name` column only.
- /api/v1/label/<tag>/values reads the dedicated column of the tag, or
  `tags[<tag>]` for a tag stored in the map.

The matchers and the time bounds are applied by the same WHERE clause and
time ranges join as the series ids query, through the new
`StorageTimeSeriesSelector::makeSelectFromTagsTable`. Each selector produces
one array of unique strings, so the memory used depends on the number of
distinct label names or values and not on the number of matched series.

The query runs with `prefer_column_name_to_alias = 1`, because a
`tags_to_columns` column may be named like the alias of the aggregated
array, and with `optimize_functions_to_subcolumns = 1`. The query context
becomes a query context of its own, so `system.query_log` records the
tables and the columns the query reads.

`__name__` and the tags of `tags_to_columns` are read from their column
only. /api/v1/labels reports every key of the `tags` map, including a key
with an empty value. /api/v1/label/<name>/values omits an empty value, as
before.

Integration tests check the columns each query reads with
`system.query_log.columns`, a `tags_to_columns` column named `labels` with a
matcher on it, and rows inserted directly into the tags table.

Measured on one host with a `TimeSeries` table of 1,000,000 series (200
metric names, 8 tags per series, one part, 84.59 MiB on disk). The values
are medians of 5 runs of `read_bytes`, `memory_usage` and
`query_duration_ms` from `system.query_log`:

| call | before | after |
| --- | --- | --- |
| /api/v1/labels | 196.6 MB read, 795 MB peak, 892 ms | 18.0 MB read, 180 MB peak, 31 ms |
| /api/v1/label/__name__/values | 196.6 MB read, 797 MB peak, 898 ms | 1.0 MB read, 1.6 MB peak, 4 ms |
| /api/v1/label/job/values | 196.6 MB read, 796 MB peak, 910 ms | 9.5 MB read, 72 MB peak, 18 ms |
| /api/v1/label/instance/values?match[]=metric_7 | 3.19 MB read, 11.6 MB peak, 9 ms | 0.33 MB read, 6.9 MB peak, 5 ms |
| /api/v1/labels?match[]={job="job_3"} | 19.5 MB read, 72 MB peak, 25 ms | 2.3 MB read, 1.8 MB peak, 6 ms |

The responses of both builds were byte-identical for every call.
@JTCunning JTCunning 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 Oct 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e730e13]

Summary: ✅


AI Review

Summary

PR #127095 aggregates Prometheus label metadata directly from the required tags-table columns, reducing reads and memory use. No actionable findings remain. The previously reported metric ID pruning regression is fixed, with focused regression coverage.

Missing context / blind spots
  • ⚠️ Full CI for head e730e13e8976f18d54ab5d758fc4a7df40c6fcf2 is still running. The preceding commit 94d12bcac41685a603d1afe378faaded7b8f3956 passed all 65 label-endpoint integration tests. Its release binary also passed 88 local endpoint assertions across eight table configurations; both modified C++ implementation files are identical at the reviewed head.
Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Oct 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e730e13e8 with master 378e52264 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of b29785d13; 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

6 object files changed (+50.16 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp.o 284.47 KiB 329.46 KiB +44.99 KiB (+15.82%)

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

11 translation units recompiled, 30 s compile time in total, 11 of them have a recent master baseline.

Job report

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 21, 2026
…eplicas

Same mechanism as 02317_distinct_in_order_optimization. Since ClickHouse#114550 the
final DISTINCT hash-partitions its input (DistinctStep::tryScatterStreams)
when it has more than one input stream and max_threads > 1. Under parallel
replicas the initiator's final DISTINCT has several input streams (local
plan plus remote replicas), so the two rows of `test_string` can land in
different partitions and reach the client in either order. CI's own rerun
with the failing run's settings reproduced it 19 of 446 times on PR ClickHouse#127095;
the test had 0 failures in 33352 runs before the merge.

The returned set is unchanged and a DISTINCT without ORDER BY has no
defined row order, so pin it with ORDER BY c1. The reference is unchanged.
With ORDER BY the final DISTINCT runs after the sort and keeps the input
order, which forbids the scatter.

The 49622 path stays covered (in-order DISTINCT with an empty-string
non-sorted column, preliminary and final): the preliminary DISTINCT is
still planned directly above the in-order read with the `c1` prefix, and
the final DISTINCT now also runs in order over `c1`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…abel metadata

`makeSelectFromTagsTable` passed no metric id ranges to the time ranges table join, so a request to `/api/v1/labels` or `/api/v1/label/<name>/values` with `start` or `end` read the time ranges of every metric. `makeSelectIDsQuery` derives the ranges of the selected metrics with `tryGetTimeSeriesIDRanges`; `makeSelectFromTagsTable` now takes `table_id_type` and does the same, so the time ranges table is read over the id ranges of the selected metrics and the series with ids outside the ranges are kept without filtering by time.

The integration tests check the generated query for a request with one metric and time bounds: the time ranges subquery carries the id range of the metric, and the outer WHERE keeps the ids outside the range.
@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master b29785d13

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Extended support (upstream engine tests) 93.17% 93.17% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 539 (+0) 0 -> 0 (+0) 0 -> 0 (+0)
Extended support (upstream engine tests) 682 -> 682 (+0) 16 -> 16 (+0) 34 -> 34 (+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

This branch has not been deployed

No deployments
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants