Skip to content

TimeSeries: Disable the adaptive aggregator for queries generated from PromQL - #128764

Merged
vitlibar merged 1 commit into
ClickHouse:masterfrom
vitlibar:timeseries-bucketed-samples-tuning
Nov 3, 2026
Merged

vitlibar merged 1 commit into
ClickHouse:masterfrom
vitlibar:timeseries-bucketed-samples-tuning

Conversation

@vitlibar

@vitlibar vitlibar commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Disable the adaptive aggregator for queries generated from PromQL

The grid aggregation groups by time series with a few rows per series and a state that keeps every sample of its windows, so the adaptive aggregator's byte bound freezes each thread's table after a few series and stages the remaining heavy rows for the merge.

c01 at S: sum by (namespace) (rate(container_cpu_usage_seconds_total{job="cadvisor", image!=""}[5m])), 30 days at step 15 m; 400 series, 4 threads, 400/4 = 100 series per thread

case adaptive aggregator states staging buffers notes
one row per sample on (freeze after 4 series, then thaw after staging 1 series) 480 MB total, 120 MB per thread 65,536 x 24 B = 1.5 MB per thread, 6 MB total, until the merge drains them 0.4% of the rows are staged
bucketed samples on (freeze after 4 series, then staging 91 series, then thaw at 95 series) 480 MB total, but 4 series per thread built in the local table and 91 built in the merge phase 65,536 x 3.85 KB = 252 MB per thread, about 1 GB total, held until drained 91% of the rows are staged
bucketed samples off (no freeze) 480 MB total, 120 MB per thread 0

So for "one row per sample" design the adaptive aggregator was meaningless, but harmless, and for "bucketed samples" it became a problem, so this PR disabled it.


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

Version info

  • Merged into: 26.11.1.1200-master (included in 26.11 and later)

The grid aggregation groups by time series with a few rows per series and a state
that keeps every sample of its windows, so the adaptive aggregator's byte bound freezes
each thread's table after a few series and stages the remaining heavy rows for the merge.
@vitlibar vitlibar added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5b37503]

Summary: ✅


AI Review

Summary

The PR disables adaptive aggregation by default inside generated PromQL SQL, preserving explicit overrides and sharing the settings helper between SQL table functions and HTTP queries. ⚠️ Request changes: the claimed performance improvement needs measurements covering the affected query path and the scope of the override.

Findings

⚠️ Majors

  • StoragePrometheusQuery.cpp:198–199: The performance claim is unverified. The override disables adaptive aggregation throughout generated SQL, including grouped PromQL operators, while the motivation concerns sample-heavy grid aggregation. No before/after measurements are provided. The sample-heavy timeseries_to_grid_* benchmarks call aggregates directly and bypass this helper. Supply an end-to-end comparison demonstrating the benefit and checking a representative grouped query.
Tests
  • ⚠️ Compare prometheusQueryRange before/after, or with adaptive aggregation explicitly enabled/disabled, using fixed max_threads and enough samples per series to reach the byte freeze threshold. Report elapsed time and peak memory, including a representative grouped PromQL case. A focused performance test or completed relevant CI measurements would close this evidence gap.
Missing context / blind spots
  • ⚠️ All 12 performance comparison shards were PENDING in the CI report. No local ClickHouse binary/build was available for independent measurements.
Final Verdict

⚠️ Request changes. Provide reproducible performance evidence for the generated-query path and a representative grouped query before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 2, 2026
@EmeraldShift

Copy link
Copy Markdown
Contributor

I wonder if there's a long-term way for the adaptive aggregator to get.. more adaptive to this use case? It seems reasonable for PromQL queries, but I wonder if there are other use case with a similar problem who would catch a regression

@nikitamikhaylov

Copy link
Copy Markdown
Member

@nihalzp FYI

Comment on lines +198 to +199
if (!context.getSettingsRef()[Setting::enable_adaptive_aggregator].changed)
context.setSetting("enable_adaptive_aggregator", false);

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.

⚠️ Measure the generated-query path before changing its aggregation default

This disables adaptive aggregation for every aggregation in generated PromQL SQL, including grouped operators, whereas the rationale describes sample-heavy grid aggregation specifically. The PR provides no before/after measurements demonstrating the claimed performance improvement or checking the broader override. The sample-heavy timeseries_to_grid_* benchmarks invoke aggregates directly, so they bypass this helper and cannot measure this change.

Please provide a reproducible comparison through prometheusQueryRange, with enough samples per series to reach the byte freeze threshold at a fixed max_threads, reporting elapsed time and peak memory before/after (or with adaptive aggregation explicitly enabled/disabled). Include a representative grouped PromQL query to check the wider scope. A focused performance test or completed CI results covering those workloads would supply the missing evidence.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5b3750394 with master 4944813cc (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e8ca7d358; 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.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master e8ca7d358

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

@nihalzp

nihalzp commented Nov 3, 2026

Copy link
Copy Markdown
Member

This is a known problem of the faster adaptive aggregator design. The fix, a cell-only freezing of local table, is planned which would avoid unnecessary staging. We can disable for now and I will enable it with the fix.

Meanwhile, @groeneai let's benchmark different queries relevant to this PR to document the slowdowns with adaptive aggregator.

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm benchmarking PromQL queries through prometheusQueryRange with the adaptive aggregator on and off (range functions over sample-heavy series, plus grouped aggregations), at several max_threads, and will post elapsed time and peak memory here shortly.

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Benchmark of prometheusQueryRange with enable_adaptive_aggregator = 0 vs 1, on this PR's amd_release build (5b375039), shared 384-vCPU x86 host. Median of 5 warm runs, FORMAT Null, peak memory from query_log; split-half noise of one arm is 5% median, 13% p90. Results (hash of tags + samples, 16 threads) are identical in both arms. The PR's default gives the same numbers as = 0 (no AdaptiveAggregationLocalFreezes), and an explicit = 1 still turns it on.

Data: default TimeSeries tables (15-minute buckets in the recent samples table, 1-hour in the main one), one counter m, labels job (10 values), dc (4), instance (unique):

  • A: 20k series, 24h at 15s, queried over 24h, step 60s
  • B: 200k series, 2h at 15s, queried over 1h, step 15s
  • C: 2k series, 24h at 1s, queried over 24h, step 60s

A and B: no difference beyond noise for all six queries below at 4/16/64 threads (time 0.92x..1.15x, memory 1.00x..1.01x).

C, time ratio on/off (memory ratio where it is not ~1x). "main" is time_series_prefer_recent_samples_table = 0, i.e. ranges older than the recent table's TTL:

Query recent, 4 thr 16 64 main, 4 thr 16 64
rate(m[5m]) 1.11 1.16 1.05 1.37 1.36 1.18
sum by (job) (rate(m[5m])) 1.18 1.12 1.11 1.46 1.38 1.14
avg_over_time(m[5m]) 1.09 1.09 1.11 1.48 1.33 1.33
quantile_over_time(0.9, m[5m]) 1.17 1.14 1.13 1.30 1.36 1.35
m 3.15 (14x mem) 2.03 (9.9x) 1.13 (3.6x) 3.93 (16x) 1.99 (8.3x) 0.98
sum by (dc) (m) 3.63 (14x) 2.25 (9.7x) 1.36 (3.6x) 4.37 (18x) 2.26 (9.2x) 1.06 (1.3x)

Worst case, sum by (dc) (m) on the main table at 4 threads: 273 ms / 136 MiB -> 1194 ms / 2.4 GiB.

For the range functions the grid states hold every window sample in both arms (~3 GiB either way), so only time grows. For the selector (timeSeriesLastToGrid) on the main table at 4 threads, the = 0 peak is 156 MiB, while the = 1 peak is roughly the raw samples of the staged rows: 43,506 of 50,000 input rows staged, x 3,600 samples x 16 bytes = 2.3 GiB. The effect shrinks with max_threads, as the 4 MiB bound is per thread: 1,113 rows staged at 64 threads. AdaptiveAggregationStagedBytes stays at about 1 MiB here, since it counts key bytes only.

Reproducer (dataset C, worst case)
SET enable_time_series_table = 1;
CREATE TABLE ts_c ENGINE = TimeSeries;
INSERT INTO ts_c (metric_name, tags, samples)
SELECT 'm', map('job', 'job' || toString(number % 10), 'dc', 'dc' || toString(number % 4), 'instance', 'inst' || toString(number)),
       arrayMap(i -> (toDateTime64(1793696400 - 86400 + i, 3), toFloat64(i * (1 + number % 5))), range(86401))
FROM numbers(2000)
SETTINGS max_block_size = 50, max_insert_block_size = 50, min_insert_block_size_rows = 0, min_insert_block_size_bytes = 0;

SELECT * FROM prometheusQueryRange(ts_c, 'sum by (dc) (m)', 1793696400 - 86400, 1793696400, 60)
SETTINGS max_threads = 4, time_series_prefer_recent_samples_table = 0, enable_adaptive_aggregator = 1
FORMAT Null;
-- 1313 ms, 2.36 GiB, 43,516 staged records; with enable_adaptive_aggregator = 0: 282 ms, 135 MiB

@vitlibar
vitlibar added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit 4d76414 Nov 3, 2026
179 checks passed
@vitlibar
vitlibar deleted the timeseries-bucketed-samples-tuning branch November 3, 2026 11:49
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
@nihalzp

nihalzp commented Nov 5, 2026

Copy link
Copy Markdown
Member

@groeneai Confirm whether

fixes the regressions relevant to this PR and the queries previously mentioned by you.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

Yes. On dataset C, the only one that regressed, #129565 removes all of it: with enable_adaptive_aggregator = 1 every query runs as fast as with = 0, at the same peak memory, and no table freezes (AdaptiveAggregationLocalFreezes and AdaptiveAggregationStagedRecords are 0 in every run). Its merge base still reproduces the numbers above.

Time ratio = 1 / = 0, range over the recent and main table x 4/16/64 threads, memory ratio where it is not ~1x:

Query merge base 3b0d42e9 #129565 1be96c48
rate(m[5m]) 1.21..1.47 0.92..1.06
sum by (job) (rate(m[5m])) 1.16..1.68 0.93..1.06
avg_over_time(m[5m]) 1.18..1.73 0.92..1.03
quantile_over_time(0.9, m[5m]) 1.16..1.55 0.96..1.02
m 1.01..3.43 (memory up to 15x) 0.84..1.04
sum by (dc) (m) 1.13..4.03 (memory up to 18x) 0.90..1.05

Worst case, sum by (dc) (m) on the main table at 4 threads: merge base 294 ms / 137 MiB -> 1186 ms / 2.4 GiB (43,533 staged records); #129565 309 ms / 137 MiB -> 309 ms / 132 MiB.

A: no difference on either build (0.93..1.09). B: on the merge base the range functions at 16 threads are up to 1.18x slower with = 1 (all 16 tables freeze, 187k staged records); on #129565 they are 0.91..1.08x, with 2 to 4 tables freezing by the key count. The = 0 path is unchanged (geomean #129565 / merge base 0.96..1.05 per dataset). Results are identical across both builds and both arms (sum by (job) (rate(m[5m])) after rounding to 9 digits, as its float sums differ run to run within one arm).

#129565 does not touch StoragePrometheusQuery.cpp, so PromQL keeps the aggregator off by default. When re-enabling: passed as an HTTP parameter or a clickhouse-client flag, enable_adaptive_aggregator = 1 does not appear in query_log.Settings and the run has 0 freezes (= 0 does appear), so the changed check there turns it off; only a query-level SETTINGS clause turns it on today. I used that clause for every = 1 run.

Method: local release builds (CMAKE_BUILD_TYPE=None, no ThinLTO) of #129565's head and its merge base, as the PR's CI builds were skipped after Build (arm_tidy, 2/4) failed. Same host, data and queries as above, median of 5 warm runs with the arms interleaved, peak memory from query_log; split-half noise of one arm 2.6% median, 8% p90.

@nihalzp

nihalzp commented Nov 13, 2026

Copy link
Copy Markdown
Member

@groeneai #129565 has been merged. Revert this PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm preparing the revert of this PR on current master; I'll follow up here with the PR link (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

The revert is open: #131270. On the amd_release build of 414302af (#129565 in, #128764 still in), the six PromQL queries of the earlier benchmark run with the adaptive aggregator on at 0.86..1.13x the time and 0.70..1.03x the peak memory of off, with the same results.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 13, 2026
…or override

Restore the helper that ClickHouse#128764 introduced and its two call sites (the
prometheusQuery* table functions and the Prometheus HTTP API), and remove
only the part of it that disabled the adaptive aggregator, as asked in
review. The helper keeps setting `enable_materialized_cte` and
`empty_result_for_aggregation_by_empty_set` for the generated SQL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 13, 2026
…ated from PromQL"

This reverts commit 4d76414 (ClickHouse#128764),
reversing changes made to 8886954.

ClickHouse#129565 fixed the staging of the adaptive aggregator that made the grid
aggregation of the SQL generated from PromQL slower, so that SQL can use
the aggregator again.

The conflict in the includes of PrometheusHTTPProtocolAPI.cpp is resolved
by keeping `Server/PrometheusMetricsWriter.h`, added later by ClickHouse#125250.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh Bot pushed a commit that referenced this pull request Nov 20, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 127836 124816 Revert "Avoid building stream names and substreams cache keys for every block in MergeTreeReaderWide"
Changelog-revert: 128706 116083 Revert "Fit the insert pipeline and merges into a small server's memory"
Changelog-revert: 128760 128658 Revert "Prewarm macOS code signature verification of the clickhouse binary after linking"
Changelog-revert: 128947 127422 Revert "[GPU] `GDeflate` compression codec on the CPU"
Changelog-revert: 129099 128947 Revert "Revert "[GPU] `GDeflate` compression codec on the CPU""
Changelog-revert: 129310 127149 Revert "Mark a query as cancelled in the process list when its TCP client cancels it"
Changelog-revert: 129311 129310 Revert "Revert "Mark a query as cancelled in the process list when its TCP client cancels it""
Changelog-revert: 129862 129425 Revert "Add 7 tests for coverage gaps in 5 components"
Changelog-revert: 129863 129862 Fix `GLOBAL IN` in projection `WHERE` with parallel replicas; restore coverage tests
Changelog-revert: 129986 122871 Revert "Search long integer slices in 512-byte chunks on AArch64 in `hasAll` and `hasAny`"
Changelog-revert: 130046 129986 Revert "Revert "Search long integer slices in 512-byte chunks on AArch64 in `hasAll` and `hasAny`""
Changelog-revert: 130368 114729 Revert "CI: run the full test suite only when review threads are resolved"
Changelog-revert: 130509 130368 Revert "Revert "CI: run the full test suite only when review threads are resolved""
Changelog-revert: 130531 114923 Revert "Make a table read by a scalar subquery in a CONSTRAINT a loading dependency"
Changelog-revert: 131043 129464 Revert "Sync shared files changed by the private `AmberMap` PR"
Changelog-revert: 131045 130793 Revert "Fix wrong ORDER BY ... LIMIT results on Delta Lake tables with column mapping"
Changelog-revert: 131270 128764 Re-enable the adaptive aggregator for queries generated from PromQL
Changelog-revert: 131424 122826 Revert "Forbid renaming the source of incremental refreshable views"
Changelog-revert: 131562 131454 Revert "Build the symbol index in the background at server startup"
Changelog-revert: 131638 131562 Revert "Revert "Build the symbol index in the background at server startup""
Changelog-revert: 131691 130864 Revert "Use one source instead of N for parallel_inserts of AzureQueue/S3Queue"
Changelog-revert: 131765 119685 Revert "Enable `-mbranch-protection=pac-ret` on ARM"
Changelog-deleted-entry: 116083 [Performance Improvement] [section] * Reduce memory use for `INSERT` and background merges on servers with a few GiB of RAM. Write buffers, insert squashing, the `Parquet` reader and merge selection now scale with `max_server_memory_usage`, avoiding `MEMORY_LIMIT_EXCEEDED` during wide-table inserts and merges that repeatedly fail without reducing the part count. New `MergeTree` settings `max_memory_ratio_to_activate_adaptive_write_buffer` and `merge_memory_estimate_per_source_part_column` control adaptive write buffers and merge selection, respectively; set either to `0` to disable that adjustment. [#116083](#116083) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 119685 [Build/Testing/Packaging Improvement] [raw] * Build the `C` and `C++` code of the ARM binaries with `-mbranch-protection=pac-ret`, which signs the return address so that overwriting it on the stack cannot redirect control flow; the AArch64 `.S` sources that key off `__ARM_FEATURE_PAC_DEFAULT` opt into the same signing. Sanitizer builds are excluded, because the sanitizer runtimes do not strip the signature when they unwind. [#119685](#119685) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 122826 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Forbid renaming the source of incremental refreshable views closes #[#120082](#120082). [#122826](#122826) ([Smita Kulkarni](https://github.com/SmitaRKulkarni)).
Changelog-deleted-entry: 128658 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Prewarm macOS code signature verification of the clickhouse binary after linking. [#128658](#128658) ([Azat Khuzhin](https://github.com/azat)).
Changelog-deleted-entry: 128764 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Disable the adaptive aggregator for queries generated from PromQL. [#128764](#128764) ([Vitaly Baranov](https://github.com/vitlibar)).
Changelog-deleted-entry: 129464 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Sync shared files changed by the private `AmberMap` PR. [#129464](#129464) ([Miсhael Stetsyuk](https://github.com/mstetsyuk)).
Changelog-deleted-entry: 130793 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed wrong results of `ORDER BY ... LIMIT` on a Delta Lake table with column mapping when a renamed column has the name that another column is stored under: the top-K dynamic filter (`use_top_k_dynamic_filtering`) compared the other column against the threshold and dropped rows of the true result. [#130793](#130793) ([Groene AI](https://github.com/groeneai)).
Changelog-deleted-entry: 130864 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Use one source instead of N for parallel_inserts of AzureQueue/S3Queue. [#130864](#130864) ([Azat Khuzhin](https://github.com/azat)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... 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.

6 participants