Skip to content

Measure compressed blocks read for AutoPR input bytes instead of sampling - #127835

Merged
nickitat merged 34 commits into
fix-stats-for-string-filtersfrom
autopr-subcolumn-input-bytes
Nov 20, 2026
Merged

nickitat merged 34 commits into
fix-stats-for-string-filtersfrom
autopr-subcolumn-input-bytes

Conversation

@nickitat

@nickitat nickitat commented Oct 26, 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):

Automatic parallel replicas now measure input bytes as the compressed blocks the readers actually load, instead of estimating them by sampling, so queries that read subcolumns such as length(URL) or skewed ranges of rows are no longer under-priced.


Related: #127586

The analyzer turns length(s) and s <> '' into reads of the subcolumn s.size. RuntimeDataflowStatisticsCacheUpdater::recordInputColumns estimated input bytes from in-memory column bytes times a compression ratio taken from getColumnSizes or from sampling. A subcolumn found no ratio of its own and silently inherited the ratio of the other columns of the block. On ClickBench Q27 (hits_4p, 100M rows) the recorded input was 0.94 MB against ~97 MB actually read for URL.size, so AutoPR could never switch to parallel replicas there; on Q31 the same bug inflated the input by 48%. Any per-row estimate also misses skew: a PREWHERE or primary-key range that selects rows with long strings is priced at the part average.

#127586 already makes the readers report the compressed blocks they load (setBlocksReadSink) for compact parts. This PR uses that measurement everywhere and removes input sampling altogether:

  • Wide parts: each stream gets a block-range sink. MergeTreeReaderWide::takeCompressedBytesRead adds only bytes not yet counted over the reader's lifetime, so a stream shared by several columns (n.size0, s and s.size from a single_stream String) and a block read by several granules are charged once.
  • Columns cache hits load nothing, so they are priced by the range of the blocks that hold the served granule (MergeTreeReaderStream::addRangeOfPosition, now in the base stream class), for wide and compact parts alike.
  • IMergeTreeReader::takeCompressedBytesRead returns std::optional<size_t>; a reader that cannot measure returns std::nullopt, and the statistics mark the case unsupported rather than guess.
  • Removed: input sampling through estimateCompressedColumnSize, codec resolution per column (ColumnCodecs, resolveCodecsForWholeColumn), and the ratio lookups. Output sampling stays and uses the default codec.

Results on a local server (test.hits, randomized settings): the recorded input is within 25% of ReadCompressedBytes for 184 of 207 queries of the AutoPR tests that collect statistics, against 155 of 203 with #127586 alone. New test 05452_autopr_subcolumn_input_bytes covers wide (with_size_stream, single_stream), compact, renamed, Nested with shared offsets, skewed PREWHERE and primary-key reads, and columns-cache hits, compared with on-disk sizes from system.parts_columns; it passed 40 of 40 runs with randomized settings.

Known limitation: in a wide part, a subcolumn served from the columns cache that has no stream of its own (the null map of a sparse Nullable) records 0 bytes.


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

The analyzer turns `length(s)` and `s <> ''` into reads of the subcolumn
`s.size`. `RuntimeDataflowStatisticsCacheUpdater::recordInputColumns`
counted the bytes of such a column in `bytes`, but found no compression
ratio for it: the wide-part branch looks columns up in `getColumnSizes`,
keyed by storage column, and the compact-part branch checked membership
in the part's `NamesAndTypesList`. The subcolumn then silently inherited
the ratio of the other columns of the block.

On ClickBench Q27 (`hits_4p`, 100M rows) the key compresses 1:1279, so
the recorded input was 0.94 MB against ~97 MB actually read for
`URL.size`, and AutoPR could never switch to parallel replicas there.
On Q31 the other columns compress poorly, so the same bug inflated the
input by 48% instead.

- Wide parts: the read task resolves the sizes of the subcolumns it reads
  once, through `getSubcolumnSize`, and they are priced by the compressed
  bytes of their streams per row. Not by a ratio: their in-memory bytes
  need not match those streams - a `single_stream` `String` keeps its
  sizes inside its only stream, so reading `s.size` reads all of `s`.
- Compact parts: subcolumns are matched through the part's
  `ColumnsDescription`, so they are sampled like any other column, with
  the `CODEC` of their storage column.
- A column the part has but which still cannot be priced marks the case
  unsupported instead of borrowing another column's ratio.

Known limitation: a compact part with a `single_stream` `String` still
prices `s.size` by the sizes column alone.

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

clickhouse-gh Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [445bb71]

Summary: ✅


AI Review

Summary

PR #127835 replaces sampled AutoPR input sizes with compressed-block accounting and deduplicates shared blocks across readers. Reviewed head 445bb71f830c189a907e938f63dfd0e42c1a416a. One previously reported accuracy issue remains in cached reads of merged LowCardinality parts; request changes.

Findings

⚠️ Majors

  • src/Storages/MergeTree/MergeTreeReaderStream.cpp:682–699: Cached reads can omit a dictionary needed by the selected rows. [dismissed by author -- https://github.com/Measure compressed blocks read for AutoPR input bytes instead of sampling #127835#discussion_r4473365968]

    A merge can start another dictionary inside a granule. When the next mark points to that dictionary at decompressed offset zero in a different compressed block, addRangeOfMark ends the accounted range before it. The disk read needs both dictionaries, so warming the columns cache reduces the recorded input and can incorrectly suppress automatic parallel replicas. The existing thread's reproduction recorded 1,178,196 bytes cold versus 645,514 warm. The current condition still excludes that same dictionary; these measurements were not rerun on this head.

    Commit 445bb71f deliberately accepts this undercount to avoid charging an inserted granule for the next granule's dictionary. The concern remains because the demonstrated error is about 45%, sufficient to change the cost decision. Determine the actual dictionary bounds, or mark ambiguous cached reads unsupported, as other unmeasurable serializations already do. Do not simply extend every dictionary range: that would reintroduce the insert overcount.

Tests
  • ⚠️ 05508_autopr_cache_lowcardinality_next_dictionary.sql stops merges and covers an inserted granule written in one call. Also retain a cold/warm case using two interleaved parts merged with index_granularity = 10000, merge_max_block_size = 1000, and min_compress_block_size = 1. Verify that cached accounting includes every required dictionary or declines to publish statistics.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary/build was available to rerun the merged-part reproduction. The latest Praktika index is green, but the selected targeted stateless report returned no per-test results. A run of the merged fixture on the reviewed head would close this execution-evidence gap.
Final Verdict

⚠️ Request changes. Handle or reject ambiguous cached dictionary ranges and cover both inserted and merged parts. No new inline findings were posted: the remaining issue already has a review thread, and the latest commit explicitly documents the author's decision.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Oct 26, 2026
nickitat and others added 2 commits October 26, 2026 13:36
The callback that records input bytes receives the columns under the
names the readers give them, which are the names in the part, while the
size and codec maps were keyed by the read task's current-schema names.
Fixes found in review:

- A column renamed by a mutation not yet applied to the part is read as
  `s.size` but was looked up as `renamed.size`, so the statistics of the
  whole query were dropped as unsupported (0 bytes instead of 2.99 MB).
- `length(n.a)` reads the offsets `n.size0` shared by the arrays of a
  `Nested`. That name was in no map and unknown to the flattened part
  description, so it borrowed the other columns' ratio (72 KB recorded
  against 2.47 MB read).
- Several columns reading the one stream `n.size0` charged it once each
  (9.79 MB recorded against 2.47 MB read for four of them).
- After a pending rename, a compact part was sampled with the part's
  default codec instead of the column's `CODEC` (3.2 MB vs 14.1 MB).

`MergeTreeReaderWide::getCompressedBytesOfColumnsToRead` lists, for each
column it reads, the streams it opens and their compressed bytes, under
the names the read uses. The read task builds the size and codec maps
from each main and PREWHERE reader, pairing the requested column (for
the metadata lookup) with the column in the part (for the key). A stream
is charged once per block, while every column's in-memory bytes still
count in the sample, as they do in `read_bytes`. The membership check
uses the part description with collected `Nested` columns.

Columns with a dynamic structure, or a bucketed `Map`, list their data
streams only after their prefixes are read; they keep using the part's
`getSubcolumnSize`. A random `map_serialization_version_for_zero_level_parts
= 'with_buckets'` used to make the reader treat every column that way.

Known gap: compact parts still charge a stream shared by several columns
once per column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…put-bytes

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderWide.cpp
Fixes found in review:

- A compact part reads the offsets of a `Nested` array as `n.a.size0`,
  which the description with collected `Nested` columns does not know,
  so they were left out of the sample and took the other columns'
  ratio (72 KB recorded against 2.44 MB on disk). The new
  `IMergeTreeReader::getPartColumnsDescription` names the part's
  columns the way `getColumns` names the columns read: collected for a
  wide part with `share_nested_offsets`, as written otherwise.
- A full `single_stream` `s` read next to `s.size` shares its only
  file with it, but the streams of columns priced through
  `column_sizes` were never marked as charged, so the file was charged
  twice (7.07 MB recorded against 3.49 MB on disk). They are now taken
  before any other column of the block is priced.

The test compares every case with the bytes on disk from
`system.parts_columns` instead of `ReadCompressedBytes`, which a read
served from the uncompressed cache or the columns cache does not count:
with a random `use_columns_cache = 1` the repeated read of `t_nested`
failed in CI.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=127835&sha=c9c5f6b09813c8cafa9bbcd890969ca653483259&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
PR: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
Found in review: a stream marked as charged was not always paid for.
`MergeTreeDataPartWide::calculateEachColumnSizes` counts the offsets
`n.size0` a `Nested` shares in the size of one of its arrays only, so
reading `n.b` whole marked `n.size0` as charged without its bytes, and
`SELECT key, avg(length(n.a)), sum(arraySum(n.b))` recorded 846 KB
against 3.77 MB read.

Every column of a wide part whose streams the reader lists, full column
or subcolumn, is now priced by those streams per row, and a stream is
charged once per block. `column_sizes` and its compression ratio price
only the columns whose streams are not known, those of a dynamic
structure.

The block's compressed bytes are now the cost of the whole read, so they
are no longer scaled by `read_bytes` over the in-memory bytes: the two
count a `String` differently (a varint against 8 bytes per offset), which
overstated a full `String` read by 11-14% and understated `s` read next
to `s.size`. A full `single_stream` `s` now records 3,487,702 bytes
against 3,487,729 read (3.89 MB before).

PR: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
nickitat and others added 10 commits October 26, 2026 19:39
The input of the dataflow statistics was estimated from the read columns: a sampled
compression ratio for compact parts, a per-column ratio from the part's column sizes
for wide parts, scaled by the in-memory size of the block. Each of these misses
something real: a subcolumn read from the stream of its column (`s.size` of a
`single_stream` `s` reads all of `s`), the offsets the arrays of a `Nested` share,
columns renamed by a mutation not yet applied, a selection of unusually large
values, the values a scan-time string filter replaced.

Every reader now reports the compressed size of the blocks it loaded, which
`CompressedReadBufferFromFile` and `CachedCompressedReadBuffer` count, and
`recordInputBytesRead` adds it as it is. Wide readers sum their streams, the
released ones included. A granule served from the columns cache loaded nothing, so
it is priced by the compressed size between its marks, without the streams that a
column read from the part in the same granule loads; marks are loaded for this only
when statistics are collected. `MergeTreeReaderIndex` loads nothing at read time,
and `MergeTreeReaderTextIndex` reports its fallback reader (its posting lists are not
counted). The input sampling, the per-column ratios and codecs, and the accounting of
the values skipped by string filters are removed.

Recorded input against `ReadCompressedBytes` over the 203 queries of the AutoPR tests
that collect statistics: within 25% for 181 (155 before), under half for 11 (18 before).
In `05452` every case matches the bytes read within 0.2%, the same with rows served
from the columns cache.

Related: #127586
Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…to autopr-measure-input-bytes

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/RuntimeDataflowStatistics.cpp
#	src/Processors/QueryPlan/Optimizations/RuntimeDataflowStatistics.h
#	src/Storages/MergeTree/IMergeTreeReader.h
#	src/Storages/MergeTree/MergeTreeReadTask.cpp
#	src/Storages/MergeTree/MergeTreeReadTask.h
#	src/Storages/MergeTree/MergeTreeReadersChain.h
A compact part is served from the columns cache granule by granule and column by
column since "Columns cache for compact parts", and such a granule loads nothing. It
is priced by the compressed size between its marks, of the positions the column is
read from: its own, or the substreams a subcolumn is read from. A position whose block
a column read from the part in the same granule loaded is skipped: without
`compress_per_column_in_compact_parts` the columns of a granule share their blocks.
This replaces the estimate of the served rows from a sample of them.

`05452` reads a wide and a compact table twice with the columns cache, and the second,
served read must be priced as the first one. `05443` pins
`compress_per_column_in_compact_parts`: with shared blocks, its second query loads the
part all the same, so it cannot check that the columns cache saved the read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…to autopr-measure-input-bytes

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/RuntimeDataflowStatistics.cpp
#	src/Storages/MergeTree/IMergeTreeReader.h
#	src/Storages/MergeTree/MergeTreeReadTask.cpp
#	src/Storages/MergeTree/MergeTreeReaderCompact.cpp
#	src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.cpp
…to autopr-measure-input-bytes

The incoming commit prices a compact granule served from the columns cache from its
first mark to the next mark in the file at a later offset, which counts the whole block
a column shares with others. This branch priced it by the span to the next position,
which counts a shared block once but misses it when only one of its columns is served,
and skipped the blocks a column read from the part in the same granule loads.

Kept together, for both part types: a served granule of a column costs the blocks it
begins in, up to the next mark at a later offset; a block is counted once for the
reader, by its offset (many granules of a wide part share a block, and a granule is
served in pieces when rows are skipped), and not at all when a column read from the
part in the granule loads it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…-bytes

The incoming commit makes the compressed read buffers report the ranges in the file of
the blocks they load, adds the ranges of the blocks that hold the granules served from
the columns cache, and counts the union of the ranges of a read step. Its compact
reader is taken as it is, in place of this branch's.

Wide parts use the same ranges: every stream reports the blocks it loads, a granule
served from the cache adds the range of the blocks that hold it (`addRangeOfPosition`,
moved to `MergeTreeReaderStream`), and the union is counted per stream. A block of a
wide part holds many granules, served in several read steps, so a served block is
added once for the reader.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
A block of a wide part can hold the end of one granule and the beginning of the next. With
large granules, a block read from the part in one read step also held a granule served from
the columns cache in another step, and it was counted in both: the union of the ranges was
taken per read step, and only the served blocks were remembered across steps. 05452
recorded 1.29x the bytes on disk with `index_granularity = 60964`.

Each stream now keeps the ranges it counted for the reader, merged, and a range read or
served adds only the bytes not counted yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…-bytes

Replaces the estimate of the input of the dataflow statistics with the compressed bytes the
readers load, see the merged branch. It is built on
#127586 and supersedes the per-stream pricing
of this branch: the tree is taken from the merged branch as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Oct 27, 2026
@nickitat nickitat changed the title Price subcolumn reads in AutoPR input-bytes statistics Measure compressed blocks read for AutoPR input bytes instead of sampling Oct 27, 2026
@nickitat
nickitat changed the base branch from master to fix-stats-for-string-filters October 27, 2026 09:38
@nickitat
nickitat added this pull request to stack #127929 October 27, 2026 09:38
…d its cache checks robust

A `Quantized` column enumerates its codes and codebook, which reading the vectors from a wide part skips, so a granule of
the vectors served from the columns cache was overcharged. The codebook of the part is one value with all marks at
(0, 0), so a granule of it was charged nothing. The bytes read are not measured then, like for the other columns whose
streams are not known without reading them.

05452 ran over 180 s in the ASan flaky check: the tables hold 200k rows instead of 1M. The first read of the cache
checks was served from the cache in the debug flaky check: the randomized injection split the ranges into overlapping
ones, and a stream served the granules another one cached. It is off for these reads, and a read is expected to be
measured exactly when the cache served nothing.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
nickitat and others added 2 commits October 27, 2026 22:40
… the columns cache

A granule that wrote nothing of its own to a stream, like the granules that share a `LowCardinality` dictionary, has
the same mark as the next one. When the dictionary starts a compressed block (`min_compress_block_size = 1` flushes the
version prefix before it), both marks are at the start of the block, and `addRangeOfPosition` took the next mark as
the end: an empty range, and a cached read of an initial key range did not count the dictionary. The end is now the
next later offset then too, as in `MergeTreeReaderStreamSingleColumn::getRightOffset`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
nickitat and others added 2 commits October 28, 2026 09:17
The readers of a read each counted the blocks they loaded, so a block loaded by several of them, each for its own
granules, was counted once by each. With large compressed blocks and small read tasks, the measured input of
`03783_autopr_dataflow_cache_reuse` on the `s3 storage` job was 259466 bytes for a part of about 65 KB, four streams
each loading the single block of a column, and parallel replicas were chosen for a table of 10000 rows. A replica
would load such a block as well, so the input is the data, counted once.

The counted ranges move from the reader to a `CountedCompressedBlocks` shared by the readers of an updater, by part
and file. The reads parallel replicas would not split get an updater each, so two reads of a table still count it
twice.

Also, a wide reader that cannot measure a granule served from the columns cache drops the ranges its streams keep
appending, and stops adding the cache hits, instead of keeping them for the rest of the read.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…ut-bytes

Takes the end of a cached granule of a compact part from all the marks in the order of the file, which
fixes the wrapped `RuntimeDataflowStatisticsInputBytes` of 05452 for compact parts with stripes of
several granules. The compact streams use that version as is; the streams of one column keep the end
at the next later offset for a same next mark (`LowCardinality` dictionaries) as `addRangeOfMark`.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 445bb71f8 with master 08d8752ac (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

81 object files changed (+31.74 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReadTask.cpp.o 270.90 KiB 239.88 KiB -31.02 KiB (-11.45%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderStream.cpp.o 153.01 KiB 181.47 KiB +28.46 KiB (+18.60%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderWide.cpp.o 407.06 KiB 430.68 KiB +23.62 KiB (+5.80%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.cpp.o 119.34 KiB 139.17 KiB +19.84 KiB (+16.62%)

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

671 translation units recompiled, 5951 s compile time in total, 670 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.5 s

Job report

nickitat and others added 2 commits November 3, 2026 13:39
A granule that writes nothing to a stream, like empty arrays to the elements or empty strings to the
string data, has the same mark as the next one, and `addRangeOfMark` took the range up to the next later
offset, as for the granules that share a `LowCardinality` dictionary. A warm read of the empty granules
before the values of the last one was charged with their block: 620,087 bytes against 108,062 cold
in the reported case. Now only the dictionary keys extend a range over the same next mark; for the other
streams the granule has nothing to count.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
nickitat added a commit that referenced this pull request Nov 3, 2026
The second read of `t_compact` from the columns cache had 33 hits and 4 misses: the cache of the tests
is 100 MiB, an SLRU whose probationary half is close to the allocated size of the 37 granules of `s`, so
the first granules may be evicted. The 4 granules read again were 1,393,296 bytes, over a tenth of the
12,746,538 read the first time. The check now asks for less than half; the estimate is checked anyway.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
nickitat and others added 4 commits November 4, 2026 13:11
…ut-bytes

# Conflicts:
#	src/Storages/MergeTree/IMergeTreeReader.h
#	src/Storages/MergeTree/MergeTreeReaderStream.cpp
#	src/Storages/MergeTree/MergeTreeReaderWide.h
…it begins

`CountedCompressedBlocks::take` subtracts the begin of a range from its end. A range that ended before
it began made the count wrap around to 2^64 in `05452` on Cloud, where compact parts are written in
stripes of several granules. The ranges of cached granules now take the stripe bound (merged from
`fix-stats-for-string-filters`), so such a range is a bug.

Related: #127835
Related: #127586

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SZKMswoC3pzhtU6mb2KeM1
…lumn too

The columns of a reloaded part lose the custom serialization of the `Quantized` codec, which
`getColumnAndSerializationInPart` then takes from the requested column: after a pending rename and a
reload, the column to read is a plain `Array` read with `SerializationQuantizedVector`. The guard looked
only at the column to read, missed it, and charged the codes and the codebook, which reading the vectors
skips: 8,401,962 bytes for a cached read that is otherwise not measured.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
nickitat added a commit that referenced this pull request Nov 4, 2026
…anning the marks

When the next position of a granule served from the columns cache starts inside a compressed block,
`addRangeOfPosition` scanned the following marks for the next later offset, once for each cached granule
and position. When many granules share one block, that is quadratic in the number of marks. Outside of
the stripes of several granules the offsets of the positions in row order don't decrease, and the next
such stripe starts a block after this one, so a binary search finds the same mark.

Related: #127586
Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
nickitat and others added 3 commits November 4, 2026 15:29
`SYSTEM STOP MERGES` holds only the instance it is run on: after `DETACH` and `ATTACH` the new instance
runs the rename mutation, which can finish before the cached reads, and then the part has the new name
and the old guard passes the test too. The case moves to its own test on a `ReplicatedMergeTree` that
cannot become a leader, so no replica assigns the mutation. The rename is waited for with
`SYSTEM SYNC REPLICA`, since `alter_sync` would wait for the mutation too. Without the fix the test fails
5 times out of 5; 05452 needs no Keeper and is not skipped by the fast test.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…ut-bytes

Keep this branch's `MergeTreeReaderCompactSingleBuffer`: `CountedCompressedBlocks::take` counts a compressed block once
for the whole read, which covers the blocks shared by consecutive read steps in a multi-granule stripe, so the ranges
counted by the previous step and the last loaded block don't need to be kept.

Related: #127586
Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
nickitat added a commit that referenced this pull request Nov 4, 2026
… that use it

`takeCompressedBytesRead` counted the union of the ranges of one read step. In a stripe of several granules (the layout
of compact parts on Cloud), a compressed block of a column can hold several granules. Reading keeps the block loaded for
the next step, so it is loaded once. A granule served from the columns cache instead takes the range of the whole block
again at every step: with one granule per step and a block of 16 granules, that is 16 times the block.

Now the ranges of a step that the previous step counted are not counted again. Only the previous step is kept, which
bounds the memory, and works when reading in reverse order too. Upstream compact parts flush the blocks of every column
at each granule, so the blocks of consecutive steps don't overlap, and nothing changes there.

Related: #127586
Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SZKMswoC3pzhtU6mb2KeM1
…n place

`CountedCompressedBlocks::take` built the path of the file and hashed it at every read step of every stream, and
replaced a counted range it extended by a new node of the map. A reader now looks the counted ranges of a file up once
by stream and keeps a pointer to them, and `take` extends the counted range in place, so reading on from where the
previous block ended allocates nothing.

On a scan of a wide part of 40 columns with 16 threads, `takeCompressedBytesRead` drops from 2.5% to 0.7% of the
samples of the server.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
/// The block goes on to the next later offset if the next mark is inside it. The granule needs the block also if
/// it shares the data written after it, like a `LowCardinality` dictionary: then the next mark is the same, at the
/// start of the block, as in `MergeTreeReaderStreamSingleColumn::getRightOffset`.
if (next_mark.offset_in_decompressed_block != 0 || next_mark.offset_in_compressed_file == begin)

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.

[P2] Include every dictionary needed by a partially written granule

For DictionaryKeys, the next mark can be at the start of a different compressed block that the current granule still needs. A merge can serialize one granule in several calls, flush its first dictionary, and start another dictionary before the granule ends. Here shared_with_next_granules only prevents the equal-mark early return: when the next dictionary starts at offset zero of a different block, this condition is false and the range ends before that dictionary. MergeTreeReaderStreamSingleColumn::getRightOffset explicitly handles this non-atomic-granule case by advancing beyond the next distinct dictionary mark.

Reproduced on 228709f788679aa3028ad74d5aab0b3da5893014: create a wide table with key UInt64, s LowCardinality(String) CODEC(NONE), index_granularity = 10000, index_granularity_bytes = 0, merge_max_block_size = 1000, and min_compress_block_size = 1. Insert two 32,768-row parts with interleaved even/odd keys and distinct 64-character strings, then OPTIMIZE FINAL. With the AutoPR/columns-cache settings from 05452, repeating SELECT s FROM t WHERE key < 10000 FORMAT Null records 1,178,196 input bytes cold versus 645,514 warm, with two cache hits and no compressed reads on the warm execution. The missing dictionary makes the cached estimate about 45% smaller and can incorrectly suppress automatic parallel replicas.

Please account for the complete dictionary read bounds, including granules that span multiple dictionaries, or mark cached accounting unsupported when those bounds cannot be determined. Add a cold/warm regression using a merged multi-dictionary part; the existing single-dictionary fixture does not exercise this boundary.

nickitat and others added 2 commits November 4, 2026 21:33
…ts inside it

A merge writes a granule in several calls, and may start a new dictionary in the middle of it. The next mark then points
to that dictionary, which the granule needs as well, but the range of a granule served from the columns cache ended at
the next mark. Now it goes on to the next different mark after the next one, as `getRightOffset` does when reading.

The read of the new test recorded 1,177,746 input bytes cold and 645,264 served from the cache; now 1,177,713.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
A dictionary is written at the end of the call that fills it, so a granule written in one call, as by every insert,
needs no dictionary after the next mark. Going on to the next different mark, as `getRightOffset` bounds a read, priced
a granule served from the columns cache with the dictionary of the next granule too: 669,259 input bytes against
359,505 when read from the part, for one granule of a part whose dictionary fills at every granule.

A merge may write a granule in several calls and start the next dictionary in the middle of it. The marks don't tell
the two cases apart, and only the dictionary of the last granule of a read is missed then, so that case is undercounted
instead. The test covers the insert now.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
@clickhouse-gh clickhouse-gh Bot added comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026
@nickitat
nickitat merged commit f1edb16 into master Nov 20, 2026
370 of 372 checks passed
@nickitat
nickitat deleted the autopr-subcolumn-input-bytes branch November 20, 2026 14:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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