Skip to content

Read the smallest on-disk column when a query reads no columns - #107368

Closed
groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-106597-read-smallest-column-by-disk-size
Closed

groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-106597-read-smallest-column-by-disk-size

Conversation

@groeneai

@groeneai groeneai commented Jun 12, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

When a query reads no real columns (for example SELECT isNullable(lc) FROM t, where the result is constant and depends only on the type), the MergeTree reader now picks the column that is cheapest to read from disk to carry the row count, instead of the one with the smallest in-memory value size. The previous metric mis-ranked compactly stored columns such as LowCardinality(String) below a UInt64, causing the reader to read a much larger column off disk.

Description

Closes: #106597

SELECT isNullable(lc) FROM test_lc is constant-folded away (isNullable depends only on the column type), so ReadFromMergeTree is left with no columns to read and must pick one column just to know the number of rows. selectRangesToRead picked it with ExpressionActions::getSmallestColumn, which ranks by the in-memory value size: a UInt64 is 8 bytes, while a LowCardinality(String) falls back to a heuristic of 100. So it chose the UInt64 column x, which is far more expensive to read off disk than the dictionary-encoded lc.

This PR makes the fallback pick the column with the minimum on-disk compressed size via the existing IMergeTreeDataPart::getColumnNameWithMinimumCompressedSize helper. That is the same metric the read path already uses in injectRequiredColumns, so the two carrier-selection sites now agree. It falls back to getSmallestColumn only when there are no parts to measure.

Verified locally with ReadCompressedBytes on the perf-test table (x UInt64, lc LowCardinality(Nullable(String)), 1e7 rows):

Query Before After
SELECT isNullable(lc) 40 MB (reads x) 1.7 MB (reads lc)
SELECT 1 FROM test_lc 40 MB (reads x) 1.7 MB (reads lc)
SELECT isNullable(big) on (tiny UInt8, big String) 85 KB (reads tiny) 85 KB (reads tiny)

The last row is the no-regression check: when a small column is genuinely cheaper than the referenced one, the choice is unchanged. Added a regression test 04337_read_smallest_column_by_disk_size that fails before this change and passes after it.


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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On (x UInt64, lc LowCardinality(Nullable(String))) with 1e7 rows, SELECT isNullable(lc) FROM test_lc reads ReadCompressedBytes: 40,049,420 (column x, 38 MiB) every run, while sibling queries isConstant/isNull/isNotNull(lc) read 1,777,606 (column lc, 1.7 MiB).
b Root cause explained? isNullable is constant-folded (output depends only on the type), so the position-based unused-column removal added in #100586 prunes lc and leaves ReadFromMergeTree with no columns. selectRangesToRead then falls back to ExpressionActions::getSmallestColumn, which ranks by in-memory value size: UInt64=8 bytes vs LowCardinality=heuristic 100, so it picks x. x is dense and unique (~38 MiB on disk) while lc is dictionary-encoded (~1.7 MiB), so the reader pulls ~22x more data off disk.
c Fix matches root cause? Yes. The fallback now ranks by on-disk compressed size via the existing IMergeTreeDataPart::getColumnNameWithMinimumCompressedSize, the same metric the read path uses in injectRequiredColumns. This targets the wrong cost metric directly, not a symptom.
d Test intent preserved / new tests added? New regression test 04337_read_smallest_column_by_disk_size asserts the cheap on-disk column is the carrier (via ProfileEvents['ReadCompressedBytes']). No existing test weakened.
e Both directions demonstrated? Yes, with Build-ID-verified binaries. No-fix binary (Build ID f85dcf3f...): test returns 0 and FAILS. Fix binary (Build ID c41219fc...): test returns 1 and PASSES.
f Fix is general, not a narrow patch? Yes. It fixes the cost metric for every all-pruned read, not just this query (e.g. SELECT 1 FROM test_lc also improves from 40 MiB to 1.7 MiB). No-regression check: SELECT isNullable(big) on (tiny UInt8, big String) still reads tiny (85 KB), not big (40 MB) - the on-disk metric never picks a larger column than necessary. The naive "keep the referenced column" alternative would have regressed exactly that case.

Note: measured on x86 (the build machine); the regression reported on ARM is the cost of reading the larger column off disk through the planning/exec path on a tiny query, which is architecture-independent and directly observed here via ReadCompressedBytes.

Session id: cron:clickhouse-worker-slot-0:20260612-201200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @davenger — could you review this? When a query reads no real columns (e.g. isNullable(lc) constant-folds away), ReadFromMergeTree::selectRangesToRead falls back to getSmallestColumn (in-memory size), which picks a UInt64 over a LowCardinality(String) that is far cheaper to read off disk. This switches the fallback to getColumnNameWithMinimumCompressedSize (on-disk size, the metric injectRequiredColumns already uses), recovering the low_cardinality_argument q0 regression from #106597 with no degradation when a small column is genuinely cheaper.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jun 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ae9d462]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05317_local_read_throttler_filesystem_cache FAIL cidb
02346_non_negative_derivative NOT_FAILED cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
AST fuzzer (amd_release, oracle) FAIL
AST fuzzer oracle mismatch FAIL cidb

AI Review

Summary

This PR improves no-output MergeTree reads by replacing the old in-memory-width heuristic with an on-disk-size-based carrier choice, and the earlier correctness issues around schema-evolved parts, projection pruning, and bucket pruning look addressed in the current code. However, the remaining getColumnSize-based ranking still has two merge-blocking performance regressions on the hot SELECT count() / constant-only path, and there is still one late-stage pipeline mutation that leaves dead carrier work on FINAL queries with deferred filters. I would not merge it in the current form.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:199] chooseColumnToReadForNoColumnsQuery still ranks candidates with IMergeTreeDataPart::getColumnSize, but that cache is a deduplicated table-total figure, not the cost of reading one column in isolation. On wide parts with shared substreams (for example Nested with share_nested_offsets = 1), the later sibling gets the shared stream charged to the earlier one, so the new ranking can pick a carrier that reads more bytes than master on count() / constant-only queries. Suggested fix: rank by an accessor that prices one candidate independently, or refuse the on-disk ranking when a candidate shares streams with a sibling.
  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:199] The same getColumnSize call lazily triggers calculateColumnsAndSecondaryIndicesSizesOnDiskUnlocked() on cold parts. That turns a path that used to stay on cheap metadata/in-memory heuristics into a full column-size and secondary-index scan, including storage-overlay / Keeper traffic in metadata-in-Keeper deployments, just to choose the row-count carrier. Suggested fix: only use the on-disk ranking when areColumnAndSecondaryIndexSizesCalculated() is already true; otherwise fall back to ExpressionActions::getSmallestColumn.

⚠️ Majors

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:5321] The carrier is still injected before deferred FINAL filters add their required physical columns at src/Processors/QueryPlan/ReadFromMergeTree.cpp:5350. So a query such as SELECT count() ... FINAL with a deferred row policy / PREWHERE still pays the carrier-selection walk and can read an extra carrier column even though the deferred filter already makes the read set non-empty. Suggested fix: move carrier injection after the deferred-filter block, or recompute/skip it once those required columns are known.
Final Verdict

❌ Not ready to merge: the two unresolved getColumnSize regressions at src/Processors/QueryPlan/ReadFromMergeTree.cpp:199 still need a redesign or a safe fallback, and the deferred-filter path at src/Processors/QueryPlan/ReadFromMergeTree.cpp:5321 still leaves avoidable extra work on real queries.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 query(s) improved out of 31 analysed

Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there.

This PR only changes how ReadFromMergeTree picks a fallback column for queries that read no real columns (for example count() with trivial-count optimizations off, or isNullable(x)). It now ranks candidates by on-disk compressed size instead of in-memory size. None of the flagged ClickBench or TPC-H queries is that kind of query, so all directional improvements except one were downgraded to not_sure. ClickBench Q32 (-46.1%) is too large to override, but it reads real columns, so it is most likely an upstream gain. All flags are improvements, and the base build (26.9) is older than the source (26.10), so a baseline built on the PR's exact merge-base would show this PR as performance-neutral on these benchmarks.

clickbench

🟢 1 improved · ⚠️ 5 inconclusive

Flagged queries (6 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 32 improvement 1342 724 -46.1% <0.0001 aggregation: The -46.1% is a large, locked delta backed by a big CPU drop. This high-cardinality GROUP BY reads real columns, so the gain most likely comes from changes between base and source, not from this diff.
⚠️ 16 not_sure 616 514 -16.5% <0.0001 aggregation: This GROUP BY query reads real columns, so it never reaches the no-columns fallback column that this PR changes. The -16.5% cannot be attributed to the diff.
⚠️ 18 not_sure 1064 808 -24.1% <0.0001 aggregation: This aggregation reads real columns and never takes the no-columns fallback read path this PR changes. The -24.1% on a noisy query is not attributable to the diff.
⚠️ 28 not_sure 1061 1005 -5.3% <0.0001 aggregation: Borderline -5.3% where the two tests disagree. The query reads real columns, so the changed fallback-column logic does not run.
⚠️ 33 not_sure 1236 992 -19.7% <0.0001 aggregation: This GROUP BY reads real columns and never takes the no-columns fallback read path. The -19.7% on a noisy query is not attributable to the diff.
⚠️ 34 not_sure 1244 1005 -19.2% <0.0001 aggregation: This GROUP BY reads real columns and never takes the no-columns fallback read path. The -19.2% on a noisy query is not attributable to the diff.

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_official

⚠️ 5 inconclusive

Flagged queries (5 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 66 52 -21.2% <0.0001 aggregation: Q1 aggregates over real lineitem columns and never needs a fallback column. The -21.2% (14 ms on a noisy, fast query) is not attributable to the diff.
⚠️ 7 not_sure 82 60 -26.8% <0.0001 join_operator: This multi-join query reads real columns from every table, so the changed fallback-column path never runs. The -26.8% is not attributable to the diff.
⚠️ 8 not_sure 90 76 -15.6% <0.0001 join_operator: This multi-join query reads real columns from every table, so the changed fallback-column path never runs. The -15.6% is not attributable to the diff.
⚠️ 9 not_sure 104 86 -16.9% <0.0001 join_operator: This multi-join query reads real columns from every table, so the changed fallback-column path never runs. The -16.9% is not attributable to the diff.
⚠️ 17 not_sure 100 60 -40.0% <0.0001 join_operator: Q17 reads lineitem and part columns for a correlated subquery and never takes the no-columns fallback read. The -40.0% also shows a very noisy baseline, so it is not attributable to the diff.

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
  • StressHouse run: 4c55a300-ec66-4059-bf8b-d6ebb7cef2c0
  • MIRAI run: f2c7f71c-e60c-4e32-85c7-87d2ed9b6e2f
  • PR check IDs:
    • clickbench_754942_1791660383
    • clickbench_754948_1791660383
    • clickbench_754970_1791660383
    • tpch_adapted_1_official_754985_1791660384
    • tpch_adapted_1_official_755000_1791660383
    • tpch_adapted_1_official_755014_1791660383

@groeneai
groeneai force-pushed the fix-106597-read-smallest-column-by-disk-size branch from bb97bb2 to 06e574b Compare June 12, 2026 23:57
When a query references a column whose result is constant-folded away (for
example isNullable(lc), which depends only on the type), ReadFromMergeTree
ends up with no columns to read and must pick one column just to know the
number of rows. It picked the column with the smallest in-memory value size
via ExpressionActions::getSmallestColumn. That metric mis-ranks compactly
stored columns: a LowCardinality(String) is tiny on disk but looks larger in
memory than a UInt64 (8 bytes), so the reader read the larger UInt64 column
and pulled far more data off disk than necessary.

Pick the column with the minimum on-disk compressed size instead, using the
existing IMergeTreeDataPart::getColumnNameWithMinimumCompressedSize helper.
This is the same metric the read path already uses in injectRequiredColumns,
so the two carrier-selection sites now agree. Fall back to getSmallestColumn
only when no parts are available.

This recovers the low_cardinality_argument performance test query 0
(SELECT isNullable(lc) FROM test_lc) without degrading the case where a small
column is genuinely cheaper than the referenced one.

The regression test uses ORDER BY tuple() so the table has no sorting-key
column. With a sorting key, the split-ranges read path (controlled by the
randomized merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability
testing setting) additionally reads the key column to merge intersecting
ranges, which inflated ReadCompressedBytes past the assertion threshold
regardless of the carrier column and made the test flaky. Removing the
sorting key keeps the carrier choice the only thing that decides what is read.

Closes: ClickHouse#106597

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-106597-read-smallest-column-by-disk-size branch from 06e574b to ae4fddf Compare June 13, 2026 01:32
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (test-determinism follow-up, commit ae4fddf)

The previous commit's regression test 04337_read_smallest_column_by_disk_size was flaky in CI (amd_debug 153/162, arm_binary 27/142, and the flaky-check job). This commit makes the test deterministic. The source fix in ReadFromMergeTree.cpp is unchanged.

# Question Answer
a Deterministic repro? Yes. Binary-searched the full amd_debug randomized-settings string from CIDB down to a single setting: merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability. With it at 1.0 (and max_threads>1) the old test reads x (~4 MB) every time; at 0.0 it reads lc (5861 B) every time.
b Root cause explained? The split-ranges injection (a PartsSplitter testing knob) takes the path at ReadFromMergeTree.cpp:1138-1160, which adds getColumnsRequiredForSortingKey() to the columns to read so it can merge intersecting ranges. The table was ORDER BY x, so the PK column x (~4 MB) was read in addition to the carrier lc, inflating ReadCompressedBytes past the 1 MB assertion. This is independent of which carrier column the fix picks. CI rates match the per-run injection probability (amd_debug 0.93 -> 94% fail; arm_binary 0.18 -> 19% fail).
c Fix matches root cause? Yes. The test now uses ORDER BY tuple() (no sorting key), so the split-ranges path has no key column to add and never reads x. This removes the confound at its source rather than silencing the setting (no no-random-settings, no pinning the injection to 0).
d Test intent preserved / new tests added? Preserved. The test still asserts the carrier is the on-disk-smallest column: baseline reads lc (5861 B), not x (~4 MB). The old getSmallestColumn metric would pick x (smaller in memory) and read ~4 MB > 1 MB, so the test still fails on the pre-fix binary. no-random-merge-tree-settings is retained because index_granularity=1 legitimately bloats lc on disk past 1 MB.
e Both directions demonstrated? Yes. Pre-fix getSmallestColumn selects x (~4 MB read) -> assertion fails; fix selects lc (5861 B) -> passes. Re-validated through clickhouse-test --test-runs 50 --random-settings 1 (the same configuration the CI flaky-check uses): 50/50 PASS. Also verified directly with injection_probability=1.0 max_threads=4: reads lc (6115 B), PASS.
f Fix is general, not a narrow patch? N/A for this commit (test-only change). The source fix (unchanged) targets the empty-column fallback in selectRangesToRead and uses the same on-disk-size metric that injectRequiredColumns already uses, so the two carrier-selection sites agree.

Note: the flaky-check "Server died" verdict was investigated and is NOT a real server crash. The flaky-check ran only this test 50x, hit the failure cap on the same 0-vs-1 reference mismatch, and reported "Server died"; clickhouse-server.err.log shows no <Fatal>/signal/sanitizer and dmesg.log shows no OOM. It shares the single root cause above and is resolved by the same change.

Session id: cron:clickhouse-worker-slot-0:20260613-010900

…-evolved parts

The previous commit on this branch switched the no-columns-to-read carrier
selection in selectRangesToRead from ExpressionActions::getSmallestColumn
(in-memory size) to IMergeTreeDataPart::getColumnNameWithMinimumCompressedSize
measured on parts.front(). That has two problems, both raised in review:

1. The carrier is global to the read but was sampled from a single part. A
   column that is tiny in the first part but dense in the later (larger) parts
   would be picked, and since injectRequiredColumns then finds it physically
   present, the read would still pull the large column for most of the table.

2. getColumnNameWithMinimumCompressedSize throws LOGICAL_ERROR when the measured
   part has files for none of the columns it is given. A selected part can be in
   that state when it predates the current schema (e.g. written with column `a`
   while the metadata has since added `c DEFAULT` and dropped `a`), so a query
   reading no columns (SELECT 1 FROM t FORMAT Null) crashed the server.

Sum each current physical column's compressed size over all selected parts and
pick the global minimum. Only parts that actually have a column's files
contribute, so a schema-evolved part simply does not vote; if no current column
has files in any part, fall back to getSmallestColumn. The carrier stays a
current metadata column, so it resolves against the StorageSnapshot and the
per-part read setup substitutes missing columns as before.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-106597-read-smallest-column-by-disk-size branch from 432e9a7 to 3755e7c Compare June 13, 2026 01:57
@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up commit 3755e7c addresses both review findings (schema-evolved-part LOGICAL_ERROR and single-part carrier sampling).

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Finding #2 (LOGICAL_ERROR): CREATE TABLE t (a,b) ... ; INSERT; DETACH PART; ALTER ADD c DEFAULT; DROP a; DROP b; ATTACH PART; SELECT 1 FROM t FORMAT Null aborts master HEAD every time. Finding #1 (wrong carrier): a table with x=0 in a small first part and dense x in two larger parts deterministically reads x (~7.6 MiB) under the old front-part sampling.
b Root cause explained? The no-columns carrier was measured on parts.front() via getColumnNameWithMinimumCompressedSize. (1) The carrier is global, so a column cheap only in the first part is read large for the rest of the table. (2) That helper throws LOGICAL_ERROR when the measured part has files for none of the current columns, which happens for a part that predates the current schema.
c Fix matches root cause? Yes. Carrier is now the global minimum of compressed size summed over all selected parts; parts contribute only columns they physically have (hasColumnFiles), so schema-evolved parts do not vote and the throwing helper is no longer called on this path; fall back to getSmallestColumn when no part has any current column.
d Test intent preserved / new tests added? Yes. The original on-disk-cost assertion is kept; added a multi-part outlier case (asserts the read stays < 1 MB) and a schema-evolved all-pruned case (asserts graceful NO_SUCH_COLUMN_IN_TABLE instead of a crash).
e Both directions demonstrated? Yes. Without the fix: server aborts (finding #2) / reads 7.64 MiB (finding #1). With the fix: graceful error + server alive, and ReadCompressedBytes = 15300. Test passes 10/10 on the fixed binary.
f Fix is general, not a narrow patch? Yes. Single carrier-selection site; the symmetric read-time site (injectRequiredColumns) already has the equivalent guard, which this now matches. The fix targets the metric (aggregate on-disk size) and the missing-files invariant, not the crash symptom.

Session id: cron:clickhouse-worker-slot-1:20260613-003600

The aggregate on-disk size used to rank carrier candidates is only
meaningful for wide parts. Compact parts keep every column in one file
and report a per-column data_compressed of 0, so summing it tied every
column at 0 and the carrier fell to the first metadata column, which can
be the most expensive one to read.

Restrict the candidates to columns physically present in every selected
part, rank those by the aggregate on-disk size when it is positive, and
fall back to ExpressionActions::getSmallestColumn (the in-memory
heuristic) otherwise. Requiring presence in every part also keeps the
carrier from being a column stored only in a new part after schema
evolution, which would otherwise force a DEFAULT materialization that
pulls a large dependency column on the parts where the carrier is
missing.

Extends 04337 with a compact-part scenario that fails before this change
(the carrier reads the dense String column instead of the UInt8).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (follow-up commit 4175aff, finding #3)

# Question Answer
a Deterministic repro? Yes. Default compact part (big String, tiny UInt8), SELECT 1 FROM t FORMAT Null: ProfileEvents['ReadCompressedBytes'] = 21438 (carrier big) on the prior commit, 355 (carrier tiny) after the fix. SELECT tiny=210, SELECT big=21438 as baselines.
b Root cause explained? MergeTreeDataPartCompact::calculateEachColumnSizes leaves the per-column map empty, so getColumnSize(col).data_compressed==0 for every compact-part column while hasColumnFiles is true. The aggregate sum tied every column at 0 and the < smallest_size scan kept the first one, never reaching the getSmallestColumn fallback.
c Fix matches root cause? Yes. Rank by aggregate on-disk size only when it is positive; fall back to getSmallestColumn when no candidate has a meaningful size (compact/fresh parts). Candidates are also restricted to columns present in every part, so a new-part-only column is never the carrier (removes the DEFAULT-injection path the bot flagged).
d Test intent preserved / new tests added? 04337 gains a compact-part scenario (isNullable(tiny), asserts ReadCompressedBytes < 5000). Existing wide / multi-part / evolved-pruned scenarios unchanged.
e Both directions demonstrated? Yes. New scenario returns 0 (assertion fails) on the prior commit (Build ID 23cecb4e1e) and 1 after (e3eeb90ba8); full test 10/10 deterministic on the fixed binary.
f Fix is general, not a narrow patch? Yes. The same compact-part 0-size pitfall already existed at the read-time site (injectRequiredColumns -> getColumnNameWithMinimumCompressedSize), which falls back on hasColumnFiles; this planner-side path now matches that behavior and additionally guarantees the carrier is readable in every part.

Session id: cron:clickhouse-worker-slot-0:20260613-023600

The count() on the all-pruned part is deterministic only via the trivial
count optimization, which reads the row count from part metadata. With
optimize_trivial_count_query and optimize_use_implicit_projections both
randomized off (as the flaky check does), count() takes the no-columns
read path, hits the unreadable part and throws NO_SUCH_COLUMN_IN_TABLE.
Pin the setting so the row count stays metadata-derived regardless of
randomization.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Also fixed a flaky-check failure the msan run surfaced on the new 04337 schema-evolved scenario (commit 499a2f2):

SELECT count() FROM t_evolved_pruned
→ Code: 16. There is no column a in table. (NO_SUCH_COLUMN_IN_TABLE)

count() on the all-pruned part is deterministic only via the trivial-count optimization (row count from part metadata). With optimize_trivial_count_query=0 and optimize_use_implicit_projections=0 both randomized off, count() takes the no-columns read path, hits the unreadable part and throws. Pinned optimize_trivial_count_query=1 on that line; verified A/B (fails under the two forced settings before, returns 3 after; 5/5 deterministic).

A compact part stores all columns in one file and reports a per-column
on-disk size of 0. Summing the aggregate compressed size over all parts
therefore ignores the compact part entirely: in a mixed compact/wide
layout, a column that is small in a tiny wide part but huge in a dominant
compact part could still win the ranking and become the carrier, reading
the whole expensive column off the compact part.

Only rank a candidate by aggregate on-disk size when every selected part
reports a positive size for it; otherwise leave it unranked and fall back
to the in-memory heuristic (getSmallestColumn), which ranks a UInt8 below
a String. This is the same fallback already used for the all-compact and
heavily-schema-evolved cases.

Extend 04337 with a mixed compact/wide scenario, and pin
query_plan_remove_unused_columns: when it is disabled the planner keeps an
unused column as a read input instead of reaching the carrier path, which
would read megabytes and break the byte-count assertions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit ad3f1da)

# Question Answer
a Deterministic repro? Yes. Isolated the trigger by binary search over the 173 randomized settings of a failing CI-style run down to a single setting: query_plan_remove_unused_columns = 0. With it, the mixed compact/wide carrier reads 60248482 bytes (big) on demand, every time; with it on, 3876 (tiny). The bot's underlying carrier bug also reproduces deterministically without randomization (compact part reports size 0).
b Root cause explained? Two linked issues. (1, the bot's finding) The carrier ranking summed aggregate on-disk size over all parts; a compact part reports a per-column size of 0, so in a mixed compact/wide layout the wide part's sizes alone decided the ranking and a column expensive on the dominant compact part could win. (2, the test-flakiness) The no-columns carrier path is only reached after the unused column input is pruned; query_plan_remove_unused_columns=0 (CI-randomized) keeps an arbitrary column as a read input, so ReadFromMergeTree reads that column directly and the byte assertions break.
c Fix matches root cause? Yes. (1) Rank a candidate by on-disk size only when every selected part reports a positive size for it; otherwise leave it unranked and fall back to getSmallestColumn — directly the bot's primary suggestion. (2) Pin query_plan_remove_unused_columns = 1 in the test so the carrier path is actually exercised. No assertion was weakened.
d Test intent preserved / new tests added? Yes. Added a mixed compact/wide scenario to 04337 asserting ReadCompressedBytes < 100000 for the carrier read (it was ~60 MB before the fix). Existing scenarios unchanged.
e Both directions demonstrated? Yes. New scenario returns 60248482 (carrier=big, assertion fails) on the pre-fix binary and 3876 (carrier=tiny, passes) after, confirmed by rebuild (Build ID e3eeb90ba8 -> 77f9e2089... then ad3f1da). Full 04337 with randomization: 150/150 pass (was ~5% flaky before pinning the setting).
f Fix is general, not a narrow patch? Yes. The gate is per-candidate and applies to every part layout (all-wide, all-compact, mixed, schema-evolved) at the single carrier-selection site in selectRangesToRead. It is not a guard against one symptom: an unmeasurable part now disqualifies the on-disk metric for that candidate and routes to the same in-memory fallback already used for the all-compact and schema-evolved cases. The symmetric mixed case degrades to the long-standing pre-PR getSmallestColumn behavior, i.e. no regression.

Session id: cron:clickhouse-worker-slot-0:20260613-034000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on ad3f1da.

The only red is Fast test (arm_darwin): 04327_rewrite_aggregate_function_with_if_distributed + 04336_parallel_blocks_marshalling_low_cardinality_native_format. Both are the known macOS connect-timeout infra flake (return code 23, ConnectionPoolWithFailover on 127.0.0.x which is unbindable on Darwin), not related to this PR's ReadFromMergeTree change: in the last 14 days 04336 hit 55 unrelated PRs and 04327 hit 15. They are skipped on Darwin by #107376.

04337_read_smallest_column_by_disk_size and all four sanitizer flaky-checks (asan/msan/tsan/debug) are green on this commit. Mergeable Check / PR reds are aggregators of the arm_darwin flake.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on ad3f1da. The only red is Fast test (arm_darwin), failing on 04336_parallel_blocks_marshalling_low_cardinality_native_format and 04327_rewrite_aggregate_function_with_if_distributed. Neither test is added or modified by this PR; both fail the same way on every PR's arm_darwin run because they use remote('127.0.0.{1,2}', ...) and macOS binds only 127.0.0.1, so the connect to 127.0.0.2:9000 times out (Code 209, SOCKET_TIMEOUT). This is the known macOS-loopback infra flake; the fix (adding both tests to ci/defs/darwin.skip) is in #107376. Mergeable Check / PR are aggregators reflecting that one red.

This PR's own regression test 04337_read_smallest_column_by_disk_size is green on this commit (the earlier amd_msan flaky-check trip was resolved by the compact-part carrier guard and pinning query_plan_remove_unused_columns).

alexey-milovidov and others added 2 commits June 13, 2026 14:08
The carrier column for a no-columns read (e.g. SELECT count() or
SELECT isNullable(x) where x constant-folds away) was chosen over the
pre-pruned `parts`, before filterPartsByPartition,
filterPartsByPrimaryKeyAndSkipIndexes, the query-condition cache and
projection filtering populate result.parts_with_ranges.

Ranking over the pre-pruned set is both wasteful (an O(parts * columns)
size scan over parts that may be dropped) and fragile: parts pruned later
neither contribute to the cost of the read nor make a column "present in
every part", so a column that is cheap only in pruned parts could be
picked as the carrier for the surviving parts.

Move the non-streaming carrier choice to after result.parts_with_ranges
is final, so it ranks only over the parts that will actually be read.
The streaming early-return path runs before pruning, so it keeps choosing
over the pre-pruned parts as before. When no part survives, the read is a
NullSource that reads nothing, so no carrier is appended. The selection
logic is unchanged and is factored into a shared helper.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (bot finding #5: defer carrier choice past pruning)

# Question Answer
a Deterministic repro? Partial / N/A as a wrong-result. The bot's finding is a code-structure issue (carrier ranked over pre-pruned parts). I confirmed via EXPLAIN/trace that no user query reaches the no-columns carrier path AND prunes parts in a skewing way: every row-level filter (WHERE, partition key, PK range, _part, minmax) keeps its column in the read set so the empty-read-set trigger no longer fires; SAMPLE reaches the path but prunes granules uniformly, not whole parts. So the skew is structurally reachable but not via a deterministic query. The wasted-scan half (iterating pruned parts) is deterministic.
b Root cause explained? The carrier loop ran at the top of selectRangesToRead over the input parts, before filterPartsByPartition / filterPartsByPrimaryKeyAndSkipIndexes / the query-condition cache / projection filtering populate result.parts_with_ranges. Ranking over the pre-pruned set both does O(parts * columns) work over parts that may be dropped and lets a column cheap only in pruned parts win the carrier for the surviving parts.
c Fix matches root cause? Yes, exactly the bot's request: the non-streaming carrier choice is moved to after result.parts_with_ranges is final, ranking only over the parts that will actually be read. The streaming early-return (which runs before pruning) keeps choosing over the pre-pruned parts. When no part survives, no carrier is appended (the read is a NullSource). Not a band-aid.
d Test intent preserved / new tests added? All five existing 04337 scenarios kept and passing (no weakening). No new test added: I could not construct a user-reachable query that demonstrates the pruned-parts skew (see (a)), and per the no-speculative-test rule I declined to assert on an unreachable state. The selection logic is unchanged (extracted verbatim into a shared helper), so existing coverage still exercises it.
e Both directions demonstrated? The fix is behaviorally equivalent for all reachable cases (no pruning when read-set is empty), so a fails-without/passes-with pair is not applicable here. Instead verified: 04337 passes 50/50 with randomization on the rebased+rebuilt head (build id 2c3ba53594), and the behavior-changed early-return paths (alwaysFalse, all-granules-pruned, count() WHERE 0, normal carrier) all return correct results.
f Fix is general, not a narrow patch? Yes. The change covers every non-streaming pruning mechanism at once (partition, PK+skip-index, distributed index analysis, parallel-replicas-local-plan, QC cache, projection filtering) by deferring to the single point where result.parts_with_ranges is final, rather than patching one pruning site. The streaming path is handled symmetrically with the same helper. No defensive symptom-guard.

Session id: cron:clickhouse-worker-slot-2:20260613-131500

The carrier column for a no-columns read (e.g. SELECT count()) was ranked
during selectRangesToRead, after partition/PK/skip-index/query-condition-cache
pruning. But optimizeUseNormalProjection and optimizeUseAggregateProjection run
later and call filterPartsByProjection, removing parent parts from
parts_with_ranges without recomputing the carrier. A column cheap only in a
projection-covered (now pruned) part could win and the surviving parent part
would then be read through an expensive column.

Defer the carrier choice to initializePipeline, the last point before the read,
once all plan optimizations (including projection filtering) have finalised
parts_with_ranges. The streaming path keeps choosing over the pre-pruned parts
as before. When no part survives the read is a NullSource, so no carrier is
needed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The no-columns carrier (the cheap column a SELECT count() reads just to learn
the row count) was chosen in initializePipeline before the
distributed_read_bucket_count block. In a bucketed make_distributed_plan read,
filterMarkRangesForBucket trims ranges and can drop whole parts per worker, so
the carrier was ranked over the pre-bucket part set. A worker reading only the
part where the globally-cheapest column is expensive then reads that expensive
column, reintroducing the stale-carrier problem for distributed reads.

Move the carrier choice past the bucket block so it ranks over the parts this
pipeline actually reads, keeping the !parts_with_ranges.empty() guard (zero
surviving parts become a NullSource). This mirrors the earlier move past the
projection-filtering optimizations. Non-distributed reads are unaffected: the
bucket block is skipped, so the carrier site is functionally identical.

Local A/B over a two-part table where the globally-cheapest column is the
expensive one in one part (make_distributed_plan, 3 buckets): the distributed
read went from 2,008,345 to 502 ReadCompressedBytes. The committed scenario
asserts the bucketed no-columns read stays correct (the distributed worker
pipeline does not surface ReadCompressedBytes, so the byte win cannot be
asserted in a parallel-safe stateless test).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Two-part t_iso table where the globally cheapest column is the expensive one in one part; make_distributed_plan=1, distributed_plan_execute_locally=1, distributed_plan_default_reader_bucket_count={2,3,4}. Global ReadCompressedBytes delta is deterministic (5/5 identical per bucket count).
b Root cause explained? The carrier was chosen in initializePipeline before the distributed_read_bucket_count block. That block calls filterMarkRangesForBucket per worker, which trims ranges and can drop whole parts, after the carrier was already ranked over the pre-bucket set. chooseColumnToReadForNoColumnsQuery ranks by whole-part getColumnSize().data_compressed, so a worker bucketed onto a single part picks the column cheap globally even when it is the expensive one in that part.
c Fix matches root cause? Yes. The carrier insertion is moved to after the bucket block, so it ranks over the final parts_with_ranges the worker reads. Same mechanism as the earlier move past projection filtering.
d Test intent preserved / new tests added? Preserved. The 5 existing byte-count scenarios are unchanged and still produce 1 1 1 1 1 3. Added a 6th scenario (t_smallest_column_bucket) exercising the bucketed carrier path end to end.
e Both directions demonstrated? Yes. Carrier pre-bucket (HEAD f0fb0c8e binary): 2,008,345 ReadCompressedBytes; carrier post-bucket (fix, 65239bf1): 502. A/B table in the in-thread reply.
f Fix is general across code paths? Yes. The non-streaming carrier choice has a single site (initializePipeline); the streaming path (selectRangesToReadImpl early-return, pre-pruning by design) is unchanged. No sibling site reads the carrier.
g Fix generalizes across inputs? Yes. The carrier ranking is over the post-bucket parts regardless of column type/wrapper; the change is a code-position move, not type-specific logic. Verified for count() and isNullable(col) no-columns reads.
h Backward compatible? N/A. Behavior-internal carrier-column choice; no setting default, on-disk/wire format, or new validation changed. Results are unchanged (it was a performance regression for distributed reads).
i Invariants and contracts preserved? Yes. The carrier is still ranked over result.parts_with_ranges after all mutations, the !parts_with_ranges.empty() guard is kept (zero parts become a NullSource), and chooseColumnToReadForNoColumnsQuery's present-in-all-parts contract holds for the post-bucket subset.

Session id: cron:clickhouse-worker-slot-0:20260624-081000

The no-columns carrier (SELECT count() etc.) ranks candidate columns by
getColumnSize().data_compressed, a whole-part figure. A distributed bucket
read (filterMarkRangesForBucket) can leave a worker only a subset of a part's
mark ranges, so a column cheap over the whole part may be the expensive one in
the marks that worker actually reads. Scale each column's per-part compressed
size by selected/total marks so the ranking reflects the ranges this pipeline
reads. The factor is 1 for a full read, so non-distributed plans are unchanged;
it tracks cross-part trimming exactly and intra-part trimming under a
uniform-compression assumption (per-range compressed sizes are not tracked in
part metadata). Follow-up to the carrier-after-bucket-filter move.

Added a single-many-mark-part bucketed scenario to 04337.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (bot finding #8 — per-range carrier cost, commit 1ec1066b467)

# Question Answer
a Deterministic repro? Yes. Two-part table (part1 a 251 B/b 2 MB, part2 a 10 MB/b 251 B, global a>b); a bucketed count() (make_distributed_plan=1, distributed_plan_execute_locally=1, reader_bucket_count=2/3) ranks the carrier over the pre-bucket set and reads ~2 MB off the part where the global carrier is the expensive column. Measured via system.events['ReadCompressedBytes'] deltas on a debug build.
b Root cause explained? chooseColumnToReadForNoColumnsQuery ranked candidates by getColumnSize().data_compressed, a whole-part figure, ignoring part.ranges. filterMarkRangesForBucket can trim a part to a mark subset per worker, so a column cheap over the whole part can be the expensive one in the marks that worker reads. Finding #7 moved the choice after the bucket block (fixing whole-part DROP); this fixes intra-part range TRIM.
c Fix matches root cause? Yes. The per-part cost is now scaled by selected_marks / total_marks (getMarksCountWithoutFinal), so the ranking reflects the marks this pipeline reads — directly the quantity that was wrong.
d Test intent preserved / new tests added? Yes. Added t_smallest_column_bucket_ranges (single many-mark part under a bucket plan, exercising the mark-fraction path). All 6 existing scenarios unchanged; no assertion weakened; SET enable_analyzer=1 / query_plan_remove_unused_columns=1 / optimize_trivial_count_query pins intact.
e Both directions demonstrated? Yes. Without scaling (pre-fix) the bucketed count() reads ~2 MB; with scaling it reads 602 / 502 bytes (each worker picks the column cheap in its own part). 04337 passes 20/20 with randomization.
f Fix is general across code paths? Yes. Both carrier call sites (streaming selectRangesToRead and initializePipeline) go through the same function; the scaling applies uniformly. No symptom-guard — the cost computation itself is corrected.
g Fix generalizes across inputs? Yes. Independent of column type/wrapper (cost is bytes-on-disk); handles 1..N parts, full and trimmed ranges, and any reader_bucket_count. The zero-size-part fallback (compact parts) is unchanged. The factor-1 full-read path keeps LowCardinality/Nullable ranking identical to before.
h Backward compatible? Yes. Internal planner heuristic for which physical column a no-columns read materializes; no setting, on-disk/wire format, or result change. Only the bytes read off disk for count()-like queries change.
i Invariants and contracts preserved? Yes. The carrier stays a current-metadata physical column present in every selected part (resolves against the StorageSnapshot); the carrier.empty() in-memory fallback is preserved for compact/schema-evolved parts. part.ranges is already final at both call sites (after pruning, projection filtering, and the bucket filter).

Session id: cron:clickhouse-worker-slot-0:20260624-105400

The no-columns carrier ranked candidate columns by whole-part compressed
size scaled by the read mark fraction. Within one part that fraction is the
same constant for every candidate, so it cannot reorder columns: a worker
that keeps only a subset of a part's marks still picked the column cheapest
over the whole part, even when it is the expensive one in the marks read.

Part metadata holds no per-mark-range compressed sizes, so a range-local
cost cannot be computed at plan time. When any selected part is read with
trimmed ranges (a distributed bucket / parallel-replicas read), distrust the
whole-part on-disk sizes and fall back to the in-memory heuristic, which does
not depend on how many marks are read. A true no-columns query has no
predicate, so a non-distributed read is never range-trimmed and keeps the
on-disk ranking, leaving all existing byte-count behaviour unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Head 7addc3a9b54 (bot finding on 1ec1066b467, comment 3466985971).

# Question Answer
a Deterministic repro? Yes. (lc LowCardinality(Nullable(String)), x UInt64) table, lc cheap on disk (979 B) but x cheaper in memory (UInt64 8 vs LC 100). On the prior binary a bucketed count() (make_distributed_plan=1, distributed_plan_default_reader_bucket_count=4) ranked over the whole-part size and the per-part mark-fraction multiplier could not reorder columns within a part; measured via system.events.ReadCompressedBytes delta.
b Root cause explained? The carrier scaled each candidate's whole-part data_compressed by selected_marks / total_marks. Within one part that fraction is the same scalar for every candidate, so argmin_c(size_c·f) == argmin_c(size_c): it never reorders columns inside a part, so intra-part range trimming (a worker keeping a mark subset where the globally-cheap column is locally expensive) still picked the wrong carrier. Part metadata has no per-mark-range compressed sizes, so a true range-local cost is not computable at plan time.
c Fix matches root cause? Yes (bot's Option B). Detect when any selected part is range-trimmed (part.ranges.getNumberOfMarks() < part.data_part->index_granularity->getMarksCountWithoutFinal()); when so, distrust the whole-part on-disk sizes and fall back to getSmallestColumn (in-memory, independent of marks read). On-disk ranking is kept only when every selected part is read in full.
d Test intent preserved / new tests added? All 5 byte-count scenarios + schema-evolved + whole-part-drop bucket scenario unchanged. t_smallest_column_bucket_ranges rebuilt to the non-uniform intra-part case the previous version missed (one many-mark part, a heavy in early marks, b heavy in late marks). No assertion weakened, no scenario removed, no no-parallel/no-random-* tag added, pins (enable_analyzer=1, query_plan_remove_unused_columns=1, optimize_trivial_count_query) intact.
e Both directions demonstrated? Single-binary flip on the disagreeing-ranking table: non-bucketed count() reads 1305 B (carrier lc, on-disk ranking retained); bucketed count() (bucket_count=4) reads 499144 B (carrier x, in-memory fallback). The fallback fires only under trimming. 04337: 1/1 (--no-random-settings), 20/20 (randomization on).
f Fix is general across code paths? Single carrier site (chooseColumnToReadForNoColumnsQuery), called from both the streaming early-return and the post-bucket initializePipeline insertion; both go through the same range-trim guard. Not a symptom guard: it corrects the cost model where the whole-part number is provably misleading, and the trim detector covers whole-part-drop (finding #7, survivors read full → on-disk ranking) and intra-part-trim (this finding → fallback) uniformly.
g Fix generalizes across inputs (params/datatypes/wrappers)? The guard is type-agnostic: it keys on mark counts, not column type, so it holds for plain / Nullable / LowCardinality / LC(Nullable) / Array / Map columns and for compact and wide parts (compact parts already route to the in-memory fallback via the zero-size check). Bucket counts 2/3/4 verified; non-uniform single-part bucketed count() returns correct 102400.
h Backward compatible? Yes. No setting, on-disk, wire, or metadata format change. Read-path-only optimization choosing which existing column to read; query results identical. N/A to SettingsChangesHistory.cpp.
i Invariants and contracts preserved? Carrier stays a current-metadata physical column present in every selected part, so it resolves against the StorageSnapshot; per-part read setup substitutes missing columns as before. !parts_with_ranges.empty() guard kept (zero parts → NullSource). No block-structure, ordering, or concurrency contract touched.

Session id: cron:clickhouse-worker-slot-0:20260624-125300

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7addc3a

Every failure below has an owner. This PR is a ReadFromMergeTree no-columns carrier-selection perf fix plus one stateless test; it does not touch the stress runner, the distributed-plan optimizer, RefreshTask, or any server-start path, so none of the failures are PR-caused.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error 'Different list of shards in child plans' (STID 4661-4940) crash #108256 (ours, open) — projection-union shard-mismatch in make_distributed_plan, exact same LEFT JOIN ... t2 PREWHERE shape at makeDistributed.cpp:900
Stress test (arm_asan_ubsan) / Logical error 'Unexpected exception in refresh scheduling' (STID 2508-34af) crash fix task (RefreshTask doScheduling, Issue #106737) — investigating at full effort, fix PR link to follow here
Stress test (arm_msan) / Logical error 'Unexpected exception in refresh scheduling' (STID 2508-3e7b) crash same owner (RefreshTask doScheduling, Issue #106737)
Stress test (arm_msan) / Cannot start clickhouse-server crash downstream of the refresh-scheduling crash above — same owner
Stress test (arm_msan) / Check failed crash downstream stress aggregate verdict for the same aborted run — same owner
Stress test (arm_tsan) / Hung check failed, possible deadlock found deadlock chronic trunk hung-check family (315 master hits / 30d) — tracked umbrella, fix PR link to follow here

STID 2508-34af/3e7b is a chronic trunk RefreshTask scheduling crash (24 master hits / dozens of unrelated PRs / 30d, Issue #106737). The hung-check deadlock is a separate chronic trunk family. Neither is reachable from this PR's diff.

Session id: cron:our-pr-ci-monitor:20260624-173000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d45eeb1

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Style check / various PR-caused: a comment line this PR adds to tests/queries/0_stateless/04337_read_smallest_column_by_disk_size.sql writes "new analyzer", which a style rule added to master on 2026-07-27 now rejects fixed in this PR

Session id: cron:our-pr-ci-monitor:20260729-043000

groeneai added 4 commits July 29, 2026 05:36
Master gained a check-style rule on 2026-07-27 (PR ClickHouse#110471,
ci/jobs/scripts/check_style/various_checks.sh) that rejects the phrases
"new analyzer" and "new query analyzer": the analyzer has been enabled by
default since 24.3 and is no longer new. Two comment lines in this test
used that wording. They were style-clean when written; the rule arrived on
this branch with a master merge, which is why Style check turned red
without a change of ours.

Comment text only: no assertion, setting or query is touched, so the
byte-count assertions the test makes are unaffected. The "old analyzer"
wording in the same paragraph is not covered by the rule (its pattern
requires a leading "new") and remains the accepted term on master.

Reverting either changed word alone reproduces one of the two reported
lines, and reverting both reproduces the CI output verbatim; driving
check_style.py's check_other over the tree reports OK after the change.
The streaming early-return in selectRangesToRead stored the ranked carrier in
result.column_names_to_read, but a streaming read never looks at that list:
groupPartitionsByStreams builds MergeTreeCommitOrderSequentialSource from the
all_column_names member, and the source derives its own read list from that
(extendWithAuxiliaryColumns(user_requested_columns)) against a snapshot it
builds itself. The only consumers of column_names_to_read - the
spreadMarkRanges family and the deferred-filter block - are on the
non-streaming path. So the per-part ranking scan behind that push was dead
work, and the comment claiming a carrier was chosen there was wrong.

Restore the cheap in-memory choice on that path, which is what the code did
before this PR, so streaming behaviour is unchanged and no part metadata is
scanned for a value nobody reads. The read-time site in initializePipeline is
now the helper's only caller.

Also say "throwing a LOGICAL_ERROR exception" instead of "crashing the server"
in the schema-evolved scenario comment: that failure is a caught exception in
release builds and only aborts under debug and sanitizer builds.

Verified on a debug build (Build ID a79bf5c7990c8118779c5ebbb7ccac3a367fbb82):
the regression test's output matches its reference exactly, and the annotated
statement still throws NO_SUCH_COLUMN_IN_TABLE. Forcing the on-disk ranking to
fall back to the in-memory heuristic turns three of the five byte assertions
from 1 to 0, so the ranking this PR adds is still the thing under test.
The comment claimed that parallel-replica reads fall back to the in-memory
heuristic, which they do not: the range-trimming check runs in
initializePipeline, while the coordinator assigns and cuts mark ranges later,
in MergeTreeReadPoolParallelReplicas::getTask. At selection time the parts
still carry the full announced ranges, so the check cannot see that trimming
and such a read keeps the whole-part ranking.

That is the intended behaviour, not a defect to guard: the whole-part size is
the best estimate available at plan time, and the carrier only supplies the row
count, so every candidate is equally correct and a per-replica mis-rank costs
bytes rather than correctness. Disabling the ranking whenever parallel replicas
are active would give up the improvement this PR exists for on those reads.
Say what actually happens instead, and name the boundary that would have to
move to make the estimate per-assignment.

Comment text only: with comments stripped and whitespace collapsed the
translation unit hashes identically to the previous commit (5d120c2a…), while
the pre-PR master version of the same file differs (dc31fa1e…).
The comments around the no-columns carrier had grown to 58 added lines in this
file and restated the reasoning that belongs in the commit message and the PR
description. Cut them to 37 and keep only what is not evident from the code at
each site: why candidates must be present in every part, why a whole-part size
cannot describe a range-trimmed read, why parallel replicas keep the whole-part
ranking, why a zero size is not "free", and why this has to run last.

Comment text only: with comments stripped and whitespace collapsed the
translation unit hashes identically to the previous commit (5d120c2a…), while
the pre-PR master version of the same file differs (dc31fa1e…).
/// both shrink parts_with_ranges, so a carrier chosen earlier could be ranked over parts this
/// pipeline never reads. An empty parts_with_ranges needs no carrier (the read becomes a
/// NullSource below).
if (result.needs_no_columns_carrier && result.column_names_to_read.empty() && !result.parts_with_ranges.empty())

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.

result.column_names_to_read still is not final here. A no-output SAMPLE query reaches this branch with the list empty, but spreadMarkRanges appends the sample_by_ast inputs later at ReadFromMergeTree.cpp:3591-3600, and the deferred-filter block below can append row-policy / PREWHERE columns at ReadFromMergeTree.cpp:4185-4192. So SELECT count() FROM t SAMPLE ... still pays chooseColumnToReadForNoColumnsQuery's O(parts * columns) size scan and can drag along an extra carrier column even though sampling already gives the read a real physical column.

Before this PR the dead work here was only the cheap ExpressionActions::getSmallestColumn heuristic; with the new helper it becomes a per-part walk over every candidate column on a path the new test file does not cover. Please delay carrier insertion until after all mandatory read columns are known, or skip it when sampling / deferred filters already guarantee that some physical column will be read.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Half of this reproduces and half does not. Measurements below are on a debug build of this head
(server buildId() matched the binary's ELF note), with a master control built from the same
snapshot so "new cost" claims are attributable.

The SAMPLE half does not reproduce, for two independent reasons.

spreadMarkRanges does not append to result.column_names_to_read. It copies into a local first
(Names column_names_to_read = result.column_names_to_read;) and the sample_by_ast loop pushes
into that local, which is then passed by value to spreadMarkRangesAmongStreams. Grepping the whole
function body for result.column_names_to_read returns exactly one hit, the copy. So the guard at
:4149 cannot be invalidated by sampling. Call order also runs the other way: :4149 executes before
the single spreadMarkRanges call site at :4540.

The O(parts * columns) size scan does not run on this path either. chooseColumnToReadForNoColumnsQuery
already declines the on-disk ranking when any part is range-trimmed, and SAMPLE trims ranges, so the
getColumnSize loop is skipped and the in-memory fallback is used. What remains is hasColumnFiles
per candidate, which is a checksums-map lookup in both the Wide and Compact implementations and does
not force the lazy size calculation.

That is visible in the bytes. With big 141,664, mid 1,606,925, k 3,213,823 and 25 sampled marks,
SELECT count() FROM t SAMPLE 0.5 reads 2,501,601, matching mid alone (2,501,122) rather than the
on-disk smallest big (1,653,096) - i.e. the in-memory pick, so the ranking really was skipped. On the
untrimmed path the same table reads 141,887, matching big.

The extra carrier under SAMPLE is also not new. On the master control, same fixture and queries, the
sampled count() reads 2,501,601 - byte-identical to this head, same carrier. Master inserts its carrier
unconditionally when the read set is empty, earlier and with the same heuristic. The two builds differ
only on the untrimmed path, where master reads 1,606,925 against this head's 141,887.

The deferred-filter half does reproduce, and it is the part worth fixing. That block does append to
result.column_names_to_read, and it runs after :4149. With a ReplacingMergeTree and a row policy on a
column other than the carrier, SELECT count() FROM t FINAL goes from 1,964 bytes to 157,831 once the
policy is added, and the policy column alone accounts for 157,386 - so the read gets a real physical
column anyway and the carrier is dead weight.

I have not taken the suggested "skip it when sampling guarantees a physical column" here. Because the
sampling columns land in that local copy, skipping the carrier would leave result.column_names_to_read
empty for the consumers that do read it, including the deferred-filter name set immediately below, so it
is not a drop-in. SAMPLE BY also takes an expression, so at :4149 only use_sampling is known, not
which columns sampling will end up needing.

So I am folding the ordering point into the redesign already open on this PR rather than special-casing
it: two earlier findings ask the same question, whether the cached getColumnSize figure is the right
cost oracle for this ranking and where the carrier decision belongs once the read set is final. A local
guard here would be rewritten by that work. The coverage gap is fair and I will add SAMPLE and
deferred-filter cases to the test as part of it.

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 64/66 (96.97%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 21f2528

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit the per-table concurrency throttle the test asserts is keyed on query id, and secondary parallel-replicas reads are sent without one, so the holder query competes against itself (3/3 reruns, deterministic) #112385 (ours, open)
AST fuzzer (amd_msan) / Column __text_index_idx_like_... already added for reading (STID 4792-5e4c) text-index direct-read optimizer removes a filter input from the read set with an unguarded erase, so a name that was never in the set is erased past the end #111844 (ours, open)
Stress test (amd_msan) / assertTypeEquality in HashJoin::buildAdditionalFilter (STID 2508-30f6) the key-value right side is stored with toNullable-wrapped columns while the residual-filter required columns stay non-nullable, so insertFrom asserts #107957 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-120000

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Before this merges: I found a shape where this change reads more bytes than master, and I had not disclosed it here yet. I would rather say so than let it merge on my silence.

chooseColumnToReadForNoColumnsQuery ranks candidates by part.data_part->getColumnSize(name).data_compressed. That cached number is not a per-column read cost when two columns share a substream: MergeTreeDataPartWide::calculateEachColumnSizes walks the columns with a single processed_substreams set (MergeTreeDataPartWide.cpp:641,644) and getColumnSizeImpl skips a stream already in it (:225). That is correct for the table total, which must not double count, but it means the column visited later has the shared stream charged to its sibling, so its cached size understates what reading it actually costs.

For Nested(a UInt64, b String) the shared n.size0 is charged entirely to n.a:

CREATE TABLE t_share3 (n Nested(a UInt64, b String))
ENGINE = MergeTree ORDER BY tuple()
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO t_share3
SELECT arrayResize(emptyArrayUInt64(), 1 + rand() % 200, 7::UInt64),
       arrayResize(emptyArrayString(), 1 + rand() % 200, 'q')
FROM numbers(300000);
OPTIMIZE TABLE t_share3 FINAL;

One Wide part, 50 marks. Stream sizes on disk: n.size0 906,768, n%2Ea 954,076, n%2Eb.size 954,076, n%2Eb 119,804. So the deduped figure the ranking reads is n.a 1,860,844 vs n.b 1,073,880 and it picks n.b, while the real cost of reading n.b alone is 906,768 + 954,076 + 119,804 = 1,980,648, against 1,860,844 for n.a. It ranks the more expensive column first.

Measured ReadCompressedBytes, this branch versus a pre-change master build, same DDL and same insert:

query this branch master
SELECT sum(arraySum(n.a)) 1,861,370 1,862,767
SELECT sum(length(arrayStringConcat(n.b))) 1,981,162 1,982,712
SELECT isNullable(n.a) (carrier path) 1,980,648 1,862,300
count(), trivial count and implicit projections off 1,980,648 1,862,300

The carrier figure equals the predicted n.b-alone cost exactly, and master's equals its n.a arm: master's in-memory heuristic compares UInt64 8 against the String estimate and happens to pick the cheaper column here. So on this shape the change is a 6.4% regression rather than a missed optimization, which is why I am flagging it rather than filing it as a follow-up. Both servers reported a buildId() matching their binary's ELF note.

To be clear about the size of the claim: it needs two columns sharing a substream with own(a) < own(b) < own(a) + shared, so Nested and multi-stream types, and it costs bytes and not correctness, since the carrier only supplies the row count. The untrimmed LowCardinality case this PR exists to fix is unaffected and still shows the large improvement.

I have not sent a fix, because I do not think the right one is a patch on top of this ranking loop. getColumnSizeImpl(column, nullptr) returns the un-deduped true per-column cost but is private on MergeTreeDataPartWide, so the options are to expose a "cost to read this column alone" accessor or to decline the on-disk ranking when a candidate shares a stream. A naive "only rank single-stream candidates" rule would be wrong: it would exclude LowCardinality(String), whose dictionary and index streams are its own. That same question ("is cached getColumnSize the right cost oracle here?") also covers the other thing I owe you: this ranking calls getColumnSize, which forces the lazy column-size calculation that columns_and_secondary_indices_sizes_lazy_calculation defaults to deferring, and that calculation probes secondary-index files through the storage overlay, reaching Keeper in the metadata-in-Keeper setup. One redesign answers both, with one performance story.

Happy to do that work. Given you have just merged master in, tell me whether you would rather hold this for the redesign, or merge the LowCardinality win now and take the shared-substream ranking as a follow-up, in which case I will open it against the Nested shape above.

@groeneai groeneai added the groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR label Aug 19, 2026
@abashkeev abashkeev added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
Resolves one conflict in ReadFromMergeTree.cpp. Master's 6b27f2d
deprecated merge_tree_enable_remove_parts_from_snapshot_optimization and made
the snapshot stripping in initializePipeline unconditional, dropping the
enable_remove_parts_from_snapshot_optimization || query_info.isStream() guard
that this branch had adapted. I kept master's unconditional block and its
comment, and kept the deferred no-columns carrier injection immediately above
it, which is where this branch needs it: filterPartsByProjection and the
distributed bucket filter both shrink parts_with_ranges, so the carrier has to
be ranked after them.

Checked after the merge: selectRangesToRead still computes
needs_no_columns_carrier before the streaming early return, which keeps the
cheap in-memory choice there; initializePipeline still reaches the deferred
injection with no intervening return; and master's own use of
getColumnNameWithMinimumCompressedSize is confined to the estimateReadBytes
cost estimator, so it does not overlap the read path this branch changes.
bool measurable_in_all_parts = true;
for (const auto & part : parts)
{
size_t part_size = part.data_part->getColumnSize(column.name).data_compressed;

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.

getColumnSize is not the cost of reading this candidate in isolation on Wide parts. MergeTreeDataPartWide::calculateEachColumnSizes caches per-column sizes with one processed_substreams set shared across the whole part, so a shared stream is charged only to the first column that visits it. With share_nested_offsets = 1, a Nested(a, b) layout puts n.size0 entirely on n.a; n.b then looks smaller here even though reading n.b alone still has to pull n.size0.

That means a no-columns read can now pick the more expensive carrier and regress against master on shared-substream tables. I think this needs either an accessor that prices a candidate column independently, or a fallback that refuses the on-disk ranking when a candidate shares streams with a sibling.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and it is the same mechanism I disclosed in #107368 (comment) rather than a new one: one processed_substreams set per part (MergeTreeDataPartWide.cpp:641, :644) and getColumnSizeImpl returns early for a stream already in it (:226 at this head, :225 when I wrote that comment). So the column visited later has the shared stream charged to its sibling.

That comment carries the Nested(a UInt64, b String) reproducer and the ReadCompressedBytes numbers: on that shape the carrier path reads 1,980,648 against master's 1,862,300, so it is a 6.4% regression there rather than a missed optimization.

Your two remedies are the two I listed there. One caveat on the second: "refuse the on-disk ranking when a candidate shares streams with a sibling" must not be implemented as "only rank single-stream candidates", because that would exclude LowCardinality(String), whose dictionary and index streams are its own, and that is the case this PR exists to fix.

Choosing between the two is the open question in that comment and it is still unanswered, so I do not think this should merge as it stands.

bool measurable_in_all_parts = true;
for (const auto & part : parts)
{
size_t part_size = part.data_part->getColumnSize(column.name).data_compressed;

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.

This getColumnSize call also makes the first virtual-only read on a cold part bootstrap calculateColumnsAndSecondaryIndicesSizesOnDiskUnlocked() when columns_and_secondary_indices_sizes_lazy_calculation = 1 (the default). That computes all column sizes and all secondary-index sizes before returning this one number, and the secondary-index side goes through the storage overlay / Keeper path for packed substreams.

So a SELECT count() / SELECT 1 FORMAT Null that used to stay in a pure in-memory heuristic can now pay a full size-cache build just to choose the carrier. We should avoid triggering the lazy size calculation from this path unless the sizes are already cached, or precompute/store a cheaper carrier metric elsewhere.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and also on the record in the last paragraph of that same comment: #107368 (comment)

Re-verified at this head: getColumnSize computes under the lock when the sizes are absent and checksums are loaded (IMergeTreeDataPart.cpp:3169-3173), which runs both calculateColumnsSizesOnDisk() and calculateSecondaryIndicesSizesOnDisk() (:3068-3069); the setting defaults to true (MergeTreeSettings.cpp:2413); and the secondary-index half's packed-substream fallback goes through the storage overlay, "which reaches Keeper in the metadata-in-Keeper configuration" (:3100-3103).

Two refinements, in opposite directions. The memory is not charged to the query (MemoryTrackerBlockerInThread, :3062), so what a virtual-only read on a cold part pays here is latency and IO rather than query memory. Against that, your "unless the sizes are already cached" remedy is cheaper than I assumed when I wrote that comment: IMergeTreeDataPart::areColumnAndSecondaryIndexSizesCalculated() is already public on master and documented as never triggering the lazy computation, so gating this path on it needs no new accessor.

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ae9d4629f with master b13e8f865 (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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #131371 (merged), which fixes #106597 using the table's column sizes, so my question above is moot. This PR can be closed.

@rschu1ze

Copy link
Copy Markdown
Member

Superseded by #131371

@rschu1ze rschu1ze closed this Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ARM performance regression: low_cardinality_argument query 0 is slower

5 participants