Skip to content

Limit the ranges automatic parallel replicas count to measure the input bytes - #133777

Draft
nickitat wants to merge 19 commits into
fix-stats-for-string-filtersfrom
autopr-count-ranges-cap
Draft

nickitat wants to merge 19 commits into
fix-stats-for-string-filtersfrom
autopr-count-ranges-cap

Conversation

@nickitat

@nickitat nickitat commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

The memory automatic parallel replicas use to measure the input bytes of a query is limited by the new setting automatic_parallel_replicas_max_counted_ranges. Past it the query is not measured, and the statistics remember that, so automatic parallel replicas are not enabled for it.


Stacked on #127586, which measures the input bytes as the compressed blocks the readers load, each block once. The ranges registered for that in the ReadRangesRegistry are kept per file for the whole read, so a read over many files, or with a sparse filter, could keep many of them.

The ranges and files of all the reads of a query are now limited by automatic_parallel_replicas_max_counted_ranges (1'000'000 by default, 0 means no limit; a file takes 8 units, about the memory of 8 ranges). Each batch of ranges is reserved from a query-wide atomic counter before it is kept, so the counter is updated once per registerReadRanges, not once per range. Past the limit the readers stop collecting the ranges and free what they registered, and the statistics are cached with input_not_measured, so the next run does not collect them again: considerEnablingParallelReplicas declines and counts AutoParallelReplicasRejectedByUnmeasuredInput.

The registry also takes less memory and time than in #127586:

  • The ranges of a file are a flat vector: a range is appended, or extends the last one in place, and the appended ranges are sorted and merged in bulk once they are as many as the merged ones, or before the vector would grow. Their bytes are counted when they are merged; what is left unmerged is counted when the registry is destroyed, which is before the statistics are recorded since the registry holds their block. A range takes 16 bytes (25-39 at the peak) instead of the 48 of a std::map node, and adding one is 2-10x faster than with a B-tree, which was tried too (absl::btree_map: 18-22 bytes, but slower than std::map until the ranges no longer fit in the cache).
  • The files are keyed by the sipHash128 of the path in an absl::flat_hash_map, not by the path in a std::unordered_map: 137-167 bytes per file instead of 261 at 1M files, and slightly faster lookups.
  • All of registerReadRanges is timed in RuntimeDataflowStatisticsInputNanoseconds, not only the merge of the ranges.

The default comes from ClickBench: on hits (one part of 100M rows) the most a query takes is 3,511 units (q23, whose filter leaves 3,462 separate ranges), and most take 15-330. 1M leaves room for about 300 times that, with the ranges within 16-32 MB.


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

nickitat and others added 7 commits November 22, 2026 21:07
A compressed block is counted once however many times it is loaded, so the counted ranges of each file are kept
until the query ends. A read that skips many granules leaves one range per run of granules read, per column, per
part: 48 bytes each in the `std::map`, about 250 bytes per file, so a sparse scan of a billion rows and a hundred
columns needs about 300 MB.

The new setting `automatic_parallel_replicas_max_memory_for_input_statistics` (256 MiB by default) limits that per
query. The memory is accounted in the statistics block every reads of the query share, once per reader per step.
Past the limit the reads stop counting and free their ranges, and the cache remembers that the input was not
measured: the next run declines parallel replicas from it, counted in
`AutoParallelReplicasRejectedByUnmeasuredInput`, without collecting the statistics again until the rows read drift.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The limit was checked when a reader committed its batch, after the maps of all its streams had grown, and a file
looked up once counting stopped still got an entry. Now each stream's `take` is checked beforehand against what it
can add at most, a node per range, and a file is added only within the limit: past it `getCountedRanges` gives out
an empty `CountedRanges` that is never counted into. The entries readers already point to stay, emptied by the
next `count`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`modernize-use-nodiscard` flags them in every translation unit that includes the header. The PR changed the
header, so the clang-tidy cache no longer hid them.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=127586&sha=141c98b0e47f6cb31f8858d2d53c64949e2e624a&name_0=PR
#127586

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…er instead of their memory

The check before a map grew compared the committed total, so concurrent readers could all pass it and then commit
past the limit together, and the ranges pending in the buffers were outside the limit.

Now the limit is `automatic_parallel_replicas_max_counted_ranges`, a number of ranges (about 48 bytes each) where a
counted file takes a unit too, by default 4 million. A reader reserves what a stream's ranges can add at most before
taking them, and releases the rest when it commits its batch; a reservation that does not fit stops the counting. Once
it stopped, the readers detach their sinks and free the pending ranges, and a reader enabled later attaches none. The
buffers extend the last pending range with a block that continues it or that it covers already, so reading on and
loading a block again do not grow the pending ranges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The compact tables of `05443` and `05452` are created from their wide counterparts, keeping only the settings that make
them compact. The assertions of `05452` and `05838` take their aliases from `WITH` instead of a subquery. Comments that
repeated the accounting are shortened, and the comment on the columns cache in `05443` says why it is still disabled: a
reader writing to it reads the values without the string filter. `Readers::countCompressedBytesRead` had one caller and
is inlined into it, and `RuntimeDataflowStatistics.h` no longer includes headers for the removed input sampling.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Nov 23, 2026
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/RuntimeDataflowStatistics.h
#	src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp
# Conflicts:
#	src/Compression/CachedCompressedReadBuffer.cpp
#	src/Compression/CompressedReadBufferBase.h
#	src/Compression/CompressedReadBufferFromFile.cpp
#	src/Processors/QueryPlan/Optimizations/RuntimeDataflowStatistics.h
#	src/Storages/MergeTree/IMergeTreeReader.h
#	src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.cpp
#	src/Storages/MergeTree/MergeTreeReaderStream.cpp
#	src/Storages/MergeTree/MergeTreeReaderStream.h
#	src/Storages/MergeTree/MergeTreeReaderWide.cpp
Revert before this PR is retargeted to master.

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

clickhouse-gh Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4a331bd]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) FAIL
05182_compress_per_substream_in_compact_parts FAIL cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
00542_access_to_temporary_table_in_readonly_mode NOT_FAILED cidb
01414_push_predicate_when_contains_with_clause NOT_FAILED cidb
La Casa Del Dolor (arm_asan_ubsan) FAIL
UndefinedBehaviorSanitizer: signed integer overflow (STID: 1003-46d8) FAIL cidb

AI Review

Summary

This PR limits the compressed-block ranges retained while automatic parallel replicas measure query input, remembers an abandoned measurement, and replaces the range maps with vectors merged in bulk. Reviewed 4a331bdaf3c6239cd53d4b362be6de74c79b7fd4. Request changes: pending allocations remain outside the budget, and the regression test does not exercise exhaustion after ranges have been retained.

Findings

⚠️ Majors

  • src/Compression/CompressedReadBufferBase.h:78, src/Storages/MergeTree/MergeTreeReaderStream.cpp:482: The setting does not bound accounting allocations before they grow. [dismissed by author -- https://github.com/Limit the ranges automatic parallel replicas count to measure the input bytes #133777#discussion_r4681968336] recordBlockRead still appends disjoint ranges without reserving budget, and registerRanges now processes the entire batch before checking its capacity growth. A sparse read can therefore allocate many pending ranges and copy them into the registry, or raise MEMORY_LIMIT_EXCEEDED, before collection stops; the overshoot scales with batch size and concurrent readers independently of the configured limit. Reserve bounded chunks before growing both stores. The author's resolution is respected; this thread was left closed without a reply.

  • tests/queries/0_stateless/05839_autopr_input_statistics_ranges_limit.sql:20: Range-capacity exhaustion has no regression coverage. A budget of 1 rejects the first file, which costs 8 units, so no range reaches the registry and the new capacity-growth check is never exercised. Removing reserve(grown) would leave this test passing. Add a case that admits files and some ranges, exhausts the budget with disjoint compressed ranges, and verifies successful query completion plus rejection on the next execution. Include an unlimited-budget control with forced statistics recollection. New inline finding.

Tests
  • ⚠️ Fast test at the reviewed head passes the new test and 92 other automatic-parallel-replica tests, but provides no evidence for the allocation bound or exhaustion after collection starts. A focused sparse-read case covering that transition would close this gap. No local tests were run, as requested.
Final Verdict

Status: ⚠️ Request changes

Bound pending and registered allocation growth before it happens, and add focused coverage for exhaustion after collection starts.

LLVM Coverage Report

Measured on commit 4a331bd.

Metric Baseline Current Δ
Lines 91.90% 91.90% +0.00%
Functions 92.20% 92.20% +0.00%
Branches 81.60% 81.60% +0.00%

Changed lines: Changed C/C++ lines covered: 282/311 (90.68%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 24, 2026
nickitat and others added 2 commits November 24, 2026 14:28
The workflow edit in 8e9803d failed the `Check Workflows` job, which regenerates the workflows from `ci/workflows`.
Set the base branches in the source instead. Revert before this PR is retargeted to master.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=133777&sha=latest&name_0=PR
Related: #133777

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderStream.cpp
#	src/Storages/MergeTree/MergeTreeReaderWide.cpp
nickitat and others added 2 commits November 24, 2026 15:32
…arallel_replicas_max_counted_ranges` to 10M

A `std::map` node takes 48 bytes for the 16 bytes of a range; `absl::btree_map` keeps a range in
about 18-23 bytes with about 15 times fewer allocations. In a benchmark of `ReadRanges::add` on one core:

- 10k ranges per file: 5-50% slower than `std::map` (both in cache);
- 500k ranges per file: up to 2.4x faster (random order: 535 -> 218 ns per range).

The range that goes on from where the last one ended, the common case, is now extended without a lookup:
9.8 -> 2.3 ns per range with `std::map`, 25.6 -> 8.2 ns with the B-tree.

The limit is raised to keep about the memory it allowed before, ~200 MB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n a flat hash map

With 1M files of ~105-character paths, the `std::unordered_map<String, ReadRanges>` took ~261 bytes
and 3 allocations per file; `absl::flat_hash_map<UInt128, std::unique_ptr<ReadRanges>>` takes
137-167 bytes and 2 allocations, and the lookup is a bit faster (405 -> 381 ns per file at 1M files,
102 -> 74 ns at 10k).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… keeping them in a B-tree

A range is appended, or extends the last one in place; the appended ranges are sorted and merged
into the others once they are as many, or before the vector would grow. Their bytes are counted when
they are merged, and the ranges left unmerged when the registry is destroyed, which is before the
statistics are recorded since it holds their block.

In a benchmark of the same workloads on one core, per range:

- 10k ranges per file: 2-10x faster than the B-tree (e.g. gaps, 16 streams: 94 -> 28 ns);
- 500k ranges per file: 2.5-6x faster (random order: 212 -> 77 ns);
- 16 bytes kept, 25-39 at the peak, against 18-22 for the B-tree.

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

clickhouse-gh Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4a331bdaf with master 2b066904b (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

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

121 object files changed (+53.36 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderStream.cpp.o 175.88 KiB 230.71 KiB +54.83 KiB (+31.17%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReadTask.cpp.o 296.85 KiB 257.62 KiB -39.23 KiB (-13.21%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderWide.cpp.o 464.24 KiB 486.77 KiB +22.53 KiB (+4.85%)

716 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

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

Job report

…the limit, and the arguments of a unit test

`setReadRangesRegistry` takes `ranges_read_mutex` under the lock of the streams, and
`registerReadRanges` took the lock of the streams under `ranges_read_mutex` to drop the sinks once the
counting stopped: TSan reported a lock-order inversion. The sinks are now dropped with
`ranges_read_mutex` released.

The test of the undecided queries passed its key as `max_counted_ranges_`, the argument inserted before it.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=133777&sha=latest&name_0=PR
Related: #133777

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nickitat and others added 3 commits November 24, 2026 22:25
…ge a file 8 units of it

On ClickBench (`hits`, one part of 100M rows), the most a query takes of the limit is 3,511 units
(q23, where the filter leaves 3,462 separate ranges), and most take 15-330. 1M leaves room for about
300 times that while keeping the ranges within 16-32 MB. A file takes about as much memory as 8
ranges, so it now takes 8 units instead of 1.

The description of the setting no longer explains how the ranges are kept.

Also from the review: the files looked up once the counting stopped share one `not_registered`, which
`registerRanges` no longer adds ranges to, and the reservation is checked not to underflow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ty the ranges hold, and free them all when the counting stops

The units given back when ranges merged were by the size of the vector, which keeps its capacity: a
file whose ranges collapsed returned its budget while still holding the memory, and over many files
the memory could grow past the limit. The limit is now charged by what the capacity grows by after
each registration, and nothing goes back on a merge; a query can go over by one vector growth at most.

When the counting stopped, only the file at hand was freed, and the ranges of the others stayed until
the registry was destroyed. Now each registry frees the ranges of all its files once it sees the stop,
keeping the files the readers refer to, and frees the file a registration after the stop is given.

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

-- The first counted file takes more units than the limit.
SELECT key % 10 AS k, max(value) FROM t_autopr_input_ranges GROUP BY k FORMAT Null
SETTINGS automatic_parallel_replicas_max_counted_ranges = 1, log_comment = 'autopr_input_ranges_collect';

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.

[Major] Cover range-capacity exhaustion after collection starts

With automatic_parallel_replicas_max_counted_ranges = 1, getReadRanges rejects the first file because units_per_file is 8 and returns not_registered. Consequently this test never adds a range to the registry or reaches the capacity-growth check in ReadRangesRegistry::registerRanges; deleting reserve(grown) would leave it passing. The existing input-byte tests use the default budget and do not exercise exhaustion either.

Please add a focused case whose budget admits the measured files and some ranges, then exhaust it with disjoint compressed ranges. Check that the query completes and the next execution reports AutoParallelReplicasRejectedByUnmeasuredInput, with an unlimited-budget control that successfully measures the same read. This would protect the range-storage limit that is the main behavior of this change.

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

ci-force-all Do not skip any jobs when running comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant