Skip to content

Do not compute a default from other columns when a MergeTree read needs no column - #131671

Open
groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:no-column-read-column-stored-in-all-parts
Open

groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:no-column-read-column-stored-in-all-parts

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131530
Related: #131371

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed SELECT count() and other reads of a MergeTree table that need no column failing, or reading much more data than needed, after ALTER TABLE ... ADD COLUMN with a default expression: for the parts written before the ALTER, the read computed that default, reading its source columns and throwing when it could not be computed for an old row. Closes #131530.

Description

On 26.3, 26.8 and 26.10, SELECT count() after a lightweight DELETE over a table with a column added by ADD COLUMN n UInt8 DEFAULT toUInt8(s) fails with CANNOT_PARSE_TEXT when an old row's s does not parse: the read picks the narrowest column and computes its default for every part written before the ALTER.

Since #131371 (master only) the pick ranks columns by the table's column sizes. A column added by ALTER TABLE ... ADD COLUMN ... DEFAULT|MATERIALIZED <expr> is stored only by the parts written after the ALTER, so it ranks cheapest: with domain String MATERIALIZED domain(url) count() reads all of url (#131530), and with n UInt64 DEFAULT toUInt64(s) it throws as above. The planner's chooseSmallestColumnToReadFromStorage (query_plan_remove_unused_columns = 0) ranks the same way.

MergeTreeData::getColumnsReadableWithoutOtherColumns drops a candidate whose default reads stored columns (also through ALIAS columns) unless every part to read stores it. When a DROP COLUMN or RENAME COLUMN is pending, it resolves such candidates per part with AlterConversions as the reader does (a column re-added under a dropped name is read in old parts as its default). A column whose default reads no stored column stays a candidate, as on master: where a part does not store it, the reader reads that part's smallest column. ReadFromMergeTree::selectRangesToRead ranks the rest using the parts to read, and the planner using the snapshot's parts; when no candidate is left, the previous choice stays. A read of virtual columns only (GROUP BY _part) no longer picks a column whose default reads other columns. Merge tables are unchanged.

Validation: master fails 22 of 48 test statements; the fix passes 50/50 randomized runs. count() stays within noise of master on the alter_select performance test; with a MATERIALIZED column added to it, a trivial count() is up to 4 ms slower in a debug build.


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

groeneai and others added 7 commits November 14, 2026 10:43
A MergeTree read that needs no column of the table (`SELECT count()` that
has to scan, `sum(1)`, ...) reads one column only to learn the row count.
Since ClickHouse#131371, `ReadFromMergeTree::selectRangesToRead` ranks that column by
the table's column sizes, as the planner's
`chooseSmallestColumnToReadFromStorage` already did. Those sizes sum only the
parts that store a column, and a compact part adds 0 per column, so a column
added by `ALTER TABLE ... ADD COLUMN ... DEFAULT|MATERIALIZED <expr>` ranks
cheapest. For an older part that lacks it, `injectRequiredColumns` injects
the default expression's inputs, so the reader computes the default over
every row: it reads the source columns (45x the bytes in ClickHouse#131530) and throws
if the default fails on an old row (`CANNOT_PARSE_TEXT` for
`DEFAULT toUInt64(s)`), at default settings on master. The planner path has
the same problem on releases with `query_plan_remove_unused_columns = 0`.

`MergeTreeData::getColumnsStoredInAllParts` keeps the columns that every part
stores. Parts with the same columns share one interned position map, so each
distinct set is checked once. `selectRangesToRead` ranks among them using the
parts to read, and the planner using the storage snapshot's parts. If no
column is stored by every part, the previous choice stays: the type-ranked
column in `selectRangesToRead`, the unfiltered list in the planner.

Closes ClickHouse#131530

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

`getColumnsStoredInAllParts` decided "stored" by the part's column names only.
A column dropped by a pending `DROP COLUMN` mutation and re-added under the
same name (`ALTER TABLE t DROP COLUMN c, ADD COLUMN c UInt64 DEFAULT
toUInt64(s)`) is still in every old part, and its stale bytes count under that
name in the column sizes, so a narrow stale column ranks cheapest. The reader
treats it as missing in those parts (`AlterConversions::isColumnDropped`) and
computes the new default there, which reads `s` and throws `CANNOT_PARSE_TEXT`
on a row it cannot parse. A single `RENAME COLUMN a TO b, DROP COLUMN b, ADD
COLUMN a ...` is the same: the drop is recorded under the part-side name `a`,
while `getColumnsChangedOnFly` lists only `b`.

The helper now takes the mutations snapshot and skips the names it changes on
the fly plus every name of a pending `RENAME COLUMN` of the parts, the
predicate `getColumnsUpdatedOnFly` in `optimizeDirectReadFromTextIndex.cpp`
uses for the same reason. Both call sites pass their snapshot. The test gains
the drop/re-add and rename/drop/re-add cases with
`query_plan_remove_unused_columns` 0 and 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…narrow added column

A read of virtual columns only (`SELECT count() FROM t GROUP BY _part`) has a
non-empty column list, so neither call site of `getColumnsStoredInAllParts`
runs; `injectRequiredColumns` adds a row-count carrier per part instead, the
smallest of the part's columns that the metadata still has. That list kept a
column dropped by a pending `DROP COLUMN` mutation and re-added under the same
name, or renamed away by a pending `RENAME COLUMN`, although the same function
treats such a column as missing when it is requested, so the reader computed
the new column's default without its source column (`Code: 32 ... _CAST(
toUInt64('' AS s), 'UInt64')`). The fallback now prefers the part columns that
no pending mutation drops (`isColumnDropped`) or renames away
(`columnHasNewName`), and keeps the previous list when none is left.

The test gains a `GROUP BY _part` read for both pending-mutation tables and a
table whose added column is narrower than every other one
(`ADD COLUMN n UInt8 DEFAULT toUInt8(s)` on `(k UInt64, s String)`). That case
fails on releases at default settings: 26.3, 26.8 and 26.10 pick the narrowest
type as the carrier of a no-column read, so `SELECT count()` after a lightweight
`DELETE` throws `CANNOT_PARSE_TEXT` when an old row's `s` does not parse.

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

A pending `DROP COLUMN n` of a `Nested` column is recorded on the fly under the
parent name `n`, while the reader retires every member through the parent
(`AlterConversions::isColumnDropped` matches the part before the first `.`).
`getColumnsStoredInAllParts` compared only exact storage names, so after
`DROP COLUMN n, ADD COLUMN n.a ... DEFAULT ...` with the mutation pending it kept
the stale `n.a` (stored by every old part, ranked cheapest), and the reader then
computed the default for the old parts, e.g. `CANNOT_PARSE_TEXT` on `count()`.

The helper now also skips a name whose `Nested` parent is in the set. The parent
is matched regardless of `share_nested_offsets`: the filter only removes
carrier candidates, and an empty result keeps the previous choice.

The test gains `t_nested` (Nested parent dropped and re-added while the
mutation is pending), with `query_plan_remove_unused_columns` 1 and 0.

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

`getColumnsStoredInAllParts` excluded every name `getColumnsChangedOnFly`
returns. That set also holds columns a pending mutation only UPDATES (an
`ALTER ... UPDATE` applied on the fly, a lightweight-update patch column, a
pending type change); such a column is still stored by the parts and read with
the update applied, not computed as its default. On an `ORDER BY tuple()`
table where every stored column has a pending on-fly update, the helper
returned an empty list, both callers kept the previous choice, and the added
column's default was evaluated for the old parts (`CANNOT_PARSE_TEXT` on
`count()`).

It also matched the `Nested` parent unconditionally, while
`AlterConversions::isColumnDropped` does so only under `share_nested_offsets`.
With `share_nested_offsets = 0` a column `n.a` is independent of `n`, so a
pending `DROP COLUMN n, ADD COLUMN n ... DEFAULT f(n.a)` removed the readable
`n.a` too and, with nothing left, the re-added `n` was read as its default.

The helper now excludes only the names a pending mutation retires (the
column of a pending `DROP COLUMN`, both names of a pending `RENAME COLUMN`),
matches a `Nested` parent only when the table has `share_nested_offsets`, and
ranks the columns a pending mutation only updates after the others.

The test gains `t_updated` (every stored column with a pending on-fly
`UPDATE`) and `t_independent` (`share_nested_offsets = 0`), each with
`query_plan_remove_unused_columns` 1 and 0.

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

`getColumnsStoredInAllParts` checked the part's column NAMES and re-derived
the pending `DROP COLUMN` / `RENAME COLUMN` semantics by hand, retiring the
dropped name and both names of a rename. The reader does not work by names:
`injectRequiredColumnsRecursively` maps a renamed column to its old name
(`isColumnRenamed` / `getColumnOldName`) and reads it from the part, and
treats a column as missing only when the part lacks that name or
`isColumnDropped` holds. So after a pending `RENAME COLUMN s TO t`, `t` is
stored data in every old part, read as `s`, but the helper dropped it. With
`s` the only column, the list was empty, both callers kept the added column
`n UInt8 DEFAULT toUInt8(t)` and its default was computed for the old part
(`CANNOT_PARSE_TEXT` on `count()`). It was the fifth divergence between the
helper's notion of a stored column and the reader's.

The helper now builds an `AlterConversions` from each part's pending
metadata commands (`RENAME_COLUMN` / `DROP_COLUMN`, the only ones that feed
its rename map and dropped set; for them the constructor uses no context and
cannot throw) and applies the reader's resolution. Chained renames,
drop-after-rename and the `Nested` parent under `share_nested_offsets` follow
from it. Parts without such commands keep the check on their interned column
positions. The callers pass their query context.

The test gains `t_renamed` (pending `RENAME COLUMN s TO t` next to an added
column whose default reads `t`), with `query_plan_remove_unused_columns` 1
and 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove two comments in getColumnsStoredInAllParts that narrate the new code's design.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-6): 10 findings, 7 fixed in later commits, 3 out of scope; round 6 found none
Finding Verdict
❌ r1: the "stored in all parts" filter accepted a column dropped by a pending mutation and re-added under the same name (old parts still list the stale column, the reader computes the new default there). AGREE: the filter also skips names a pending mutation drops or renames away; test cases added.
❌ r2: a read of virtual columns only (count() ... GROUP BY _part) picks its column per part and could still pick such a stale column. AGREE: the per-part fallback skips columns a pending mutation drops or renames away; test cases added.
⚠️ r2: releases pick the column by type width at default settings, so an added column narrower than every other one may already fail there; the changelog category depends on it. AGREE: measured on official releases, category set by the result.
❌ r2: a Merge table ranks the columns by its children's summed sizes and forwards the pick to each child, so it still reads the added column. DISAGREE (out of scope: separate PR): unchanged by this PR and present on 26.10; needs a separate mechanism in StorageMerge.
❌ r3: a pending DROP COLUMN n of a Nested column retires n.a through its parent, but the filter matched exact names, so a re-added n.a could still be picked. AGREE: the filter also matches the Nested parent name; test case added.
❌ r4: on an ORDER BY tuple() table where every stored column has a pending update, the filter left no column, so the old pick (the added column) came back. AGREE: only columns a pending mutation drops or renames away are skipped; columns it only updates rank after the others; test case added.
❌ r4: with share_nested_offsets = 0, a pending drop of a column n also skipped the independent column n.a. AGREE: the Nested parent is matched only when share_nested_offsets is on, as the reader does; test case added.
❌ r4: a user granted only the added column still computes its default with query_plan_remove_unused_columns = 0. DISAGREE (out of scope): a developer-only setting; the planner keeps its pre-existing restriction to granted columns, unchanged since 26.10; correct at the default.
❌ r4, r5: a read of virtual columns only, on a part whose columns all have a pending rename, injects the old name (NO_SUCH_COLUMN_IN_TABLE). DISAGREE (out of scope: separate PR): unchanged master code, no default is computed; the fix for this class (#114562) was reverted in #119429.
❌ r5: when every stored column has a pending RENAME COLUMN, the filter found no column under its current name, so the old pick (the added column) came back. AGREE: pending drops and renames are now resolved with AlterConversions, as the reader does; test case added.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Each of the test's twenty SELECT count() statements, run on master a33e1c1612ba7 through clickhouse local, fails on every run: two with TOO_MANY_BYTES (968.75 KiB read against a 97.66 KiB limit), sixteen with CANNOT_PARSE_TEXT and two (GROUP BY _part) with Code: 32. The narrow-column case also fails at default settings on 26.3.60, 26.8.34 and 26.10.2.
b Root cause explained? getColumnSizes() sums only the parts that store a column, and compact parts add 0, so a column added by ALTER ... ADD COLUMN ... DEFAULT/MATERIALIZED ranks cheapest. For older parts injectRequiredColumns then evaluates its default, which reads its source columns and can throw.
c Fix matches root cause? Yes. Only columns stored by every part to read are ranked; the sizes and the reader are unchanged.
d Test intent preserved / new tests added? New test 05771_no_column_read_column_missing_in_old_parts: the issue's repro (MATERIALIZED, compact new part), a throwing DEFAULT (wide new part), an added column narrower than every other one, a column dropped (or renamed away) and re-added while the mutation is pending, a Nested member whose parent is dropped and re-added, a table whose every stored column has a pending UPDATE applied on the fly, a column n dropped and re-added next to an independent n.a under share_nested_offsets = 0, and a table whose only column has a pending RENAME COLUMN s TO t next to an added column whose default reads t, each with query_plan_remove_unused_columns 0 and 1, plus a GROUP BY _part read for the pending-mutation cases.
e Both directions demonstrated? Yes. Master fails 20/20; the fix passes 20/20 and 50/50 randomized. Reverting one call site fails exactly the nine statements of its path; reverting the per-part change fails exactly the two GROUP BY _part statements.
f Fix is general across code paths? Both rankings that use the table-wide sizes (selectRangesToRead and the planner's chooseSmallestColumnToReadFromStorage) go through one helper, which resolves pending drops and renames with AlterConversions built from each part's pending metadata commands, as the reader does, and ranks the columns a pending mutation only updates after the others. The per-part fallback in injectRequiredColumns (reads of virtual columns only) skips columns a pending mutation drops or renames away, as its own predicate for requested columns does. Merge tables are out of scope (separate mechanism).
g Fix generalizes across inputs (params/datatypes/wrappers)? Covers MATERIALIZED and DEFAULT, String, UInt64 and UInt8 added columns, compact and wide parts, pending DROP COLUMN, RENAME COLUMN (a re-added old name, and a renamed column read under its old name in the old parts) and on-fly UPDATE, a Nested member under share_nested_offsets = 1 and an independent dotted column under share_nested_offsets = 0, MergeTree and ReplicatedMergeTree. Subcolumns map to their storage column. An access-filtered planner list can only narrow. When no column is stored by every part, the previous choice stays.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change, and nothing changes while every part stores the cheapest column.
i Invariants and contracts preserved? The read still names one physical column; the helper only reads immutable part snapshots and the snapshot's pending commands. SELECT count() over 1000 parts x 200 columns stays within noise; with a pending RENAME COLUMN on every part its median goes from 18-22 ms to 23-29 ms (debug build).

Session id: cron:clickhouse-impl-slot-40:20261114-180900

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d4afbaf]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR filters row-count carrier columns to avoid evaluating defaults that read other stored columns during MergeTree reads. One significant scan regression remains: a column missing from a tiny old part is excluded from all newer parts, forcing them to read a large payload column.

Findings

❌ Blockers

  • src/Storages/MergeTree/MergeTreeData.cpp:9974: The global eligibility filter discards a cheap added column whenever any old part lacks it and its default references another stored column. With ten old numeric strings, ADD COLUMN k UInt8 DEFAULT toUInt8(s), and 1000 new large strings inserted with explicit k = 0, forced-scan count reads 963020 bytes on head d4afbaf0 versus 20 bytes on base 58726cc5 (48,151×), with either chooser setting. After a lightweight deletion, default count returns 1009 on base but throws TOO_MANY_BYTES on the PR under max_bytes_to_read = 100000. Choose carriers per part so parts storing k keep using it and older parts use a stored carrier without evaluating the default.
Tests
  • ⚠️ Add a focused stateless regression for a dependency-bearing added default missing only from a small old part, followed by large new parts that store the column. Cover both values of query_plan_remove_unused_columns and assert the byte limit; the added constant-default case does not exercise this branch.
Final Verdict

❌ Block — Preserve cheap per-part row-count reads for dependency-bearing added columns and add the focused regression above.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 71a9df4f7 with master 58726cc5c (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

8 object files changed (+24.27 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.44 MiB 4.46 MiB +21.26 KiB (+0.47%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.57, programs/clickhouse-keeper ×0.65 (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.4 s 11.6 s +7.9 s (+218%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.2 s +5.2 s (+261%)
Compile time of recompiled translation units

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

Job report

… changes them

Resolving pending drops and renames built an `AlterConversions` for every part with a
pending metadata mutation on each read that needs no column, including the planner's
choice for a trivial `count()`. With 10000 parts and a pending `DROP COLUMN`
(`tests/performance/alter_select.xml`) `select count()` became 2.3-2.5x slower.

A pending drop or rename changes what a part stores only under a name it names or under
that name's Nested parent. So the columns no pending mutation changes are checked by
name against the distinct part column sets, and the per-part resolution runs only when
none of them is stored in every part. `getColumnsChangedOnFly` now also returns the
names of pending renames, so this needs no per-part lookup; its other user, the text
index direct read, already excluded those names for the parts it reads.

alter_select fixture, debug build, base and fix servers side by side, 300 interleaved
runs: count() median 6.97 / 6.79 ms (MergeTree) and 8.96 / 9.32 ms (Replicated) for
master / fix; the previous head was 19.46 / 27.07 ms against 7.60 / 10.87 ms.

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

With `apply_mutations_on_fly = 1` the reader recalculates a stored
MATERIALIZED column whose expression reads a column a pending UPDATE
changes (`AlterConversions::buildMutationChainForRead`), so reading it
reads its dependencies and can throw. `getColumnsStoredInAllParts`
listed only assignment targets as changed and preferred such a column
over the directly updated ones: with `m UInt64 MATERIALIZED toUInt64(s)`
and a pending `UPDATE k = k, s = concat(s, 'x')`, `count()` read `m`
and threw CANNOT_PARSE_TEXT (TOO_MANY_BYTES with `sipHash64(s)` under
`max_bytes_to_read`) at both values of
`query_plan_remove_unused_columns`, while master reads `k` and returns
the row count.

When the snapshot has data mutations, the helper now also counts as
changed the MATERIALIZED columns `MaterializedColumnDependencies` says
the read recalculates, the same graph the reader uses. The planner and
`selectRangesToRead` pass the table's columns for it. Measured on a
100-part table with 30 MATERIALIZED columns and a pending UPDATE (debug
build): `count()` 13.4 ms vs `count(m11)` 12.8 ms, so the analysis
costs under 1 ms; master's `count()` takes 53 ms there, reading the
updated column with the mutation applied. Snapshots without data
mutations (e.g. `alter_select`'s pending DROP COLUMN) skip it.

Found by clickhouse-gh review:
ClickHouse#131671 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`getColumnsStoredInAllParts` preferred the columns no pending mutation
changes over every other stored column, and since the previous commit
also counted the MATERIALIZED columns a pending UPDATE recalculates as
changed. Both rules only work around data mutations: an updated column
is still stored in the part and read from it with the update applied,
exactly as master reads it. The preference made `count()` read a large
`String` instead of an updated `UInt8` (`ALTER TABLE t UPDATE k = k`
with `apply_mutations_on_fly = 1`, or a lightweight `UPDATE t SET k =
k + 1`): TOO_MANY_BYTES at both values of
`query_plan_remove_unused_columns`, while master reads `k`.

The helper now separates columns only by whether a part stores them, as
the reader resolves them: only a pending DROP COLUMN or RENAME COLUMN
(of the column or of its Nested parent) changes what a part stores under
a name, so only then does it resolve candidates per part; every other
candidate is checked by name and all of them are ranked by size. That
removes the preference, the MATERIALIZED dependency analysis and the
helper's `table_columns` parameter. With the bot's MATERIALIZED case
(`m UInt64 MATERIALIZED toUInt64(s)`, pending `UPDATE k = k, s = ...`)
the cheapest column is `k` again, as on master.

Measured (debug, A/B with the master snapshot a33e1c1): the four new
05771 statements fail on 34ff795 and pass here and on master; 05771
26/26, master fails 20/26; 50/50 randomized; dropping the Nested-parent
check fails exactly the two t_nested statements. tests/performance/
alter_select.xml count(): fix/master 8.6/7.3 ms (mt), 11.9/10.6 (rmt);
ports swapped 10.5/10.0, 11.1/11.6, i.e. within noise: its pending
DROP COLUMN names no current column, so no per-part resolution runs.

Found by clickhouse-gh review:
ClickHouse#131671 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reader fills a column that a pending mutation drops from its default.
That only matters when the default is computed: evaluating it can read
other columns and throw. A column with no default, or with a literal one,
is filled without evaluating anything, so a pending `CLEAR COLUMN` or a
drop and re-add of such a column no longer stops it from being the
cheapest carrier (master reads 8 KB there, the previous head read the whole
`String` column). A column a part does not store at all is still never
used. The per-part reader fallback gets the same rule.

Pending renames are no longer added to `getColumnsChangedOnFly`: that set
also covers completed mutations that are still kept in the history, so the
text index consumer disabled direct reads after any `RENAME COLUMN`. The
helper instead resolves pending drops and renames per part when the
snapshot has metadata mutations and some candidate's default is computed;
parts with the same pending commands share one `AlterConversions`. The
`alter_select` performance test is back to master (it has no such column).

Addresses the clickhouse-gh review comments r4577022930 and r4577022936.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 3 commits November 15, 2026 08:58
…ored under its name

With no candidate whose default is computed, the per-part resolution of pending drops and
renames was skipped, so a column renamed by a pending `RENAME COLUMN` was checked by its new
name against old parts, which store it under the old one. After an insert gave the new name a
size entry, `count()` read an unrelated large column instead (clickhouse-gh r4577586674):
`RENAME COLUMN k TO renamed` + one insert made `count()` read the whole `s` column, while
master reads `renamed` (the reader resolves it to `k` in old parts).

Resolve per part also when some part does not store a candidate under its current name.
Tables whose candidates every part stores by name (the `alter_select` performance test) keep
the fast path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…reads other columns

A pending `DROP COLUMN`/`CLEAR COLUMN` makes the reader fill the column from its default. That is a problem
only when the default reads other columns: the reader then reads them (the default's identifiers, as
`injectRequiredColumnsRecursively` collects them) and can throw on old rows. The previous rule kept only a
column with no default or a literal one, so a constant default such as `toUInt8(0)` or `now()` made a
`count()` read a whole unrelated `String` column, where master reads the cheap column.

The per-part fallback of `injectRequiredColumns` also skipped a part column renamed away by a pending
`RENAME COLUMN` and re-added under the same name. The reader reads such a column from the part, so skipping
it only forced a scan of another column (`RENAME COLUMN k TO renamed, ADD COLUMN k UInt8 DEFAULT 0`,
`SELECT count() ... WHERE _part_offset % 2 = 0`: master reads `k`). That check is removed.

A default that throws without reading any column (`DEFAULT throwIf(1)`) is used again, as on master; such a
default also fails every `INSERT` that omits the column. The test case for it is removed, and cases for a
constant default and for a rename with a re-added column are added.

Reported by clickhouse-gh in ClickHouse#131671 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`defaultReadsColumns` treated every identifier of the default expression as a
column read, including the parameters of a lambda. So the constant default
`k UInt8 DEFAULT arraySum(arrayMap(x -> x, [toUInt8(0)]))` disqualified `k` as
the row-count carrier while a `CLEAR COLUMN k` was pending, and `count()` read
the whole `String` column instead of `k`, as master does.

Use `getStorageColumnsReadByDefault`, which collects the required source
columns with `RequiredSourceColumnsVisitor` (lambda parameters and dictionary,
table and set names are not reads). When a lambda parameter shadows a column
name, `k` is now kept as on master, and the reader still reads the shadowed
column for the default in the chooser paths, also as on master.

`getColumnsStoredInAllParts` evaluates the predicate only when some part has
pending drops or renames.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A no-column read excluded every column that some part does not store,
and treated a default that names an ALIAS column as reading a column.
Both made `count()` scan a large unrelated column where master reads a
cheap one:

- `ALTER TABLE t ADD COLUMN k UInt8 DEFAULT 0` with old parts that lack
  `k`: the reader fills `k` there from its default and reads the part's
  own smallest column, so `k` is a valid carrier.
- `k UInt8 DEFAULT c`, `c UInt8 ALIAS 0`: the default reads no stored
  column, but `getStorageColumnsReadByDefault` returns `c`.

So the presence check now applies only to a column whose default reads
stored columns, which is the case that reads other columns and can throw
(ClickHouse#131530). `defaultReadsColumns` follows ALIAS and EPHEMERAL columns
into their own expressions, the way `injectRequiredColumnsRecursively`
resolves them through `getDefault`; cyclic aliases are rejected at DDL
time. The answers are cached across the candidates of one scan, so a
shared alias chain or DAG is expanded once. A default-less column needs no per-part work at all, and the
pending-rename trigger is gone with it: a renamed column without a
default is always readable.

The helper is renamed to `getColumnsReadableWithoutOtherColumns`, as it
no longer returns only columns every part stores.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Read a column every part stores when a MergeTree read needs no column Do not compute a default from other columns when a MergeTree read needs no column Nov 15, 2026

NamesAndTypesList result;
for (const auto & column : columns)
if (!default_reads_columns.contains(column.getNameInStorage()) || is_stored(column.getNameInStorage()))

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.

[Blocker] Choose row-count carriers per part instead of excluding a cheap column globally

If an added column has a default that reads another column, one tiny old part lacking it removes it from the entire cost comparison. This forces every newer part to scan an unrelated large column, even though those parts already store the cheap carrier. The constant-default exception does not cover this case:

CREATE TABLE t (s String) ENGINE = MergeTree ORDER BY tuple()
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO t SELECT toString(number) FROM numbers(10);
DELETE FROM t WHERE s = '0';
SYSTEM STOP MERGES t;
ALTER TABLE t ADD COLUMN k UInt8 DEFAULT toUInt8(s);
INSERT INTO t (s, k)
SELECT repeat(hex(sipHash128(number)), 30), 0 FROM numbers(1000);
SELECT count() FROM t SETTINGS max_bytes_to_read = 100000;

Base 58726cc5 returns 1009; current head d4afbaf0 throws TOO_MANY_BYTES at 940.46 KiB. Both values of query_plan_remove_unused_columns reproduce it. Without the deletion, forcing a scan and removing the byte limit returns 1010 on both binaries, but statistics.bytes_read increases from 20 to 963020 (48,151×). The helper removes k because the ten-row part lacks it, so the read uses s in all parts.

Please select row-count carriers per part, using a stored column in parts that lack the cheap candidate without evaluating its default. Preserve the throwing-default fix while avoiding a full payload scan in every newer part, and cover this case in both chooser paths.

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.

Reproduced (20 -> 963,020 bytes; with one non-numeric s in the old part master throws and this PR returns the count). One read column cannot serve both, so I asked for a design decision before changing this: #131671 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov, one design decision before I add more cases to this PR.

#131371 made a read that needs no column take the column with the smallest table-wide size. A column added by ALTER ADD COLUMN is missing from old parts, so its size counts only the new parts, and in an old part the reader computes its default, which reads other columns and can throw (#131530). This PR therefore skips a column whose default reads stored columns unless every read part stores it.

The latest bot finding (#131671 (comment)) is the limit of that rule. An added k UInt8 DEFAULT toUInt8(s) missing only from a 10-row old part is skipped, so count() reads s in every part: 963,020 bytes instead of 20 on master and 26.10.2. With one non-numeric s in that old part, master and 26.10.2 throw CANNOT_PARSE_TEXT and this PR returns the count. Getting both needs a per-part choice, which one read column cannot give.

  1. Keep this PR: a no-column read does not compute a default that reads other columns; the cost above is reading the cheapest column that every part stores.
  2. Per-part: request no column and let each part read its own smallest stored column, the fallback injectRequiredColumns uses for virtual-only reads. On master that fallback reads s in a compact (s String, k UInt8) part (948 KiB, where count() reads k) and ignores pending renames, the area of Fix NO_SUCH_COLUMN_IN_TABLE naming a column absent from the table when a part's columns were all renamed or all dropped #114562, reverted in Revert "Fix NO_SUCH_COLUMN_IN_TABLE naming a column absent from the table when a part's columns were all renamed or all dropped" #119429. Both need fixing first.
  3. Revert Read the column that is smallest on disk when a MergeTree read needs no column #131371 and close this PR (its 26.10 cherry-pick Cherry pick #131371 to 26.10: Read the column that is smallest on disk when a MergeTree read needs no column #131655 is still open).

Which one do you prefer? I would take 1.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

No-column read ranks a column old parts lack as cheapest: 45x bytes read

1 participant