Repository navigation
Split long PromQL range queries by interval and cache completed chunks - #122585
valerypetrov wants to merge 42 commits into
Conversation
With promql_range_query_split_interval > 0, /api/v1/query_range evaluates a query at least that long in chunks, one after another, and merges the series of the chunks in the order of the unsplit query. Chunks start at the first step at or after each multiple of the interval since the Unix epoch, so the same chunks repeat when a dashboard is refreshed, and no step is lost or repeated. A query using @ start() or @ end() is not split. With promql_range_query_cache_min_age > 0, a chunk ending earlier than that many seconds ago runs with use_query_cache = 1 and query_cache_nondeterministic_function_handling = 'save' (the timeSeries* functions are non-deterministic only because of per-query state), and a newer chunk runs without the query cache. A query with a negative offset or an @ modifier can read samples after its chunk, so it is not cached. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The integration test compares the split and unsplit responses byte for byte for several queries and ranges, checks the number of executed chunk queries in system.query_log, and checks that a repeated request reads all chunks but the newest from the query cache. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The key of a query cache entry hashes the changed settings, so a chunk cached with one promql_range_query_cache_min_age was never found again with another. Neither setting changes the result of a chunk, so reset both in the context of the chunk query. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ntervals The next chunk start is computed in Int128 one chunk at a time, so a huge step no longer overflows into an endless loop that builds an unbounded list of chunks. max_execution_time now applies to the whole request, checked between chunks. Only chunks covering a whole interval are cached, since a chunk cut by the start or the end of a sliding range is never requested again. Timestamps before 1970 round down to the right boundary. The test waits for the query_log row of the unsplit query, which is written after the response. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Such a query fails at once without splitting, while its chunks would each pass the limit and run until the time limit or KILL QUERY. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [ebdf20c] Summary: ❌
AI ReviewSummaryReviewed PR #122585 at Missing context / blind spots
Final VerdictStatus: ✅ Approve |
A chunk copied `use_query_cache` from the request when `promql_range_query_cache_min_age` was 0, so a request with `use_query_cache = 1` cached every chunk, including the newest one and the chunks of queries with a negative offset or an `@` modifier. Now a chunk uses the query cache only when it covers a whole interval, is older than the minimum age and reads no later samples. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`max_result_rows`, `max_result_bytes`, `limit` and `offset` apply to the whole result, but each chunk of a split query applied them to its own result: the merged response could exceed the limits, and a truncated or offset result differed from the unsplit one. A post-merge check can't reproduce block-granular `result_overflow_mode = 'break'` or the byte count of the unsplit result, so such a query isn't split. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The chunks are converted to SQL one by one, so a check of the converter that depends on the length of the range, like a limit on the number of points per series, would see only one chunk. Converting the whole request first makes a split query fail on a check of the converter as the unsplit one does. Checks made during execution still see one chunk. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A chunk eligible for the query cache ran with `use_query_cache = 1`, and executeQuery refuses that when any overflow mode is not 'throw', so a split request failed where the unsplit one succeeded. Such a chunk could also be cut short by its limit, so it now runs without the query cache. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The settings `select`, `order`, `sort` and `filter` wrap the SQL of each chunk, so a split query applied them to each chunk: `order` and `sort` broke the merge of the chunks, which expects every chunk sorted by tags, and repeated series, while `select` and `filter` saw only one chunk of each series. Like the result limits, they now keep the query from being split. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each chunk checked `max_rows_to_group_by`, `max_rows_to_sort`, `max_bytes_to_sort`, `max_rows_in_join` and `max_bytes_in_join` on its own rows, so a split query passed a limit the unsplit query exceeds, and with a non-throw overflow mode each chunk was cut separately. The overflow modes act only when these limits are set, so a query with any of them isn't split. The grid limit of a subquery is checked during execution and still applies to each chunk; this is documented. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each chunk of a split range query is a separate query, so it counts as one query against quotas, and the docs now also say which queries are not split. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…le query Each chunk is a separate query, so `max_rows_to_read`, `max_bytes_to_read`, their `_leaf` variants, `max_execution_time`, `max_execution_time_leaf` and `max_estimated_execution_time` would start again for each chunk and a split request could exceed them several times. Such a query is now executed at once, like a query with a GROUP BY, sorting or JOIN limit. The check of `max_execution_time` between the chunks is not needed anymore. The documentation no longer says that splitting bounds the peak memory: it bounds the memory to evaluate the query, but the results of all chunks are kept until they are merged into the response. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…chunks again The time limit of the whole request was already checked between the chunks, and a deployment setting `max_execution_time` in a profile would otherwise never split. Only the read limits, which have no check across the chunks, disable splitting. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes10 object files changed (+70.36 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units137 translation units recompiled, 742 s compile time in total, 137 of them have a recent master baseline. |
A cached chunk runs with `query_cache_nondeterministic_function_handling = 'save'`, so with `query_cache_for_subqueries = 1` from the request or a profile its subqueries were cached too. The subqueries that fill and read the tags of the query then came from another query: after `node_load1`, `node_cpu_seconds_total or node_load1` returned 11 of 12 series, and the other order failed with "Group 2 is out of bounds". A cached chunk now turns `query_cache_for_subqueries` off. Settings starting with `query_cache_` are not a part of the key in the query cache. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The speed limits (min_execution_speed, max_execution_speed, their byte variants and max_estimated_execution_time) are checked from the start of one query. Each chunk of a split range query is a separate query, so the limits started again for every chunk and a request the whole query would reject could pass. Such a query is now executed at once, like one with a read limit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Prometheus 3.5.0 accepts `~invalid` as a valid label name. Expect the `label_replace` and `label_join` cases to succeed so the compliance test compares their results with ClickHouse instead of counting reference mismatches. Observed report: ClickHouse#122585 (comment) Related: ClickHouse#118190
Each chunk of a split range query is a separate query with the whole max_execution_time, and the limit of the request was checked only after a chunk finished. A chunk that started just before the limit could run for almost the whole limit again, so a request could take nearly twice max_execution_time. The chunk's executor now wakes every 100 ms to check the limit of the request, and throws or stops as timeout_overflow_mode says. The chunks keep the request's max_execution_time rather than the time left, because a changed setting is a part of the query cache key and a cached chunk would never be found again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mit together With `timeout_before_checking_execution_speed = 0` the speed checks start with the first rows of a query, so `max_estimated_execution_time` and `max_execution_speed` would start again for each chunk of a split query. The new case sets them together with the split interval and checks that the request runs as one query. The documentation now names the speed limits, like the description of the setting. Co-Authored-By: Claude Opus 5.5 <[email protected]>
max_rows_in_set and max_bytes_in_set would see the sets of one chunk at a time, and the max_network_bytes counter would start again for each chunk, like the other limits that already keep a range query whole. The merge of the chunks now checks the time limit before the samples of each chunk and before the footer, so one large series cannot run far past the limit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master is at version 26.11 now, and the settings history check requires a setting added by a pull request to have a record of the current version. Both settings are new, so their only record moves from 26.10 to 26.11. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…imits `additional_result_filter` is applied to the final result like `filter`, so on split chunks it saw at most one chunk of each series and could drop a series the whole query keeps. `max_rows_to_transfer` and `max_bytes_to_transfer` restart for each chunk's GLOBAL subqueries, like the set and network limits. Both now keep the query unsplit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ter walk `_list_commits_page` ran one `gh api repos/ClickHouse/ClickHouse/commits` call and raised on the first non-zero exit or timeout, and the per-TU master first-parent walk makes ~20 such calls per job. GitHub fails single requests (HTTP 503 and 504, a body cut short so `--jq` reports `unexpected end of JSON input`, a stalled body) while the requests around them succeed, so one blip errored the whole check: 9 jobs on 9 PRs between 2026-10-03 and 2026-10-14, the failing anchors 11-15 days deep in walks whose earlier fetches had just succeeded, and the same commits passing on other runs. Retry the listing up to 3 times (after 5 s, then 10 s), keeping the 120 s per-call timeout. A timeout, an HTTP 5xx or 429, or a failure whose stderr names no HTTP status is retried; any other 4xx (unknown sha, permissions) fails at once, since `gh` reports an HTTP error as `gh: <message> (HTTP <status>)`. After the last attempt the error propagates as before, so the walk stays fail-close as the `extend_master_shas` docstring requires. The praktika `GH` helpers retry but pass no subprocess timeout, which ClickHouse#115201 kept on this call site on purpose. CI reports: - https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124959&sha=1d61eebf3fe5ed809d4811ea947169074a3e1712&name_0=PR&name_1=Build%20profile%20diff (ClickHouse#124959) - https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125328&sha=ab772cc3b97c2e6777f2ef60723bcbeb5a5f29e3&name_0=PR&name_1=Build%20profile%20diff (ClickHouse#125328) - https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122585&sha=bf8b2d2470663e1b5703c2014b7887fe2d5dd239&name_0=PR&name_1=Build%20profile%20diff (ClickHouse#122585) - https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119371&sha=88edddd16dcd4250ac56e1642f964a03763097f4&name_0=PR&name_1=Build%20profile%20diff (ClickHouse#119371) Co-Authored-By: Claude Opus 5.5 <[email protected]>
The chunks of a split range query were each finished before the merge of their results started, so during the merge the request had no entry in system.processes and KILL QUERY could not find or stop it. The last chunk now stays in the process list until the response is written, and the merge checks whether it was killed, like the request time limit. A pauseable failpoint before the merge lets the new integration test kill the request while it merges. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cache Co-Authored-By: Claude Opus 5.5 <[email protected]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
…cache # Conflicts: # src/Core/Settings.cpp # src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp
…gs are set Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…cache Master moved the PromQL query settings into StoragePrometheusQuery::applySettingsForPrometheusQuery, so makeQueryContext now calls it and range-query chunks also get its settings. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`Converter::getSQL` is `[[nodiscard]]` in master now. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Context nodiscard Master is now 26.12, so the settings history check requires the records of promql_range_query_split_interval and promql_range_query_cache_min_age under that version. clang-tidy's modernize-use-nodiscard, now an error on master, flags PrometheusHTTPProtocolAPI::makeQueryContext; both callers use the result. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
The chunks of a split range query run in the thread group of the HTTP request, and a chunk is charged to the quotas over profile events with the counters of that group when it finishes or fails. The counters kept growing over the chunks, so each chunk was charged again with the events of the previous ones: two cache hits were charged as 1 + 2 + 2 = 5 and could get a later chunk rejected by the quota, three chunks reading 25 rows each were charged with 150 `SelectedRows`, and `query_log` showed the same growing counters. The counters of the group start from zero again after each chunk, so a chunk is charged only with its own events, also when it fails or is rejected by the quota. The memory tracker of the group and the time limit still cover the whole request. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nge query The first chunk finalizes the performance counters of the request thread when it finishes, and `ThreadStatus::finalizePerformanceCounters` does nothing after that until the thread attaches to a new thread group. The chunks run in the thread group of the HTTP request, so the CPU and real time that thread spent in the later chunks, including merging and writing the response, never reached `UserTimeMicroseconds`, `SystemTimeMicroseconds` and `RealTimeMicroseconds` of the chunks in `query_log`, nor the quotas over these events. A request paused for 1.5 s before the merge logged 456 us of real time for its last chunk, and the merge of a 600 KB response 195 us of CPU. `ThreadStatus::restartPerformanceCounters` starts the counters of the thread from zero and lets the next finalization account its usage since then. After each chunk the request thread restarts them together with the counters of the group, so the next chunk is charged with the usage of the thread too, also when it fails or is rejected by a quota. The memory tracker of the group still accounts the whole request. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a split PromQL range query When the first chunk finishes, `ThreadStatus::finalizePerformanceCounters` calls `PerfEventsCounters::finalizeProfileEvents`, which disables every perf event of the request thread, and closes the descriptors too unless `metrics_perf_events_enabled` is set globally. `ThreadStatus::restartPerformanceCounters` started the rusage and taskstats counters of the thread again, but not the perf events. So with `metrics_perf_events_enabled = 1` the later chunks, the merge included, got no `PerfTaskClock`, `PerfInstructions` or other perf events from the request thread, neither in `query_log` nor in the quotas over these events. `restartPerformanceCounters` now enables them again like `initPerformanceCounters` does when the thread attaches to the group, through `initPerfEvents`, which both call. Closed descriptors are opened again; open ones are enabled again and keep the values read by the last finalization, so the next one accounts only the usage since the restart. The integration test reads the `PerfTaskClock` of the request thread for each chunk from `query_thread_log`. It is a software event, so it needs no hardware PMU; where perf events can't be opened at all, the first chunk has none and the test is skipped. Co-Authored-By: Claude Opus 5.5 <[email protected]>
PromQL Compliance ReportBaseline: S3 master
Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream Note: Prometheus compliance score is unchanged vs baseline. |
This PR adds two settings for range queries of the Prometheus HTTP API (
/api/v1/query_range), both off by default:promql_range_query_split_interval: a range query at least this long is evaluated in chunks split at multiples of the interval, one chunk after another, and the results are merged. Evaluating the query takes the memory of one chunk, and the results of all chunks are kept until the response is written.promql_range_query_cache_min_age: chunks that cover a whole interval and ended more than this many seconds ago are stored in the query cache, so a dashboard refresh only recomputes the newest chunk and the partial ones.Example, as Grafana
customQueryParameters:promql_range_query_split_interval=86400&promql_range_query_cache_min_age=600&query_cache_ttl=3600.sum by (mode) (rate(node_cpu_seconds_total[5m]))sum by (mode) (rate(node_cpu_seconds_total[5m]))sum(rate(node_cpu_seconds_total[5m]))sum(rate(node_cpu_seconds_total[5m]))avg_over_time(node_load1[10m])avg_over_time(node_load1[10m])Measured on 84.7M samples of 2,100 series over 7 days at step 60 s on an Apple M4 (10 cores), median of 7 requests, request wall time and peak
memory_usagefromsystem.query_log, on a TimeSeries table with one sample per row (the default before the bucketed samples table), master being the same build with both settings off, the query cachemax_entry_size_in_bytesraised to 64 MiB so the daily chunks ofavg_over_timefit, load average 3.2 to 7.5. The split results are byte-identical foravg_over_time; the sums differ in the last bits (at most 1.7e-15 relative) because they add in a different order.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add settings
promql_range_query_split_intervalandpromql_range_query_cache_min_age: a long range query of the Prometheus HTTP API is evaluated in time chunks to lower its peak memory, and old chunks are kept in the query cache, so a dashboard refresh recomputes only the newest data.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/122585]