Repository navigation
Group PREWHERE read steps by exact columns and rewrite m['key'] to a key subcolumn only for bucketed Map - #124553
Conversation
…n its subcolumn Since ClickHouse#107988, tryBuildPrewhereSteps groups adjacent PREWHERE conditions by the storage column they read, so that the keys of one Map, each of which reads the whole Map, share one read step (ClickHouse#107912). The resolution was type-blind: `j.kind` and `j`, two JSON paths, a Tuple element and the whole Tuple, `m.size0` and `m.key_k1`, and keys of two Maps nested in one Tuple all resolved to one storage column. A cheap subcolumn condition was then merged with an expensive condition on the rest of the column, which read the whole column for every row. On master a may-throw `toString(j)` gets its own step (ClickHouse#111954), but its read-ahead, keyed on the same comparison, reads `j` in step 0 anyway. Key each input by the storage column and the substreams cache key of its subcolumn path instead. A Map key subcolumn drops its trailing MapKeyValue, so it keys as the Map that owns it (`(m, "")` at the top level, as before; `(c, "%2Eleft")` for a Map inside a Tuple, so two sibling Maps no longer share a step). The pair is used rather than a concatenated string because the path rendering escapes tuple dots. MergeTreeWhereOptimizer keeps grouping by storage column: that keeps a guard ahead of a throwing condition on the same column. So with the expensive condition written first the order is still kept. Closes ClickHouse#124535 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the clause narrating how the new grouping identity splits steps from the resolveStorageColumnName comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (3 nits).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261008-051100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261008-035200 |
|
Workflow [PR], commit [c6da0df] Summary: ❌
AI ReviewSummaryThis PR separates independently readable subcolumns into distinct Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block. At minimum, preserve previously working map-key lookups and remove the measured compact-part CPU regression, with focused correctness and performance verification. The two author-dismissed concerns above remain recorded without reopening or replying to their threads. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units727 translation units recompiled, 6303 s compile time in total, 727 of them have a recent master baseline. |
The performance test runner expands every `{name}` in a query template
with `str.format`, so the JSON literal in the fill query was read as a
`{"kind"}` placeholder and the test failed with `KeyError: '"kind"'`
before running any query. Double the braces, as other JSON perf tests do.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: All four flagged improvements are downgraded to not_sure. This PR only changes how PREWHERE conditions on subcolumns are grouped into read steps: Map key subcolumns still count as their parent Map, while other JSON and Tuple subcolumns are now told apart by the part of the column they read. No ClickBench or TPC-H query reads Map, JSON or Tuple subcolumns, so for plain columns the change returns the same result as before. The ClickBench Q33 (-8.5%) and Q34 (-10.1%) speedups also show about 11% lower CPU time, but their medians are only slightly below master's current band, and TPC-H Q1 (-20.0%) and Q7 (-25.9%) fall inside or at the edge of that band. That points to differences between the test runs, not to this change. The new prewhere_subcolumn_read_steps performance test is the right place to check the intended effect. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
…zation With `basic` serialization, reading the key subcolumn `m.key_<key>` of a `Map` reads the whole column, so the rewrite gave nothing there, and ClickHouse#107988 had to group PREWHERE conditions by the storage column to keep several keys of one `Map` in one read step. That grouping also merged a cheap subcolumn condition with an expensive condition on the rest of the same column (ClickHouse#124535). The first version of this pull request worked around it with a `Map` key special case in `tryBuildPrewhereSteps`, which put generic PREWHERE code in charge of `Map` serialization details and was wrong for `with_buckets`. Gate the rewrite on the new `IStorage::hasBucketedMapSerialization`, true for a `MergeTree` table if either `map_serialization_version` setting is `with_buckets`, and forwarded by the storages that pass the analyzed query to other tables (`Merge` requires all of them). The check is in `storageAllowsTransformer`, so both passes of `FunctionToSubcolumnsPass` agree. Explicit key subcolumns still work for any serialization. With that, `MergeTreeWhereOptimizer` and `tryBuildPrewhereSteps` group conditions by their exact column set again, and `tryBuildPrewhereSteps` no longer needs `ColumnsDescription`. The `may_throw` split and the read-ahead of a split run stay. Tests that assert the rewrite now pin both map serialization settings, which clickhouse-test randomizes. The new `05340` covers the gate, and `05339` gets the `with_buckets` case from the CI review. Closes: ClickHouse#124535 Related: ClickHouse#124553 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…re-subcolumn-read-steps Keep the query condition cache attribution boundary from master in the PREWHERE step grouping, comparing exact column sets. Drop the `ColumnsDescription` argument from the new seal-gated `MergeTreeSelectProcessor` call site. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The test compares the `arrayElement` and key subcolumn forms of `m['key']`, and the key subcolumn rewrite now applies only to bucketed Maps. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The new `SubcolumnSupportAnswers::bucketed_map_serialization` field was missing from the aggregate initialization, which fails the build with `-Wmissing-field-initializers`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124553&sha=6a84ce82278446b934bb316be58af106c2f4f53b&name_0=PR&name_1=Fast%20test PR: ClickHouse#124553 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
In 04631 the interleaved Map conditions read the same column `tags`, so the last step takes it from the first one instead of reading it again, and only two of the three steps read rows. In 05339 the WHERE optimizer may put `m['k1'] != ''` before `length(m) = 3` based on the column sizes, and the key condition passes every row. Write that case as PREWHERE, which keeps the written order, since the test is about separate read steps, not about the order. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124553&sha=29003da91f5a35f49a43deb35dedd0055448880c&name_0=PR&name_1=Fast%20test PR: ClickHouse#124553 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…re-subcolumn-read-steps Keep the index-aware PREWHERE steps from master (`required_indexes`, `index_read_tasks`), grouping table columns by exact name instead of by storage column, and drop the `ColumnsDescription` argument from the new `tryBuildPrewhereSteps` call. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The WHERE optimizer orders the conditions by the on-disk size of their columns when it has no selectivity estimate. A repeated character compresses to a few bytes per row, so the expensive subcolumn could be ordered first and read for every row. Random values make the on-disk size reflect the cost of reading a column. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124553&sha=0686a448ce0ba3aa70b6aeecc1aa20a2747a7b17&name_0=PR&name_1=Fast%20test PR: ClickHouse#124553 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
CI finish ledger - 06aa3e9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261015-233008 |
…4535-prewhere-subcolumn-read-steps
Cherry pick #124553 to 26.9: Group PREWHERE read steps by exact columns and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
…and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
Backport #124553 to 26.8: Group PREWHERE read steps by exact columns and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
Backport #124553 to 26.9: Group PREWHERE read steps by exact columns and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
Backport #124553 to 26.3: Group PREWHERE read steps by exact columns and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
… its sibling Since ClickHouse#124553, `MergeTreeWhereOptimizer` groups conditions by the exact columns they read, so in `t.safe != '' AND toUInt64(t.val) > 50` the two conditions on subcolumns of one `Tuple` (or `JSON`, or bucketed `Map`) became separate groups and were reordered by size, and `toUInt64` ran on the rows the guard rejects. When a condition that may throw follows a condition over the same physical columns, group all conditions over these physical columns by them again, as before that PR. `tryBuildPrewhereSteps` still splits the group into exact-column steps and filters before the throwing one. Closes: ClickHouse#130086
…and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
…and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
…and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
… and rewrite `m['key']` to a key subcolumn only for bucketed `Map`
|
The backports of this PR to 26.3, 26.8 and 26.9 make the SELECT count() FROM t_guard_tuple WHERE t.safe != '' AND toUInt64(t.val) > 50;I measured the test's three queries (Tuple, JSON, bucketed Map) with official binaries:
The backports split the guard on 26.8 CI already shows it whenever Which do you prefer for 26.3, 26.8 and 26.9:
I have not checked whether #111954 cherry-picks cleanly onto these branches. |
|
Correction to option (a) above: #131110 as it stands makes 26.9 crash with SIGSEGV, and #131109 already does on 26.8.37.168-lts (details: #131054 (comment)). So (a) also needs a fix in #131110 before it lands, while (b) already covers #131109. |
|
Most of the compact-part slowdown of The cause is the first block of each read task. A compact part has no sizes of individual columns, so The patch below starts the main-step columns of a compact part with more rows than
Peak memory of #1/#3 drops from 1.1 GB to 0.19/0.14 GB. With caches dropped, #1/#3 are 18%/14% faster and read the same bytes; with 8 concurrent clients they get 7% more QPS. Results are identical on 22 query variants, 115 related stateless tests have the same outcomes on both builds, and the new test Two cases are left alone because extending the estimate to them made them slower. A column read only by @groeneai could you take a look? Patchdiff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
index 3ac4ca8ab7d..2acdd1b86ab 100644
--- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
+++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
@@ -253,16 +253,34 @@ NameSet injectRequiredColumns(
}
MergeTreeBlockSizePredictor::MergeTreeBlockSizePredictor(
- const MergeTreeDataPartInfoForReaderPtr & data_part_, const Names & columns, const Block & sample_block, bool allow_subcolumns_sizes_calculation_)
+ const MergeTreeDataPartInfoForReaderPtr & data_part_,
+ const Names & columns,
+ const Block & sample_block,
+ bool allow_subcolumns_sizes_calculation_,
+ const NameSet & columns_estimated_by_part_size)
: data_part(data_part_), allow_subcolumns_sizes_calculation(allow_subcolumns_sizes_calculation_)
{
number_of_rows_in_part = data_part->getRowCount();
+ double part_bytes_per_row = 0;
+ if (!columns_estimated_by_part_size.empty() && data_part->isCompactPart() && number_of_rows_in_part)
+ {
+ if (auto part = data_part->getDataPart())
+ part_bytes_per_row
+ = static_cast<double>(part->getTotalColumnsSize().data_uncompressed) / static_cast<double>(number_of_rows_in_part);
+ }
+
/// Initialize with sample block until update won't called.
- initialize(sample_block, {}, columns);
+ initialize(sample_block, {}, columns, /*from_update=*/ false, &columns_estimated_by_part_size, part_bytes_per_row);
}
-void MergeTreeBlockSizePredictor::initialize(const Block & sample_block, const Columns & columns, const Names & names, bool from_update)
+void MergeTreeBlockSizePredictor::initialize(
+ const Block & sample_block,
+ const Columns & columns,
+ const Names & names,
+ bool from_update,
+ const NameSet * columns_estimated_by_part_size,
+ double part_bytes_per_row)
{
/// Columns that are read only by `PREWHERE` steps are absent from the result block (the header of the reading step
/// contains only columns that are used later in the query), but they still occupy memory while the block is being read.
@@ -327,9 +345,13 @@ void MergeTreeBlockSizePredictor::initialize(const Block & sample_block, const C
else
column_size = data_part->getColumnSize(column_from_part ? column_from_part->getNameInStorage() : column_name);
- info.bytes_per_row_global = column_size.data_uncompressed
- ? static_cast<double>(column_size.data_uncompressed) / static_cast<double>(number_of_rows_in_part)
- : static_cast<double>(column_data->byteSize()) / static_cast<double>(std::max<size_t>(1, column_data->size()));
+ if (column_size.data_uncompressed)
+ info.bytes_per_row_global = static_cast<double>(column_size.data_uncompressed) / static_cast<double>(number_of_rows_in_part);
+ else if (part_bytes_per_row > 0 && column_from_part && !info.is_subcolumn && columns_estimated_by_part_size
+ && columns_estimated_by_part_size->contains(column_name))
+ info.bytes_per_row_global = part_bytes_per_row;
+ else
+ info.bytes_per_row_global = static_cast<double>(column_data->byteSize()) / static_cast<double>(std::max<size_t>(1, column_data->size()));
dynamic_columns_infos.emplace_back(info);
}
diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
index f41e99856b8..8dfff200d31 100644
--- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
+++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
@@ -53,7 +53,15 @@ MergeTreeReadTaskColumns getReadTaskColumnsForMerge(
struct MergeTreeBlockSizePredictor
{
- MergeTreeBlockSizePredictor(const MergeTreeDataPartInfoForReaderPtr & data_part_, const Names & columns, const Block & sample_block, bool allow_subcolumns_sizes_calculation);
+ /// A compact part has no sizes of individual columns, so a column of variable size is estimated as zero bytes
+ /// until the first block is read. The columns of variable size in `columns_estimated_by_part_size` start from
+ /// the uncompressed size of all columns of the compact part per row instead, an upper bound for any of them.
+ MergeTreeBlockSizePredictor(
+ const MergeTreeDataPartInfoForReaderPtr & data_part_,
+ const Names & columns,
+ const Block & sample_block,
+ bool allow_subcolumns_sizes_calculation,
+ const NameSet & columns_estimated_by_part_size = {});
/// Reset some values for correct statistics calculating
void startBlock();
@@ -139,7 +147,13 @@ protected:
bool is_initialized_in_update = false;
bool allow_subcolumns_sizes_calculation = false;
- void initialize(const Block & sample_block, const Columns & columns, const Names & names, bool from_update = false);
+ void initialize(
+ const Block & sample_block,
+ const Columns & columns,
+ const Names & names,
+ bool from_update = false,
+ const NameSet * columns_estimated_by_part_size = nullptr,
+ double part_bytes_per_row = 0);
public:
diff --git a/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp b/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
index 76268926f7f..b0b387e9c96 100644
--- a/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
+++ b/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
@@ -542,11 +542,21 @@ MergeTreeReadPoolBase::buildReadTaskInfo(const RangesInDataPart & part_with_rang
sample_block_from_part.insert(ColumnWithTypeAndName(column_in_part->type->createColumn(), column_in_part->type, column_in_part->name));
}
+ /// Without sizes of individual columns, the first block of every task of a compact part has `max_block_size` rows
+ /// regardless of `preferred_block_size_bytes`. Estimate the columns of the main step by the size of the part, they
+ /// are measured from the first block. Columns of `PREWHERE` steps are left as they are: a column read only by
+ /// `PREWHERE` is never measured, so an upper bound would make all blocks of a narrow column small. A part with
+ /// at most `max_block_size` rows is left as well: it is read in one block per task, which is not worth splitting.
+ NameSet columns_estimated_by_part_size;
+ if (data_part_info->isCompactPart() && data_part_info->getRowCount() > block_size_params.max_block_size_rows)
+ columns_estimated_by_part_size.insert(result_column_names.begin(), result_column_names.end());
+
read_task_info.shared_size_predictor = std::make_unique<MergeTreeBlockSizePredictor>(
data_part_info,
Names(all_column_names.begin(), all_column_names.end()),
sample_block_from_part,
- settings[Setting::allow_calculating_subcolumns_sizes_for_merge_tree_reading]);
+ settings[Setting::allow_calculating_subcolumns_sizes_for_merge_tree_reading],
+ columns_estimated_by_part_size);
}
read_task_info.deserialization_prefixes_cache = std::make_shared<DeserializationPrefixesCache>();
diff --git a/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference
new file mode 100644
index 00000000000..ba0827f6ed9
--- /dev/null
+++ b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference
@@ -0,0 +1,4 @@
+Compact
+1 199990000 1
+1 199990000 1
+1 90000
diff --git a/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql
new file mode 100644
index 00000000000..6a66d82b149
--- /dev/null
+++ b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql
@@ -0,0 +1,34 @@
+-- A compact part stores all columns in one file and has no sizes of individual columns, so the block size
+-- predictor estimated a column of variable size as zero bytes until the first block was read: the first block
+-- of every read task had `max_block_size` rows regardless of `preferred_block_size_bytes`.
+-- The columns of the main read step start from the size of all columns of the part per row instead.
+
+DROP TABLE IF EXISTS t_block_size_compact;
+
+-- Compact parts need adaptive granularity; the byte limit is high enough that a granule always has 256 rows.
+CREATE TABLE t_block_size_compact (k UInt64, x UInt64, n String, s String)
+ENGINE = MergeTree ORDER BY k
+SETTINGS index_granularity = 256, index_granularity_bytes = '100Mi', min_bytes_for_wide_part = '10G', min_rows_for_wide_part = 1000000000;
+
+INSERT INTO t_block_size_compact SELECT number, number, toString(number % 10), repeat('a', 2000) FROM numbers(20000);
+
+SELECT part_type FROM system.parts WHERE database = currentDatabase() AND table = 't_block_size_compact' AND active;
+
+-- `s` is about 2000 bytes per row, so the quota allows about 100 rows per block (rounded up to a granule),
+-- far below `max_block_size`. This holds for the first block as well. (`length(s)` would read only the `s.size` subcolumn.)
+SELECT max(blockSize()) < 2048, sum(k), max(s) = repeat('a', 2000)
+FROM t_block_size_compact
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000;
+
+-- The wide column is read by the main step after a `PREWHERE` on a narrow one.
+SELECT max(blockSize()) < 2048, sum(x), max(s) = repeat('a', 2000)
+FROM t_block_size_compact
+PREWHERE k >= 0
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000, query_plan_remove_unused_columns = 1;
+
+-- A narrow column of variable size gets `max_block_size` rows once the first block measured its real size.
+SELECT max(blockSize()) = 8192, sum(toUInt64(n))
+FROM t_block_size_compact
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000;
+
+DROP TABLE t_block_size_compact; |
|
Measuring the columns that only
For #5, peak memory falls from 1.6 GB to 0.2 GB. With caches dropped, #5 takes 332 ms instead of 553 ms and reads the same bytes. With 8 concurrent clients it gets 29% more QPS (2.45 → 3.17). The other rows of the previous table keep their results, except that the single-thread The readers chain already passes the columns that each step has read to a callback, which the runtime dataflow statistics use. When the part has no column sizes (a compact part) and the task has Query results are identical between master and the patch on 30 query variants, including 8 new Updated patch (against master 30c7f43)diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
index 3ac4ca8ab7d..60ea8a5fe20 100644
--- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
+++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp
@@ -253,20 +253,39 @@ NameSet injectRequiredColumns(
}
MergeTreeBlockSizePredictor::MergeTreeBlockSizePredictor(
- const MergeTreeDataPartInfoForReaderPtr & data_part_, const Names & columns, const Block & sample_block, bool allow_subcolumns_sizes_calculation_)
+ const MergeTreeDataPartInfoForReaderPtr & data_part_,
+ const Names & columns,
+ const Block & sample_block,
+ bool allow_subcolumns_sizes_calculation_,
+ const NameSet & columns_estimated_by_part_size)
: data_part(data_part_), allow_subcolumns_sizes_calculation(allow_subcolumns_sizes_calculation_)
{
number_of_rows_in_part = data_part->getRowCount();
+ double part_bytes_per_row = 0;
+ if (!columns_estimated_by_part_size.empty() && data_part->isCompactPart() && number_of_rows_in_part)
+ {
+ if (auto part = data_part->getDataPart())
+ part_bytes_per_row
+ = static_cast<double>(part->getTotalColumnsSize().data_uncompressed) / static_cast<double>(number_of_rows_in_part);
+ }
+
/// Initialize with sample block until update won't called.
- initialize(sample_block, {}, columns);
+ initialize(sample_block, {}, columns, /*from_update=*/ false, &columns_estimated_by_part_size, part_bytes_per_row);
}
-void MergeTreeBlockSizePredictor::initialize(const Block & sample_block, const Columns & columns, const Names & names, bool from_update)
+void MergeTreeBlockSizePredictor::initialize(
+ const Block & sample_block,
+ const Columns & columns,
+ const Names & names,
+ bool from_update,
+ const NameSet * columns_estimated_by_part_size,
+ double part_bytes_per_row)
{
/// Columns that are read only by `PREWHERE` steps are absent from the result block (the header of the reading step
/// contains only columns that are used later in the query), but they still occupy memory while the block is being read.
- /// Their sizes cannot be measured in `update`, so they keep the estimation obtained from the part in the constructor.
+ /// Their sizes cannot be measured in `update`, so they keep their current estimation: the one obtained from the part
+ /// in the constructor, or the one measured by `updateColumnsReadOnlyByPrewhere` if the part has no size of the column.
size_t prewhere_only_fixed_columns_bytes_per_row = 0;
std::vector<ColumnInfo> prewhere_only_dynamic_columns_infos;
if (from_update)
@@ -327,23 +346,80 @@ void MergeTreeBlockSizePredictor::initialize(const Block & sample_block, const C
else
column_size = data_part->getColumnSize(column_from_part ? column_from_part->getNameInStorage() : column_name);
- info.bytes_per_row_global = column_size.data_uncompressed
- ? static_cast<double>(column_size.data_uncompressed) / static_cast<double>(number_of_rows_in_part)
- : static_cast<double>(column_data->byteSize()) / static_cast<double>(std::max<size_t>(1, column_data->size()));
+ info.no_size_in_part = !column_size.data_uncompressed;
+ if (column_size.data_uncompressed)
+ info.bytes_per_row_global = static_cast<double>(column_size.data_uncompressed) / static_cast<double>(number_of_rows_in_part);
+ else if (part_bytes_per_row > 0 && column_from_part && !info.is_subcolumn && columns_estimated_by_part_size
+ && columns_estimated_by_part_size->contains(column_name))
+ info.bytes_per_row_global = part_bytes_per_row;
+ else
+ info.bytes_per_row_global = static_cast<double>(column_data->byteSize()) / static_cast<double>(std::max<size_t>(1, column_data->size()));
+ info.bytes_per_row = info.bytes_per_row_global;
dynamic_columns_infos.emplace_back(info);
}
}
bytes_per_row_global = static_cast<double>(fixed_columns_bytes_per_row);
- for (auto & info : dynamic_columns_infos)
+ bytes_per_row_current = static_cast<double>(fixed_columns_bytes_per_row);
+ for (const auto & info : dynamic_columns_infos)
{
- info.bytes_per_row = info.bytes_per_row_global;
bytes_per_row_global += info.bytes_per_row_global;
+ bytes_per_row_current += info.bytes_per_row;
+
+ max_size_per_row_dynamic = std::max<double>(max_size_per_row_dynamic, info.bytes_per_row);
+ }
+}
+
+bool MergeTreeBlockSizePredictor::hasColumnsWithoutSizeInPart() const
+{
+ return std::ranges::any_of(dynamic_columns_infos, [](const auto & info) { return info.no_size_in_part; });
+}
+
+void MergeTreeBlockSizePredictor::updateColumnsReadOnlyByPrewhere(
+ const ColumnsWithTypeAndName & read_columns, const Block & result_header, double decay)
+{
+ bool updated = false;
+ for (const auto & read_column : read_columns)
+ {
+ /// Columns of the result are measured in `update`.
+ if (!read_column.column || read_column.column->empty() || result_header.has(read_column.name))
+ continue;
+
+ auto it = std::ranges::find_if(dynamic_columns_infos, [&](const auto & info) { return info.name == read_column.name; });
+ if (it == dynamic_columns_infos.end() || !it->no_size_in_part)
+ continue;
+
+ size_t num_rows = read_column.column->size();
+ double local_bytes_per_row = static_cast<double>(read_column.column->byteSize()) / static_cast<double>(num_rows);
+ if (it->measured_in_step)
+ {
+ double alpha = std::pow(1. - decay, num_rows);
+ it->bytes_per_row = alpha * it->bytes_per_row + (1. - alpha) * local_bytes_per_row;
+ }
+ else
+ {
+ /// The first measurement replaces the estimation, as the first block does for the columns of the result.
+ it->bytes_per_row = local_bytes_per_row;
+ it->measured_in_step = true;
+ }
+ if (it->is_subcolumn)
+ it->bytes_per_row = std::max(it->bytes_per_row, it->bytes_per_row_global);
+ updated = true;
+ }
+
+ if (!updated)
+ return;
+
+ /// `update` is not called for a block without columns in the result, so the estimation is recalculated here.
+ bytes_per_row_current = static_cast<double>(fixed_columns_bytes_per_row);
+ max_size_per_row_dynamic = 0;
+ for (const auto & info : dynamic_columns_infos)
+ {
+ bytes_per_row_current += info.bytes_per_row;
max_size_per_row_dynamic = std::max<double>(max_size_per_row_dynamic, info.bytes_per_row);
}
- bytes_per_row_current = bytes_per_row_global;
}
void MergeTreeBlockSizePredictor::startBlock()
diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
index f41e99856b8..ce19e447c87 100644
--- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
+++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h
@@ -53,7 +53,15 @@ MergeTreeReadTaskColumns getReadTaskColumnsForMerge(
struct MergeTreeBlockSizePredictor
{
- MergeTreeBlockSizePredictor(const MergeTreeDataPartInfoForReaderPtr & data_part_, const Names & columns, const Block & sample_block, bool allow_subcolumns_sizes_calculation);
+ /// A compact part has no sizes of individual columns, so a column of variable size is estimated as zero bytes
+ /// until it is measured. The columns of variable size in `columns_estimated_by_part_size` start from
+ /// the uncompressed size of all columns of the compact part per row instead, an upper bound for any of them.
+ MergeTreeBlockSizePredictor(
+ const MergeTreeDataPartInfoForReaderPtr & data_part_,
+ const Names & columns,
+ const Block & sample_block,
+ bool allow_subcolumns_sizes_calculation,
+ const NameSet & columns_estimated_by_part_size = {});
/// Reset some values for correct statistics calculating
void startBlock();
@@ -61,6 +69,15 @@ struct MergeTreeBlockSizePredictor
/// Updates statistic for more accurate prediction
void update(const Block & sample_block, const Columns & columns, size_t num_rows, double decay = calculateDecay());
+ /// Columns that are read only by `PREWHERE` steps are absent from the block passed to `update`. Such a column
+ /// without a size in the part (any column of a compact part) is measured in the block of the step that reads it:
+ /// `read_columns` are the columns read by one step, before filtering, and `result_header` is the header of the result.
+ void updateColumnsReadOnlyByPrewhere(
+ const ColumnsWithTypeAndName & read_columns, const Block & result_header, double decay = calculateDecay());
+
+ /// Whether some column of variable size has no size in the part, so `updateColumnsReadOnlyByPrewhere` may be needed.
+ [[nodiscard]] bool hasColumnsWithoutSizeInPart() const;
+
/// Return current block size (after update())
[[nodiscard]] size_t getBlockSize() const
{
@@ -120,6 +137,10 @@ protected:
/// read from disk (e.g. a Map subcolumn extracts one key but reads the whole Map).
/// When set, `bytes_per_row` will not drop below `bytes_per_row_global`.
bool is_subcolumn = false;
+ /// The part has no size of the column, so `bytes_per_row_global` is not a measurement of it.
+ bool no_size_in_part = false;
+ /// The column was measured by `updateColumnsReadOnlyByPrewhere`.
+ bool measured_in_step = false;
};
std::vector<ColumnInfo> dynamic_columns_infos;
@@ -139,7 +160,13 @@ protected:
bool is_initialized_in_update = false;
bool allow_subcolumns_sizes_calculation = false;
- void initialize(const Block & sample_block, const Columns & columns, const Names & names, bool from_update = false);
+ void initialize(
+ const Block & sample_block,
+ const Columns & columns,
+ const Names & names,
+ bool from_update = false,
+ const NameSet * columns_estimated_by_part_size = nullptr,
+ double part_bytes_per_row = 0);
public:
diff --git a/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp b/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
index 76268926f7f..e1beff7fb74 100644
--- a/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
+++ b/src/Storages/MergeTree/MergeTreeReadPoolBase.cpp
@@ -542,11 +542,20 @@ MergeTreeReadPoolBase::buildReadTaskInfo(const RangesInDataPart & part_with_rang
sample_block_from_part.insert(ColumnWithTypeAndName(column_in_part->type->createColumn(), column_in_part->type, column_in_part->name));
}
+ /// Without sizes of individual columns, the first block of every task of a compact part has `max_block_size` rows
+ /// regardless of `preferred_block_size_bytes`. Estimate the columns by the size of the part instead, they are
+ /// measured from the first block (a column read only by `PREWHERE` in the block of its step). A part with at most
+ /// `max_block_size` rows is left as it is: it is read in one block per task, which is not worth splitting.
+ NameSet columns_estimated_by_part_size;
+ if (data_part_info->isCompactPart() && data_part_info->getRowCount() > block_size_params.max_block_size_rows)
+ columns_estimated_by_part_size = all_column_names;
+
read_task_info.shared_size_predictor = std::make_unique<MergeTreeBlockSizePredictor>(
data_part_info,
Names(all_column_names.begin(), all_column_names.end()),
sample_block_from_part,
- settings[Setting::allow_calculating_subcolumns_sizes_for_merge_tree_reading]);
+ settings[Setting::allow_calculating_subcolumns_sizes_for_merge_tree_reading],
+ columns_estimated_by_part_size);
}
read_task_info.deserialization_prefixes_cache = std::make_shared<DeserializationPrefixesCache>();
diff --git a/src/Storages/MergeTree/MergeTreeReadTask.cpp b/src/Storages/MergeTree/MergeTreeReadTask.cpp
index 5a6cc9ca147..d13c973b5f4 100644
--- a/src/Storages/MergeTree/MergeTreeReadTask.cpp
+++ b/src/Storages/MergeTree/MergeTreeReadTask.cpp
@@ -191,6 +191,21 @@ MergeTreeReadTask::MergeTreeReadTask(
should_continue_sampling);
};
}
+
+ /// Columns that are read only by `PREWHERE` steps are absent from the result block. If the part has no sizes of
+ /// columns (a compact part), the size predictor measures such columns in the columns read by each step.
+ if (size_predictor && !info->task_columns.pre_columns.empty() && size_predictor->hasColumnsWithoutSizeInPart())
+ {
+ read_step_callback = [this](const ColumnsWithTypeAndName & columns,
+ const NameSet & partially_read_columns,
+ size_t read_bytes,
+ std::optional<bool> & should_continue_sampling) -> void
+ {
+ size_predictor->updateColumnsReadOnlyByPrewhere(columns, readers_chain.getSampleBlock());
+ if (dataflow_cache_update_cb)
+ dataflow_cache_update_cb(columns, partially_read_columns, read_bytes, should_continue_sampling);
+ };
+ }
}
/// Returns pointer to the index if all columns in the read step belongs to the read step for that index.
@@ -528,7 +543,8 @@ MergeTreeReadTask::BlockAndProgress MergeTreeReadTask::read()
UInt64 recommended_rows = estimateNumRows();
UInt64 rows_to_read = std::max(static_cast<UInt64>(1), std::min(block_size_params.max_block_size_rows, recommended_rows));
- auto read_result = readers_chain.read(rows_to_read, mark_ranges, patches_mark_ranges, dataflow_cache_update_cb, block_size_params.max_block_size_rows);
+ const auto & step_callback = read_step_callback ? read_step_callback : dataflow_cache_update_cb;
+ auto read_result = readers_chain.read(rows_to_read, mark_ranges, patches_mark_ranges, step_callback, block_size_params.max_block_size_rows);
/// All rows were filtered. Repeat.
if (read_result.num_rows == 0)
diff --git a/src/Storages/MergeTree/MergeTreeReadTask.h b/src/Storages/MergeTree/MergeTreeReadTask.h
index 51b83af0720..a6d8d392726 100644
--- a/src/Storages/MergeTree/MergeTreeReadTask.h
+++ b/src/Storages/MergeTree/MergeTreeReadTask.h
@@ -311,6 +311,10 @@ private:
RuntimeDataflowStatisticsCacheUpdaterPtr updater;
DataflowCacheUpdateCallback dataflow_cache_update_cb;
+
+ /// Passed to the readers chain instead of `dataflow_cache_update_cb` when the size predictor measures the columns
+ /// read by each step; calls `dataflow_cache_update_cb` as well.
+ DataflowCacheUpdateCallback read_step_callback;
};
using MergeTreeReadTaskPtr = std::unique_ptr<MergeTreeReadTask>;
diff --git a/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference
new file mode 100644
index 00000000000..a3ed9ec9781
--- /dev/null
+++ b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.reference
@@ -0,0 +1,6 @@
+Compact
+1 199990000 1
+1 199990000 1
+1 90000
+1 199990000
+1 199990000
diff --git a/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql
new file mode 100644
index 00000000000..e1aa1c74715
--- /dev/null
+++ b/tests/queries/0_stateless/05814_block_size_predictor_compact_part.sql
@@ -0,0 +1,48 @@
+-- A compact part stores all columns in one file and has no sizes of individual columns, so the block size
+-- predictor estimated a column of variable size as zero bytes until the first block was read: the first block
+-- of every read task had `max_block_size` rows regardless of `preferred_block_size_bytes`.
+-- The columns start from the size of all columns of the part per row instead, and are measured from the first block.
+-- A column read only by `PREWHERE` is absent from the result block; it is measured in the block of its step.
+
+DROP TABLE IF EXISTS t_block_size_compact;
+
+-- Compact parts need adaptive granularity; the byte limit is high enough that a granule always has 256 rows.
+CREATE TABLE t_block_size_compact (k UInt64, x UInt64, n String, s String)
+ENGINE = MergeTree ORDER BY k
+SETTINGS index_granularity = 256, index_granularity_bytes = '100Mi', min_bytes_for_wide_part = '10G', min_rows_for_wide_part = 1000000000;
+
+INSERT INTO t_block_size_compact SELECT number, number, toString(number % 10), repeat('a', 2000) FROM numbers(20000);
+
+SELECT part_type FROM system.parts WHERE database = currentDatabase() AND table = 't_block_size_compact' AND active;
+
+-- `s` is about 2000 bytes per row, so the quota allows about 100 rows per block (rounded up to a granule),
+-- far below `max_block_size`. This holds for the first block as well. (`length(s)` would read only the `s.size` subcolumn.)
+SELECT max(blockSize()) < 2048, sum(k), max(s) = repeat('a', 2000)
+FROM t_block_size_compact
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000;
+
+-- The wide column is read by the main step after a `PREWHERE` on a narrow one.
+SELECT max(blockSize()) < 2048, sum(x), max(s) = repeat('a', 2000)
+FROM t_block_size_compact
+PREWHERE k >= 0
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000, query_plan_remove_unused_columns = 1;
+
+-- A narrow column of variable size gets `max_block_size` rows once the first block measured its real size.
+SELECT max(blockSize()) = 8192, sum(toUInt64(n))
+FROM t_block_size_compact
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000;
+
+-- The wide column is read only by `PREWHERE`: it is absent from the result, but its blocks stay small.
+-- (`s != ''` would read only the `s.size` subcolumn.)
+SELECT max(blockSize()) < 2048, sum(k)
+FROM t_block_size_compact
+PREWHERE s LIKE 'a%'
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000, query_plan_remove_unused_columns = 1;
+
+-- A narrow column read only by `PREWHERE` is measured as well and gets `max_block_size` rows after the first block.
+SELECT max(blockSize()) = 8192, sum(k)
+FROM t_block_size_compact
+PREWHERE n LIKE '_'
+SETTINGS max_threads = 1, max_block_size = 8192, preferred_block_size_bytes = 200000, query_plan_remove_unused_columns = 1;
+
+DROP TABLE t_block_size_compact; |
|
I opened #132445 for queries 1 and 3. It is narrower than the patch: the read pool computes the part's uncompressed size per row, and the predictor uses it as the minimum estimate of the first block only, for compact parts with more rows than The measurement of columns read only by |
… layout Queries 0 and 1 of `prewhere_subcolumn_read_steps` (added in ClickHouse#124553) are noisy on arm: on master between 2026-11-12 and 2026-11-21 the medians of the two servers differ by more than 10% in 39% / 42% of 440 arm runs (81 CI flags, 79 on arm), while the in-run spread is about 1%. The two servers read different part layouts. perf.py fills both servers and stops merges only after the whole setup, so the background merges of the JSON table race the following `Map` INSERT: arm servers read 6 to 23 parts, amd almost always 23. A zero-level part keeps the JSON shared data as `map_with_buckets` (`object_shared_data_serialization_version_for_zero_level_parts`), a merged one as `advanced`, and reading `j.kind` from the former decodes the shared data of every row. In CI, arm query 1 used 97 ms of user CPU at 6 parts and 313 ms at 23. 97% of the arm runs over 10% had different part counts on the two servers; with equal counts 2.7% were over 10%. Measured locally on one server: 200 ms of user CPU with 23 zero-level parts, 31 ms with one merged part, 34 ms with 23 zero-level parts written as `advanced`. The queries cannot be changed in place (their history would change level), so they are disabled and appended as queries 3 and 4 on a new table, `t_prewhere_json_v2`, whose merges are stopped before its INSERT. The INSERT cuts the data by rows (48 blocks of 62500 rows, squashed in pairs), so every server reads 24 zero-level parts of 125000 rows, which a `throwIf` on `system.parts` asserts. The `Map` query and its table are unchanged. Related: ClickHouse#100759 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The check of the tests a PR adds or changes (ClickHouse#129330) failed a PR only when a query's time grows run over run on the tested server. A test whose runs are noisy without a trend passed its own PR, and in master_head PR mode the report's own unstable/changed verdict never fails a PR. That is how system_clusters_replicated_databases (ClickHouse#122223) got in: tested-server spread (stddevPop / median of its runs) 0.41-2.1 in its PR, now > 0.5 on both master servers in about 99% of runs and the noisiest test on master. The check now also fails on an unstable query of such a test: - PR changes only files under tests/ and the reference is the performance reference build of the tested master commit's sources (find_prev_build's new third value; a reference of an older commit, as in about a quarter of PR jobs, does not count): both servers run the same code built the same way, so the report's verdict judges the test; fail on changed_fail or unstable_fail of report/all-queries.tsv. A query that failed on the reference server and ran only on the tested one is not in that file; it is judged by the rule below. - Any other PR or reference (code changes, the official-build fallback, or an older reference): the report measures the PR's change, not the test (the floors flag 79% of the heads of the 214 code PRs that changed a perf test in 2026-11-12..21, their own speedups). Fail when stddevPop / median of the tested server's runs is above 0.5 (at least 5 runs). A spread the change causes also fails: after the merge both master servers run that code. The bar 0.5 flags 0.5% of those code-PR heads and 0.2% of quiet tests' master heads (CIDB backtest), and all 4 jobs of ClickHouse#122223. A query the trend check already reports gets only its trend row. The reading loop of find_run_trends moves to read_query_runs, shared by both checks; run_trend_gate becomes changed_tests_gate. Validated locally on downloaded job logs (no test of the test infrastructure): ClickHouse#122223's 4 jobs fail (the old check passes them); the new tests of ClickHouse#129328, ClickHouse#124553, ClickHouse#131203 (code PRs) and the tests-only ClickHouse#130763, ClickHouse#129627 pass; the run-trend output is unchanged on all 1754 tests of 14 jobs. Related: ClickHouse#100759 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #124535
Related: #107988
Related: #107912
Related: #111954
Related: #114150
Since #107988,
MergeTreeWhereOptimizerandtryBuildPrewhereStepsgroupPREWHEREconditions by the storage column they read instead of by the exact columns. The reason was the rewrite ofm['key']to theMapkey subcolumnm.key_<key>: withbasicserialization a key subcolumn reads the wholeMap, so N keys in N read steps read theMapN times (#107912). The same grouping merges a cheap subcolumn condition with an expensive condition on the rest of the column: in #124535,j.kind = 'b' AND length(toString(j)) > 10reads and serializes the wholejfor every row.This PR removes the cause instead of teaching the
PREWHEREcode aboutMap:m['key']is rewritten tom.key_<key>only when the table uses bucketedMapserialization. The newIStorage::hasBucketedMapSerializationis true for aMergeTreetable if eithermap_serialization_versionsetting iswith_buckets;Merge,MaterializedView,Buffer,Alias,MaterializedPostgreSQLand proxies answer for the tables they read, andMergerequires all of them. The check is instorageAllowsTransformer, so both passes ofFunctionToSubcolumnsPassagree. Explicitly written key subcolumns still work for any serialization.MergeTreeWhereOptimizerandtryBuildPrewhereStepsgroup conditions by the exact columns they read again. A condition on a subcolumn and a condition on the whole column or on another subcolumn of it get separate steps, while conditions on virtual columns of one index still share a step. Withbasicserialization allm['kN']conditions readmand share one step. Themay_throwsplit from Do not evaluate a potentially throwing PREWHERE condition ahead of its guard #111954 and the read-ahead of a split run are unchanged, andtryBuildPrewhereStepsno longer needsColumnsDescription.Keys of a bucketed
Mapthat land in the same bucket are read once per step, as before #107988. Avoiding repeated reads of physical streams shared between steps is a general reader improvement and is left for a separate change.An earlier revision of this PR kept the storage-column grouping and folded
Mapkey subcolumns into theirMapinsidetryBuildPrewhereSteps, which made genericPREWHEREcode depend onMapserialization details and was wrong forwith_buckets.Expected performance comparison changes: tables with the default
basicMapserialization read the wholeMapform['key']again, soget_map_value,map_lowcardinality_key_lookupandserialization_pool_lookupmay move.map_bucketed_serialization.xmlnow actually useswith_buckets, which its comment already claimed.Tests:
05340_map_element_to_subcolumn_bucketed_onlycovers the rewrite gate, includingMerge,MaterializedViewandBuffer.05339_prewhere_subcolumn_read_stepschecks that a condition on a cheap subcolumn keeps the rest of the column unread forJSON,TupleandMap, including awith_bucketskey next to the wholeMap; its payloads are random, so that the on-disk sizes by whichWHEREconditions are ordered reflect the cost of reading. Tests that assert the rewrite now pin both map serialization settings, whichclickhouse-testrandomizes.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
PREWHEREcondition on a subcolumn (for examplej.kind = 'b'on aJSONcolumn) is again evaluated in its own read step, so the rest of the column is read only for the rows that pass it.m['key']is now rewritten to theMapkey subcolumn only for tables withwith_bucketsMapserialization, where it reads a single bucket; withbasicserialization the wholeMapis read once, as before 26.3. Closes #124535.Workflow [PR]
Sync PR [sync-upstream/pr/124553]
Version info
26.11.1.1442-master(included in26.11and later)