Skip to content

Read the column that is smallest on disk when a MergeTree read needs no column - #131371

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/read-cheapest-on-disk-column-when-no-column-is-needed
Nov 14, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/read-cheapest-on-disk-column-when-no-column-is-needed

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131235
Closes: #106597
Related: #107368

Changelog category (leave one):

  • Performance Improvement

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

A MergeTree query that needs no column of the table, such as SELECT count() over a table with lightweight-deleted rows, count() over a subquery or SELECT isNullable(c) FROM t, again reads the column that is smallest on disk, as it does with query_plan_remove_unused_columns = 0. Since 25.12 it read the column with the smallest data type, which could be more than 1000 times larger. Closes #131235. Closes #106597.

Description

With query_plan_remove_unused_columns = 1 (the default since 25.12), a MergeTree read that needs no column of the table read the column with the smallest data type instead of the one smallest on disk. On the table from #131235 (100M rows, one lightweight DELETE), SELECT count() read 124.8 MB of c4 Nullable(UInt8) instead of 84 KB of c3 Int32.

The planner picks the column to count rows by its size on disk (chooseSmallestColumnToReadFromStorage), but the plan-level column pruning then removes it from ReadFromMergeTree as unused, and ReadFromMergeTree::selectRangesToRead adds a column back with ExpressionActions::getSmallestColumn, which only compares the in-memory size of the types.

The <compressed size, type size, uncompressed size> ranking that the planner and TreeRewriter each implemented is now one function, ExpressionActions::getCheapestColumnToRead. The planner and TreeRewriter call it unchanged, and selectRangesToRead uses it on the table's column sizes once the parts to read are known. Reads of projection parts keep the type ranking, since the table's column sizes do not describe them.

This supersedes my #107368, which targets the same fallback with a separate per-part ranking.

Validation: the new test fails on master in every randomized run (150 of 150) and passes with the fix (150 of 150, 100 of them in a flaky-check style run). ReadCompressedBytes on 10M rows, master vs this PR: count() after a lightweight delete 18.0 MB vs 79 KB, sum(1) 18.1 MB vs 77 KB, count() over a subquery 18.1 MB vs 65 KB, count() ... FINAL 15.7 MB vs 94 KB, and isNullable(lc) from perf test low_cardinality_argument (#106597) 40.05 MB vs 1.76 MB.


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

Version info

  • Merged into: 26.11.1.2271-master (included in 26.11 and later)
  • Backported to: 26.10.7.3

groeneai and others added 2 commits November 13, 2026 16:08
…no column

With `query_plan_remove_unused_columns = 1` (the default since 25.12), a
`MergeTree` read that needs no column of the table (`SELECT count()` that has
to scan, e.g. after a lightweight `DELETE`; `sum(1)`; `count()` over a
subquery; `count() ... FINAL`; a constant-folded `isNullable(c)`) read the
column with the smallest data type instead of the one smallest on disk.

The planner chooses the row-count column by its size on disk
(`chooseSmallestColumnToReadFromStorage`), but the plan-level column pruning
removes it from `ReadFromMergeTree` because nothing above uses it, and the
static `ReadFromMergeTree::selectRangesToRead` then re-adds a column with
`ExpressionActions::getSmallestColumn`, which ranks by
`getMaximumSizeOfValueInMemory` only: a `Nullable(UInt8)` of 118 MB beat a
sparse `Int32` of 1.5 KB on the table from ClickHouse#131235 (126 MB read instead of
91 KB). The same fallback causes ClickHouse#106597 (`isNullable(lc)` in the perf test
`low_cardinality_argument` reads `x`, 40 MB, instead of `lc`, 1.8 MB).

The <compressed size, type size, uncompressed size> ranking, written twice
(planner `ColumnWithSize`, `TreeRewriter` `ColumnSizeTuple`), becomes one
function, `ExpressionActions::getCheapestColumnToRead`, used by both of them
unchanged (same candidates, order, ties and fallback) and by
`selectRangesToRead` right before its normal return, from the table's cached
column sizes, when no column is needed and at least one non-projection part
is read. The early returns keep the type-ranked carrier and make no size
lookup (none of them reads a part through it), and projection parts keep it
too, because the table's column sizes do not describe them.

Closes ClickHouse#131235
Closes ClickHouse#106597

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the getCheapestColumnToRead header comment from three lines to two.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings), plus my own cold review of the same head.

# Sev Finding Verdict Evidence / action
1 💡 selectRangesToRead keeps the type-ranked column for its early returns and re-ranks by on-disk size before the normal return (ReadFromMergeTree.cpp) AGREE, noted, not blocking The early returns read nothing (or stream from all_column_names), so they skip the size lookup; the normal return gets the planner's ranking.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261113-161100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 10M-row table from #131235 with one lightweight DELETE: SELECT count() ... SETTINGS query_plan_remove_unused_columns = 1 reads 18.0 MB (c4 Nullable(UInt8)) on master and 79 KB (c3 Int32) with the fix, every run.
b Root cause explained? The planner picks the row-count column by size on disk, plan-level column pruning removes it as unused, and ReadFromMergeTree::selectRangesToRead adds a column back by the in-memory size of its type.
c Fix matches root cause? Yes. The re-added column is ranked like the planner ranks it, from the table's column sizes; the pruning itself is unchanged.
d Test intent preserved / new tests added? New SQL test asserting ReadCompressedBytes of count() and isNullable(c) reads; no existing test or reference changed.
e Both directions demonstrated? Test: master 150/150 FAIL, fix 150/150 OK under randomized settings (100 of each in a flaky-check style run).
f Fix is general across code paths? The only no-column carrier that ignored sizes is fixed; the planner and TreeRewriter copies of the ranking now share the new function; projection parts keep the type ranking because the table's sizes do not describe them.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked with UInt8, UInt64, Nullable(UInt8), LowCardinality(Nullable(String)) and the shapes count() after a delete, sum(1), count() over a subquery, FINAL, isNullable. Compact parts report no sizes and fall back to the type ranking, as in the planner.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; the read matches query_plan_remove_unused_columns = 0.
i Invariants and contracts preserved? The step still reads at least one column on every path, its header is unchanged, early returns are untouched, and getColumnSizes is called with no parts or sizes lock held.

Session id: cron:clickhouse-impl-slot-7:20261113-145200

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [524e0ac]

Summary: ✅


AI Review

Summary

Reviewed PR #131371 at 524e0ac51fbb07fced95ba3a18c31efa6c56a009. The change restores column selection by compressed size for MergeTree reads that need no table columns and shares the existing ranking between the planners and reader. No actionable findings. The new regression test passes in Fast test, and the PR provides before/after read-volume measurements supporting the improvement.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 524e0ac51 with master 048029bd8 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.58, programs/clickhouse-keeper ×0.62 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.3 s 12.2 s +8.6 s (+235%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.1 s +5.1 s (+255%)
Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It still uses ExpressionActions, that we want to remove. Too bad, @KochetovNicolai

@alexey-milovidov alexey-milovidov self-assigned this Nov 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 82d74f6 Nov 14, 2026
408 of 409 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 14, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 14, 2026
alexey-milovidov pushed a commit that referenced this pull request Nov 18, 2026
Resolve the conflict in src/Planner/PlannerJoinTree.cpp: keep the 26.10 side and take only the lines of #131371. The `skip_subcolumns` argument of the master call refers to `filtered_by_allowed_columns`, which comes from #103402 (not in 26.10), so the call uses the default, as the replaced `getSmallestColumn` call on 26.10 did.
robot-ch-test-poll added a commit that referenced this pull request Nov 18, 2026
Cherry pick #131371 to 26.10: Read the column that is smallest on disk when a MergeTree read needs no column
robot-clickhouse added a commit that referenced this pull request Nov 18, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 18, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 18, 2026
Backport #131371 to 26.10: Read the column that is smallest on disk when a MergeTree read needs no column
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

6 participants