Skip to content

Fix reading subcolumns of an ALIAS column after ALTER TABLE ... COMMENT COLUMN - #121449

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-alias-subcolumns-columnsdescription-modify
Sep 24, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-alias-subcolumns-columnsdescription-modify

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

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 ALTER TABLE ... COMMENT COLUMN and ALTER TABLE ... RENAME COLUMN making reads of an ALIAS column's subcolumns (for example arr.size0) fail with NO_SUCH_COLUMN_IN_TABLE until the table was reloaded. Closes #121421.

Description

Closes #121421. Related: #119469, where @ PedroTadim named this asymmetry and @ evillique asked for it as its own PR with an issue.

On 26.8.2.7 and 26.3.33.10, SELECT arr.size0 FROM t fails with NO_SUCH_COLUMN_IN_TABLE after ALTER TABLE t COMMENT COLUMN arr 'c', though it returned 2 immediately before:

CREATE TABLE t (id UInt64, arr Array(UInt64) ALIAS [id, id]) ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (7);
SELECT arr.size0 FROM t;                 -- 2
ALTER TABLE t COMMENT COLUMN arr 'c';
SELECT arr.size0 FROM t;                 -- Code: 16 ... NO_SUCH_COLUMN_IN_TABLE

ColumnsDescription::add() registers no static subcolumns for an ALIAS column, since an alias's subcolumns are derived from its expression. modify() registered them unconditionally, so any ALTER reaching it put arr.size0 into the subcolumn index with an Alias parent. The read then resolves that entry as a plain physical column, and the MergeTree lookup, which matches it against AllPhysical, discards it and throws. The index is in-memory derived state, so a reload heals the table, and the ALTER and the SELECT must share one process to see the bug.

The fix gives modify() the guard add() already has, reading the kind after the mutation, so a column that stops being an alias stays registered and one that becomes an alias does not. The added invalidateGetCache() keeps modify()'s cache invalidation unconditional instead of leaving it a side effect of addSubcolumns; it preserves today's behaviour rather than fixing an observed staleness.

RENAME COLUMN of any column is a second trigger, since it re-applies modify() to every column of the table. Fixed as well.

Validation: the new test fails on master and passes with the fix; 50 randomized runs green; the alias-subcolumn and comment-column suites stay green, including 04738_merge_subcolumn_of_alias_parent, which asserts the opposite behaviour through a Merge table.

cc @evillique


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

Version info

  • Merged into: 26.10.1.601-master (included in 26.10 and later)

groeneai and others added 2 commits September 21, 2026 20:51
…fied

On 26.8.2.7 and 26.3.33.10, SELECT arr.size0 FROM t fails with
NO_SUCH_COLUMN_IN_TABLE after ALTER TABLE t COMMENT COLUMN arr 'c', although
it returned 2 immediately before that statement:

    CREATE TABLE t (id UInt64, arr Array(UInt64) ALIAS [id, id])
    ENGINE = MergeTree ORDER BY id;
    INSERT INTO t VALUES (7);
    SELECT arr.size0 FROM t;                 -- 2
    ALTER TABLE t COMMENT COLUMN arr 'c';
    SELECT arr.size0 FROM t;                 -- Code: 16 NO_SUCH_COLUMN_IN_TABLE

ColumnsDescription::add() deliberately registers no static subcolumns for an
ALIAS column (ColumnsDescription.cpp:455-458), because an alias has none of its
own: they are derived from its expression. ColumnsDescription::modify() did it
unconditionally, so every ALTER that reaches it on an ALIAS column inserted
arr.size0 into the subcolumns index with an Alias parent. The chain from there:

  1. get(All + withSubcolumns) emits arr.size0, since addSubcolumnsToList skips
     subcolumns of Ephemeral parents only, so it enters the analyzer's
     column_names_and_types.
  2. getDefault("arr.size0") consults columns only, finds nothing, and the
     node-map populator emplaces a plain expression-less ColumnNode
     (QueryAnalyzer.cpp:5026-5031).
  3. Identifier resolution therefore hits node_map.find and skips the
     alias-expression rewrite wrapExpressionNodeInSubcolumn
     (IdentifierResolver.cpp:768-776) that would have produced
     getSubcolumn([id, id], 'size0').
  4. With no expression the planner hands "arr.size0" to storage->read, and the
     MergeTree read re-asks with AllPhysical, where
     defaultKindToGetKind(Alias) == Aliases(4) and Aliases & AllPhysical(3) == 0
     (ColumnsDescription.cpp:876-878): the entry is found, discarded, and the
     lookup throws NO_SUCH_COLUMN_IN_TABLE.

The asymmetry dates to dcd7312 (2022-02-09), so every supported release
carries it. The subcolumns container is derived in-memory state (toString()
iterates columns only), so nothing is persisted, a DETACH/ATTACH heals the
table, and the ALTER and the failing SELECT must run in the same process for
the failure to be visible.

ALTER TABLE ... RENAME COLUMN is a second trigger: AlterCommand::apply
(AlterCommands.cpp:1276) re-applies modify() to every column of the table, so
renaming any column re-registers the subcolumns of every ALIAS column. Measured
as Code: 16 before this change and 2 after it.

The kind is read AFTER the mutation so that the guard describes the resulting
column: MODIFY COLUMN arr REMOVE ALIAS and MODIFY COLUMN arr <T> DEFAULT <expr>
turn an ALIAS into a physical column and must then register subcolumns, while
the opposite direction must stop registering them (the removeSubcolumns call
already handles the removal).

The explicit invalidateGetCache() keeps modify()'s cache invalidation
unconditional. Today the only guaranteed invalidation on the alias path is a
side effect of addSubcolumns (ColumnsDescription.cpp:1139, which invalidates
whether or not the type yields any subcolumn), while removeSubcolumns
invalidates only when it erased something and modifyColumnOrder only when
first/after_column is set. Skipping addSubcolumns for an alias without this call
would have silently removed that guarantee. Placing it before the new branch
makes the behavioural delta of this change exactly "an ALIAS column is no longer
registered". No staleness is observable today, so this preserves the existing
invalidation rather than fixing an observed bug.

Alternatives rejected:

  - Moving the guard into addSubcolumns() is not implementable: add() calls it
    before inserting the column into columns, so the callee cannot look the kind
    up. The guard has to live at the call site.
  - A comment-only ColumnsDescription::setComment was rejected on ClickHouse#119469, and
    it would fix only COMMENT COLUMN, leaving MODIFY COLUMN and RENAME COLUMN
    broken.
  - Fixing AlterCommand::apply is the wrong layer: ColumnsDescription owns the
    subcolumn index, and there are seven modify() call sites.
  - Teaching the read path to accept an ALIAS parent under AllPhysical would
    make a non-materialised column look physically readable, and the alias
    expression is already lost by then, so the read would have no data to
    compute from. The defect is the registration, not the lookup.
  - Widening addSubcolumnsToList to skip Alias parents papers over one consumer
    of a corrupt index and leaves tryGetColumn, hasSubcolumn and
    InterpreterDescribeQuery still answering for a phantom subcolumn.

No setting, no serialization and no stored metadata change, so no
SettingsChangesHistory.cpp entry is owed and a mixed-version cluster sees
identical metadata.

Closes: ClickHouse#121421
Related: ClickHouse#119469

Co-Authored-By: Claude Opus 5 <[email protected]>
Test-only follow-up to the previous commit; src/ is unchanged. Three additions
to 05235_alter_comment_column_alias_subcolumn.

1. ALTER TABLE ... RENAME COLUMN. RENAME_COLUMN is its own branch of
   AlterCommands::apply (AlterCommands.cpp:1268-1283), calling columns.rename()
   and then modify() over every column of the table, so renaming any column
   re-registers the subcolumns of every ALIAS column. That trigger was measured
   but not covered by the suite. Renaming the unrelated physical column and
   reading arr.size0 next to it returns "2 3" with the fix and
   Code: 16 NO_SUCH_COLUMN_IN_TABLE without it, measured on a fresh table so
   that the arm fails on its own rather than after an earlier arm.

2. The REMOVE ALIAS arm reads two rows now. Its single asserted value was 0,
   which is the Array(UInt64) default for a part written before the column
   became physical, so a read that silently answered the type default would
   have passed it as well. Inserting a row after the ALTER makes the expected
   output 0 then 4.

3. ALTER TABLE ... MODIFY COLUMN <physical> Array(UInt64) ALIAS <expr>, the
   direction in which a column stops being physical. This is what pins the
   guard on the kind AFTER the mutation: reading the kind before the mutation
   still registers subcolumns for a column that has just become an alias, and
   the read then fails with Code: 16, while reading it after the mutation
   answers 2. The opposite direction cannot distinguish the two, because
   MODIFY COLUMN ... REMOVE ALIAS re-enters modify() with the column already
   physical, and the entry is registered either way.

The reference is regenerated from the patched build's own output.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 21, 2026
@groeneai

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

Pre-publication review in two independent parts: my own cold read of the resulting code, and a cold
review by an independent model (engine: codex). Every finding is adjudicated against the code or
against a measurement, never against prose. Round 1: 5 nits from me, 1 major from the model, 0
blockers. Round 2, on the grown test against an unchanged src/: 0 findings from either.

# Finding Verdict
⚠️ The changelog entry promises RENAME COLUMN is fixed, but the test exercised only COMMENT COLUMN, and RENAME_COLUMN is its own branch in AlterCommand::apply. Agreed, fixed: the test now renames an unrelated column and reads the alias subcolumn, asserting 2 3; in isolation that arm throws NO_SUCH_COLUMN_IN_TABLE on an unpatched server. A fix placed in AlterCommand::apply would pass the old test and fail this arm.
💡 The arm reading arr.size0 after REMOVE ALIAS asserted 0, which is also the type default, so a read answering with a default would have passed it. Agreed, fixed: a row is inserted after the REMOVE ALIAS, so the arm asserts 0 then 4.
💡 The guard reads the column kind after the mutation, but every transition exercised was alias-to-physical, where the entry is re-derived either way. Agreed, probed and pinned: the opposite transition separates the two readings. ALTER TABLE p MODIFY COLUMN phys Array(UInt64) ALIAS [id, id] is accepted, after which the fix answers 2 while a variant reading the kind before the mutation throws NO_SUCH_COLUMN_IN_TABLE. That shape is now a test arm; the fix was not changed to make it pass.
💡 The title named no user-facing trigger and described the inverse of the mechanism; a reviewer handle appeared in plain commentary as well as in the cc. Agreed, both fixed in this PR's text.
❌ flattenNested() also calls addSubcolumns without the kind guard. Disagreed (out of scope, and measured): an ALIAS column of a Nested(...) type is flattened at CREATE, and reading it already fails inside the alias expression with ILLEGAL_TYPE_OF_ARGUMENT, so the registration is not observable. One root cause per PR, as asked.
❌ ColumnsDescription::rename() does not re-key the subcolumn index, leaving entries whose parent column name is gone. Disagreed (pre-existing, not widened): this change strictly reduces the number of registered entries, and no path from a query to those lookups could be established. A different defect, neither fixed nor claimed here.

Validation behind the change rather than the review: the new test fails on unpatched master and
passes with the fix through the real runner on build-ID-verified servers, each arm also measured in
isolation on a fresh table; 330 tests matching the subcolumn, comment-column, rename-column,
modify-column and alias-column shapes were run on a patched and a pristine server and the only
difference in the whole failure set is the new test itself; 50 randomized runs green;
ColumnsDescriptionTest green; clang-tidy clean on the affected translation units;
04738_merge_subcolumn_of_alias_parent, which asserts the opposite behaviour through a Merge
table, stays green.

One negative is reported as a negative: dropping the explicit invalidateGetCache() is not
observable today, so that line preserves an existing guarantee instead of fixing an observed
staleness, and no test arm claims otherwise.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand: one clickhouse local --queries-file process exits rc=16 with Code: 16 ... NO_SUCH_COLUMN_IN_TABLE, and clickhouse-test reports [ FAIL ] on an unpatched server. No rate, no race.
b Root cause explained? modify() called addSubcolumns unconditionally, so an ALTER on an ALIAS column put arr.size0 in the subcolumn index with an Alias parent; the read resolves it as a plain physical column and the MergeTree AllPhysical lookup discards it and throws. Introduced by dcd7312d75aa4 (2022-02-09).
c Fix matches root cause? The defect is the registration, so the fix is the missing guard at the registration site, the one add() already has. Teaching the read path to accept an Alias parent and widening addSubcolumnsToList were both rejected as papering over a corrupt index.
d Test intent preserved / new tests added? New standalone 05235_alter_comment_column_alias_subcolumn.{sql,reference}, no tags, parallel-safe, six arms: COMMENT COLUMN, a physical control column, the stored comments, RENAME COLUMN, REMOVE ALIAS (two rows, so the truth differs from the type default) and the physical-to-ALIAS direction. Reference generated from the patched build; no existing test weakened or retargeted.
e Both directions demonstrated? Yes, on Build-ID-verified servers: [ FAIL ] with Code: 16 on base, [ OK ] on the fix. Each arm was also measured in isolation on a fresh table, so no arm's failure is inherited from an earlier one: RENAME COLUMN goes Code: 16 -> 2 3, physical-to-ALIAS goes Code: 16 -> 2.
f Fix is general across code paths? All 7 modify() call sites checked, including RENAME_COLUMN (re-applies modify() to every column, the second trigger) and StorageMerge.cpp:330, the highest-risk carrier, covered by 04738_merge_subcolumn_of_alias_parent staying green. flattenNested() is unreachable with an ALIAS parent, since such a column is flattened at CREATE, so it is deliberately untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes by construction: the guard reads a ColumnDefaultKind, never a type, so Array.size0, Nullable.null, Map.keys/values, Tuple.<elem> and String.size all take the same path. All three directions of the alias boundary were exercised: alias-stays-alias, alias-to-physical and physical-to-alias.
h Backward compatible? (maintainer-approved exception only) Nothing owed: no setting, so no SettingsChangesHistory.cpp entry, and no serialization or stored metadata, since toString() iterates columns only and the subcolumn index is never persisted. Verified on a real ReplicatedMergeTree with is_readonly = 0.
i Invariants and contracts preserved? The diff restores one: an ALIAS column is never in the static subcolumn index, which is already the state CREATE TABLE and any restart produce. No signature, lifetime or locking change, the LOGICAL_ERROR path is untouched, and the explicit invalidateGetCache() keeps modify()'s existing invalidation unconditional.

Session id: cron:clickhouse-impl-slot-4:20260921-212200

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9456cdd]

Summary: ✅


AI Review

Summary

This PR fixes the ColumnsDescription::modify path so metadata-only alters stop re-registering static subcolumns for ALIAS columns, and it adds a focused stateless regression test that covers the meaningful triggers and both alias-direction transitions. I reviewed the current code, the full PR discussion, and the touched call sites around modify, RENAME COLUMN, subcolumn lookup, and cache invalidation; I did not find an unresolved correctness issue or a missing proof gap in the current head.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 9456cdd.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9456cdd0c with master f16ef1991 (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

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

Job report

@PedroTadim PedroTadim self-assigned this Sep 22, 2026
Comment thread src/Storages/ColumnsDescription.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 22, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Sep 24, 2026
Merged via the queue into ClickHouse:master with commit 0f47f73 Sep 24, 2026
176 of 177 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 25, 2026
The branch was 14 days behind master and GitHub reported it as conflicting.

One conflict, in the `ColumnsDescription::modify` template: master's ClickHouse#121449 added an
`invalidateGetCache()` and a guard that skips `addSubcolumns` for ALIAS columns, while this
branch threads a `CancellationBudget *` into the same call. Both are kept - the guard and the
cache invalidation from master, with the budget passed to the `addSubcolumns` call that
survives the guard.

Everything else merged without conflicts. The per-table cancellation check in
`StorageMerge::getColumnsDescriptionFromSourceTablesImpl` still sits between the SHOW_TABLES
visibility filter and the SHOW_COLUMNS check, so the property from the previous round holds: a
table the user may not see behaves alike whether or not it exists. Master's new StorageAlias
target-privilege check lands after it, unchanged.

Master has no cancellation checkpoint in that function and its `forEachSubcolumn` still takes
no budget, so nothing in this branch has been superseded.
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-human PR origin: human review feedback on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ALTER TABLE ... COMMENT COLUMN on an ALIAS column makes reads of its subcolumns fail with NO_SUCH_COLUMN_IN_TABLE

3 participants