Repository navigation
Conversation
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]>
Internal second-model review (rounds 1-6): 10 findings, 7 fixed in later commits, 3 out of scope; round 6 found none
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20261114-180900 |
|
Workflow [PR], commit [d4afbaf] Summary: ❌
AI ReviewSummaryThe PR filters row-count carrier columns to avoid evaluating defaults that read other stored columns during Findings❌ Blockers
Tests
Final Verdict❌ Block — Preserve cheap per-part row-count reads for dependency-bearing added columns and add the focused regression above. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes8 object files changed (+24.27 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units255 translation units recompiled, 2837 s compile time in total, 255 of them have a recent master baseline. |
… 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]>
…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]>
|
|
||
| NamesAndTypesList result; | ||
| for (const auto & column : columns) | ||
| if (!default_reads_columns.contains(column.getNameInStorage()) || is_stored(column.getNameInStorage())) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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)
|
@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 The latest bot finding (#131671 (comment)) is the limit of that rule. An added
Which one do you prefer? I would take 1. |
Closes: #131530
Related: #131371
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
SELECT count()and other reads of aMergeTreetable that need no column failing, or reading much more data than needed, afterALTER TABLE ... ADD COLUMNwith a default expression: for the parts written before theALTER, 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 lightweightDELETEover a table with a column added byADD COLUMN n UInt8 DEFAULT toUInt8(s)fails withCANNOT_PARSE_TEXTwhen an old row'ssdoes not parse: the read picks the narrowest column and computes its default for every part written before theALTER.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 theALTER, so it ranks cheapest: withdomain String MATERIALIZED domain(url)count()reads all ofurl(#131530), and withn UInt64 DEFAULT toUInt64(s)it throws as above. The planner'schooseSmallestColumnToReadFromStorage(query_plan_remove_unused_columns = 0) ranks the same way.MergeTreeData::getColumnsReadableWithoutOtherColumnsdrops a candidate whose default reads stored columns (also throughALIAScolumns) unless every part to read stores it. When aDROP COLUMNorRENAME COLUMNis pending, it resolves such candidates per part withAlterConversionsas 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::selectRangesToReadranks 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.Mergetables are unchanged.Validation: master fails 22 of 48 test statements; the fix passes 50/50 randomized runs.
count()stays within noise of master on thealter_selectperformance test; with aMATERIALIZEDcolumn added to it, a trivialcount()is up to 4 ms slower in a debug build.Workflow [PR]
Sync PR [sync-upstream/pr/131671]