Repository navigation
Fix ALTER TABLE ... COMMENT COLUMN being silently discarded on a materialized view with an inner table - #119469
Conversation
ALTER TABLE <mv> COMMENT COLUMN <col> '...' and the comment-only spelling ALTER TABLE <mv> MODIFY COLUMN <col> COMMENT '...' returned success and stored nothing on a materialized view with an inner table, so system.columns and SHOW CREATE TABLE kept reporting the old comment and there was no supported way to change it after CREATE. checkAlterIsPossible whitelists command.isCommentAlter(), so the command is accepted, and params.apply writes the new comment into new_metadata.columns. Then, under `if (has_inner_table)`, alter assigns `new_metadata.columns = target_table_metadata->columns`, replacing the whole ColumnsDescription with the inner table's and discarding every column-level result of params.apply. The gate and the body disagreed about which commands the view honours, and the body won silently. That assignment is deliberate: it re-syncs the column types from the inner table after checkTargetTableHasQueryOutputColumns, which MODIFY QUERY depends on because its apply rebuilds columns from the query sample. Deleting it would regress the type re-sync, so it stays and a column comment is instead treated as the view's own property. That is already how a TO-target view behaves, since the assignment sits inside the has_inner_table branch, so this makes the two shapes agree rather than introducing a third rule. StorageView::alter gates on the same predicate and has no overwrite, which is why a plain VIEW was already correct. The view's comments are carried across the copy from the pre-apply metadata, not the post-apply metadata: after a MODIFY QUERY the post-apply comments are all empty, so sourcing them there would wipe the inner table's comments. The second loop then applies this statement's comment commands, which the carry-over would otherwise overwrite with the column's pre-ALTER comment. Both steps are needed: without the carry-over, any other accepted alter reverts a comment set earlier, because params.apply leaves columns untouched for COMMENT_TABLE, MODIFY_SQL_SECURITY and MODIFY_REFRESH while the copy still runs. That was measured: with the second loop alone, ALTER TABLE mv MODIFY COMMENT reverts the column comment to the inner table's. One behaviour change follows deliberately. Because the view's comments now win, a comment set by altering the hidden inner table directly no longer appears on the view after the view's next ALTER. That pickup was an undocumented side effect of the type re-sync and is unnecessary now that the supported path works. The !command.ignore guard mirrors the plural AlterCommands::apply so IF EXISTS no-ops stay no-ops, and the has() guard skips a column the inner table does not have, whose absence would otherwise throw from ColumnsDescription::modify. The new test asserts all four properties and fails on master on three of them. Its fourth row, that MODIFY COMMENT does not revert the column comment, is what separates a comment that sticks from one that sticks only until the next ALTER. Related: ClickHouse#11075
Internal second-model review: adjudication log (click to expand)Pre-publication review in two independent parts: a cold review by an independent model
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20260911-132600 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260911-120500 |
|
Workflow [PR], commit [957852a] Summary: ✅
AI ReviewSummaryThis PR correctly fixes Missing context / blind spots
Findings
Final VerdictChanges requested: the inner-table comment fix itself looks correct, but the current head still leaves LLVM Coverage ReportMeasured on commit 957852a.
Changed lines: Changed C/C++ lines covered: 20/20 (100.00%) · Uncovered code |
|
cc @evillique @CheSema, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes3 object files changed (+38.38 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 15 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 2965a0fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The 169 Session id: cron:our-pr-ci-monitor:20260911-203047 |
|
🕵️ Could we restore comments without rebuilding subcolumns? This loop calls The helper behavior is pre-existing, but invoking it for every column on every accepted MV ALTER introduces a new path to it. Please use a comment-only update that preserves subcolumn registration and add a regression with a compound I haven’t reproduced a downstream query failure, but the metadata side effect should be avoided. |
ColumnsDescription::modify() re-derives a column's subcolumns from its type,
while ColumnsDescription::add() deliberately skips that for an ALIAS column,
because an alias has no real subcolumns of its own: they are extracted from the
alias expression after it is evaluated. Restoring the comments through modify()
therefore registered subcolumns for every ALIAS column of the view on every
accepted ALTER, and that registration is observable. With an ALIAS column
`arr Array(UInt64)`, the analyzer finds `arr.size0` in the table expression's
column list and resolves it to a plain column, so the plan asks the inner table
for `arr.size0`, which it does not have:
ALTER TABLE mv MODIFY COMMENT 'x';
SELECT arr.size0 FROM mv;
-- Code: 10. Column `arr.size0` not found in table default.`.inner_id...`
ColumnsDescription::setComment writes the comment field and leaves the registered
subcolumns as they are, which is all this site needs. The second loop uses it as
well, instead of AlterCommand::apply, whose COMMENT_COLUMN branch goes through
modify() too; for a comment alter that call had no other effect. Which comments
are written, and in which order, is unchanged.
The test gains three rows, one per reachable path: the alias subcolumn read after
an unrelated table comment, the comment stored on the alias column itself, and
that read again after the column comment. The first fails on the previous commit
of this pull request with Code 10, and the third fails if the second loop keeps
calling AlterCommand::apply. Both reads pass on master, where no carry-over loop
exists yet; the stored comment does not, because that is the bug this pull
request fixes. The test is tagged no-old-analyzer, like the existing
04738_merge_subcolumn_of_alias_parent, because the old analyzer never resolves a
subcolumn of an ALIAS parent.
Requested in review of this pull request.
Related: ClickHouse#11075
|
Done in 6105bf7. The restore no longer goes through The side effect turned out to be reachable from a query, not only in the metadata. With an ALTER TABLE mv MODIFY COMMENT 'x';
SELECT arr.size0 FROM mv;
-- Code: 10. Column `arr.size0` not found in table default.`.inner_id...`. (NOT_FOUND_COLUMN_IN_BLOCK)Master returns the value, so that was a regression this pull request would have introduced. The test gains three rows: the read after an unrelated table comment (red on the previous commit), the comment stored on the alias column, and the same read after
|
| checkTargetTableHasQueryOutputColumns(target_table_metadata->columns, select_query_output_columns); | ||
| /// We need to copy the target table's columns (after checkTargetTableHasQueryOutputColumns() they can be still different - e.g. the data types of those columns can differ). | ||
| new_metadata.columns = target_table_metadata->columns; | ||
| /// A column comment belongs to the view, not to its inner table, and the copy above replaces |
There was a problem hiding this comment.
MODIFY QUERY is also allowed on MATERIALIZED VIEW ... TO ..., but this replay only runs under has_inner_table. On the TO path, AlterCommand::apply(MODIFY_QUERY) rebuilds new_metadata.columns from the query sample and drops every existing column comment, so ALTER TABLE mv MODIFY QUERY ... still loses view-owned comments for one of the two supported MV shapes.
That leaves the invariant in the new comment only half-implemented, and it also contradicts the PR description's claim that the TO shape already behaves this way. Please either run the same restore/reapply logic for !has_inner_table when MODIFY QUERY is present, or add an explicit test-backed restriction if comment preservation is intentionally unsupported there.
There was a problem hiding this comment.
Confirmed and fixed in f557f16.
Measured before changing anything: on master a TO-target view with a declared column comment loses
it on MODIFY QUERY, and reverting my new hunk reproduces the previous head bit-for-bit (build id
96d286db0a25e896) with the same loss, so that half predates this PR. It is durable rather than
in-memory only, since the regenerated CREATE query came back with the COMMENT clause gone. Same
defect class and same function as what this PR already fixes, so I did not split it out.
Instead of a second copy of the restore for !has_inner_table, I moved the existing one below the
branch, so the same six lines now cover both shapes. MODIFY QUERY reaches no other storage
(MergeTreeData and StorageView both throw NOT_IMPLEMENTED), so those two shapes are the whole
population of the command.
The new assertion reads the comment back after DETACH plus ATTACH, so the stored CREATE query
has to carry it too, not just the in-memory metadata. It is the only one of eight that fails on the
previous head; master fails five of the eight. 50/50 with randomized settings is green, as are the 26
stateless tests that mention MODIFY QUERY.
The description wording was ambiguous and I have corrected it: "already how a TO-target view
behaves" held for CREATE and COMMENT COLUMN but not across MODIFY QUERY, which the description
now states explicitly.
There was a problem hiding this comment.
This is still present on the current head.
AlterCommand::apply(MODIFY_QUERY) still replaces metadata.columns with ColumnsDescription(as_select_sample->getNamesAndTypesList()) at src/Storages/AlterCommands.cpp:1261-1275, and the !has_inner_table path in StorageMaterializedView::alter still has no restore step before the final alterTable commit (src/Storages/StorageMaterializedView.cpp:975-980).
So a MATERIALIZED VIEW ... TO ... still loses its declared column comment across ALTER TABLE ... MODIFY QUERY ...; the earlier f557f16 fix no longer holds on the current head.
The restore that keeps a view-owned column comment across an accepted ALTER ran only under has_inner_table, so it covered the inner-table copy but not the other writer of new_metadata.columns: AlterCommand::apply(MODIFY_QUERY) rebuilds them from the query's sample block, which carries names and types only. On a TO-target view that dropped every column comment silently and durably, the regenerated CREATE query losing its COMMENT clause with it. MODIFY QUERY is accepted only by StorageMaterializedView (MergeTree and View both throw NOT_IMPLEMENTED), so the two view shapes are the whole population of that command, and moving the restore below the branch covers both with no new code. The new assertion reads the comment back after DETACH plus ATTACH, so it fails unless the stored CREATE query carries it too, not only the in-memory metadata. Measured: reverting this hunk reproduces the previous head bit-for-bit (build id 96d286db0a25e896) and the new assertion is the only one of the eight that fails, while master fails five of them, so the TO-target half of the defect predates this pull request. Co-Authored-By: Claude Opus 5 <[email protected]>
| /// A column comment belongs to the view, not to its inner table and not to its query's sample | ||
| /// block, while the copy above and MODIFY QUERY both replace the view's column descriptions | ||
| /// wholesale. Restore the view's comments, then apply the ones this ALTER sets. | ||
| for (const auto & column : view_metadata->columns) |
There was a problem hiding this comment.
MODIFY QUERY still drops supported view-owned column properties on MATERIALIZED VIEW ... TO ... because this replay only restores comment. AlterCommand::apply(MODIFY_QUERY) first rebuilds metadata.columns from as_select_sample->getNamesAndTypesList() (src/Storages/AlterCommands.cpp:1211), so every explicit column attribute that is not carried by the query sample is already gone at this point.
That matters for supported TO-target definitions such as x String DEFAULT _table / x String MATERIALIZED _table in tests/queries/0_stateless/04630_default_over_virtual_column.sql:88-97: after ALTER TABLE mv MODIFY QUERY ..., SHOW CREATE TABLE and the stored metadata will silently lose those column declarations even though the view accepted them at CREATE time. This patch fixes the comment field for that overwrite, but it leaves the same overwrite bug live for the rest of ColumnDescription.
Please either preserve the full surviving ColumnDescription for TO-target views across MODIFY QUERY, or add a focused restriction if those explicit column properties are intentionally unsupported there.
There was a problem hiding this comment.
I measured this before deciding, and I am not widening the patch. Two arms of clickhouse local, build ids asserted: master B91CD3D7F79DACDC, this head EE395521330F9C1A.
The mechanism is right, and it predates this PR. On a TO-target view declaring x String DEFAULT _table COMMENT 'cx' CODEC(ZSTD(1)), with a MODIFY QUERY whose sample still produces x:
default_kind |
compression_codec |
comment |
|
|---|---|---|---|
| both arms, before | DEFAULT |
CODEC(ZSTD(1)) |
cx |
master, after MODIFY QUERY |
empty | empty | empty |
this head, after MODIFY QUERY |
empty | empty | cx |
The whole arm-to-arm diff is the comment column, so this patch neither introduced nor widened the loss of the rest.
Preserving the full surviving ColumnDescription is not a mechanical extension of the comment restore. MODIFY QUERY is the one command that changes the output types and the column set, and the other attributes are type- or column-dependent, so carrying them across that change produces metadata the server rejects:
x UInt32 CODEC(Delta, ZSTD), then aMODIFY QUERYmakingxaString: master drops the codec and theALTERsucceeds. Re-attaching it givesCode: 36 ... Codec Delta is not applicable for String because the data type is not of fixed size.DEFAULT/MATERIALIZEDexpressions are over the view's own columns, whichMODIFY QUERYcan remove:Code: 47 ... Unknown expression or function identifier 'y' ... default expression and column type are incompatible.- A
DEFAULTliteral that no longer converts to the new type:Code: 6 ... Cannot parse string 'not_a_number' as UInt32 ... default expression and column type are incompatible.
So a blind carry-over turns MODIFY QUERY statements that succeed today into hard errors. A comment is the only column attribute that is both type-independent and column-independent, which is why it is the one this restore carries; that is the line, not an arbitrary subset.
The restriction alternative would reject DDL that is valid today. tests/queries/0_stateless/04630_default_over_virtual_column.sql:88-97 on master asserts that a TO-target view accepts exactly those DEFAULT and MATERIALIZED declarations at CREATE, and documents that it never evaluates them.
One edge worth recording, since it is invisible in the columns above: an ALIAS column is dropped by the same rebuild, so SELECT dbl FROM mv gives Code: 47 Unknown expression identifier 'dbl' after an unrelated MODIFY QUERY. That reproduces identically on master and on this head, so it is pre-existing and I am leaving it outside a PR whose review constraint is the shortest possible code and test.
The restore loop above puts the view's pre-ALTER comments back after the inner-table
copy and MODIFY QUERY replace its column descriptions wholesale. The loop below then
re-applied only the comments of `isCommentAlter()` commands, so a comment arriving on
any other command was restored away again:
`ADD COLUMN id UInt64 COMMENT 'changed'` -> the view keeps COMMENT 'initial'
`isCommentAlter()` is false for `ADD COLUMN`, and false for a `MODIFY COLUMN` that
also restates the type, since it requires `data_type == nullptr`. Keying on
`command.comment` instead covers every shape. `COMMENT TABLE` and
`MODIFY DATABASE COMMENT` also carry a comment but have an empty `column_name`, so
the `columns.has()` guard keeps them no-ops as before.
No public ALTER reaches this: `checkAlterIsPossible` rejects everything except
`MODIFY SQL SECURITY`, comment alters, `MODIFY QUERY` and `MODIFY REFRESH`. The
SharedCatalog replay in the private repo is what synthesizes the `DROP COLUMN` plus
`ADD COLUMN ... COMMENT` pair, and it aborted verifying the replayed CREATE query:
Logical error: 'In-place ALTER failed, resulting CREATE query is different from
the expected query, resulting: ... `id` UInt64 COMMENT 'initial' ...,
expected: ... `id` UInt64 COMMENT 'changed' ...'
That abort killed the catalog thread on the replica, which then went inactive and
timed out every later distributed DDL. Coverage stays on that side, since the
triggering ALTER cannot be issued here.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
@evillique can you give a quick review for this PR? It's small |
| DROP TABLE IF EXISTS mv_comment_inner; | ||
|
|
||
| CREATE TABLE mv_comment_src (id UInt64) ENGINE = MergeTree ORDER BY id; | ||
| CREATE MATERIALIZED VIEW mv_comment_inner (id UInt64 COMMENT 'initial') |
There was a problem hiding this comment.
@groeneai can you also test with regular views and refreshable materialized views?
There was a problem hiding this comment.
Done in 68474aa.
Regular views: never affected. A plain view has no inner table, so nothing overwrites its column
descriptions. Measured on master at 688ee33 (no fix): the comment reads back changed and survives
DETACH/ATTACH there too, so I added it as one control row (plain view changed) in the existing test
rather than as a second defect.
Refreshable views: same failure, and the new test reproduces it. A refreshable view does own an inner
table, so StorageMaterializedView::alter overwrites the comment exactly as in the non-refreshable
case. On that same master binary the comment reads back initial after the ALTER returned Ok., and
changed with the fix.
That case is a separate file, 05182_materialized_view_alter_column_comment_refreshable.sql, because
it only exists on an Atomic database:
- Ordinary:
Code: 80 ... Refreshable materialized views (except with APPEND) only support Atomic and Replicated database engines - Replicated:
Code: 36 ... refreshable materialized view, no APPEND, replicated database, non-replicated table ... Refusing to create
so it needs no-ordinary-database, no-replicated-database, and tagging the existing file instead
would have dropped the inner-table coverage from those two flavours. Happy to fold it into one tagged
file if you prefer that.
EMPTY plus SYSTEM REFRESH VIEW / SYSTEM WAIT VIEW make that refresh the only one, and the
asserted row count proves it ran, so the comment is read back after the refresh has really replaced
the inner table. 20/20 for both tests with randomized settings. No source change in this round.
Requested in review on ClickHouse#119469. A plain view has no inner table, so nothing overwrites its column descriptions and ALTER TABLE ... COMMENT COLUMN already stored the comment. Measured on master (3f1717357e2d), the new row reads back 'changed' before this fix too, so it is a control row that keeps the fix honest, not a second defect. A refreshable view does own an inner table, and hit exactly the same failure: on that same master binary the comment reads back 'initial' after the ALTER reported success. Its row lives in a separate file because the case only exists on an Atomic database: Code: 80 ... Refreshable materialized views (except with APPEND) only support Atomic and Replicated database engines, but database odb has engine Ordinary Code: 36 ... refreshable materialized view, no APPEND, replicated database, non-replicated table ... Refusing to create Tagging the existing file instead would have dropped the inner-table coverage from those two CI flavours. EMPTY plus SYSTEM REFRESH VIEW and SYSTEM WAIT VIEW make the refresh the only one, and the asserted row count proves it ran, so the comment is read back after the inner table has really been recreated. 20/20 for both tests with randomized settings. Co-Authored-By: Claude Opus 5 <[email protected]>
| WHERE database = currentDatabase() AND table = 'mv_comment_inner' AND name = 'id'; | ||
|
|
||
| -- A regular view has no inner table, so nothing replaces its column descriptions. | ||
| CREATE VIEW mv_comment_view (id UInt64 COMMENT 'initial') AS SELECT id FROM mv_comment_src; |
There was a problem hiding this comment.
@groeneai materialized views with TO clause are fine?
There was a problem hiding this comment.
Yes. A view with a TO clause has no inner table, so has_inner_table is false and the forward this PR adds never runs for it: params.apply writes the comment into the view's own ColumnsDescription and nothing overwrites it, as for a regular view.
Measured on 9c11e7a9d32d5 and on a base master build, identical on both, so this shape was never broken. After ALTER TABLE mv_to COMMENT COLUMN id 'changed' the view reads changed and the explicit target keeps its own target; after a comment-only MODIFY COLUMN plus DETACH/ATTACH the view reads changed again and SHOW CREATE carries it. Same with and without an explicit column list on the view.
Added as an arm to 05182_materialized_view_alter_column_comment in f6fe932 (view with TO / TO target). It is a boundary control rather than a fix assertion: it reddens if the forward ever starts firing for a view with no inner table, or if it touches the explicit target. Dropping the view's ALTER empties the first row and a comment alter on the target reddens the second, so neither line can pass vacuously. Green 100/100 randomized runs and 25/25 under --replicated-database.
One adjacent gap is unchanged and out of scope here: ALTER TABLE <mv> MODIFY QUERY still drops column comments on a TO-target view. That is the separate follow-up noted in the description.
A view created with TO <target> has no inner table, so the column-comment forwarding added here must not fire for it: the comment is stored on the view itself, and the explicit target is a table of its own that keeps the comment it was created with. That is the boundary of the new "if (has_inner_table)" branch, and it was the one materialized-view shape the test did not exercise. Measured identical on master and on this branch, so the arm pins behaviour rather than asserting a change. Negative controls: dropping the view's ALTER empties the first assertion, and a comment alter on the target reddens the second, so neither line can pass vacuously.
CI finish ledger - f6fe932Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link
Worth flagging for reviewers of the matCTE family: merged #121010 is present in the tree that Session id: cron:our-pr-ci-monitor:20260922-133206 |
|
Fixing PR for the |
|
@evillique can you give one more round of review? |
…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]>
| /// and commits it at the first metadata change made from the query context itself, which has | ||
| /// to be this view's own commit below, so both changes land in that one transaction. | ||
| auto target_alter_context = Context::createCopy(local_context); | ||
| /// `IStorage::alter` takes a null guard when the caller already holds one, and the caller holds this view's. |
There was a problem hiding this comment.
This is not correct, it is because of lock inversion.
There was a problem hiding this comment.
You are right, and it was the comment, not the code. The guard held above this frame is on the view's name, never on the inner table's, so "the caller already holds one" was simply false. The real constraint is the acquisition order: runCommandSegments takes the DDLGuard before the share and alter locks, in the same order RENAME/EXCHANGE/DROP take them, and StorageTimeSeries::dropInnerTableIfAny requests an inner table's guard only when the outer name sorts first for the same reason. Both alter locks are already held by the time this line runs, so acquiring the inner table's guard here would invert that order. Rewritten as that invariant in 7de2b63.
Verifying it turned up one real defect in the forward, fixed in 6902464: a comment command that IF EXISTS turns into a no-op (prepare() marks it ignored, apply() skips it) was still forwarded, so the inner engine's own alter ran for a statement that applies nothing. With Buffer as the inner engine that moves data, since StorageBuffer::alter flushes on every alter. One buffered row, ALTER TABLE mv COMMENT COLUMN IF EXISTS no_such_column 'ignored': 1 row in the destination table before the fix, 0 after, 0 on master. The new arm asserts the destination stays empty, and a real comment alter still reads back from the inner table in the same run.
#121449 merged yesterday, so #121469 is the only remaining merge dependency.
The comment claimed `IStorage::alter` takes a null guard when the caller already holds one, and that the caller holds this view's. The second half is true, the inference from it is not: the guard held above this frame is on the view's name, never on the inner table's, so an empty guard here is not a case of the guard already being held for the table being altered. The real constraint is the acquisition order. `runCommandSegments` takes the DDLGuard before the share and alter locks, the same order RENAME, EXCHANGE and DROP take them, and `StorageTimeSeries::dropInnerTableIfAny` requests an inner table's guard only when the outer name sorts first, for the same reason. By the time this frame runs, the view's guard and alter lock are held and the inner table's alter lock has just been taken, so acquiring the inner table's guard here would invert that order. `StorageMergeTree::alter` and `StorageReplicatedMergeTree::alter` both read an empty guard as nothing to release, so passing one is what keeps the order intact. Comment only, no behaviour change.
`AlterCommands::prepare` marks `COMMENT COLUMN IF EXISTS` and comment-only `MODIFY COLUMN IF EXISTS` on a missing column as ignored, and `AlterCommands::apply` then skips them, so the view applies nothing. The forward to the inner table kept them, took the inner table's alter lock and ran the inner engine's own `alter`, whose side effects are not the comment. With `Buffer` as the inner engine that moves user data, because `StorageBuffer::alter` flushes its rows into the destination table on every alter. Measured on this tree with one row buffered and `ALTER TABLE mv COMMENT COLUMN IF EXISTS no_such_column 'ignored'`: destination rows, before this commit: 1 destination rows, after this commit: 0 destination rows on master: 0 A real comment alter still reaches the inner table: the positive control in the same run reads the new comment back from the inner table afterwards. The regression test asserts the destination stays empty, which is what distinguishes a skipped forward from a performed one.
CI finish ledger - 6902464Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
All 173 check runs completed (133 pass, 39 not selected, 1 red), Master merge deliberately not pushed now, and the reason is measured rather than a preference. Session id: cron:our-pr-ci-monitor:20260925-080056 |
|
@groeneai @evillique @PedroTadim — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md. Changelog-revert: 122679 122485 Revert "Remove low-value integration tests" Changelog-revert: 122902 119469 Revert "Fix ALTER TABLE ... COMMENT COLUMN being silently discarded on a materialized view with an inner table" Changelog-deleted-entry: 119469 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed `ALTER TABLE <mv> COMMENT COLUMN <col> '...'` and comment-only `ALTER TABLE <mv> MODIFY COLUMN <col> COMMENT '...'` returning success and storing nothing on a materialized view with an inner table, which left no supported way to change a column comment on such a view after `CREATE`. [#119469](#119469) ([Groene AI](https://github.com/groeneai)).
…rialized view with an inner table Re-lands #119469, reverted by #122902 for breaking the private `Stress test (amd_tsan, SharedCatalog, meta in keeper)`. That failure came from the copy of the inner table's columns over the view's, which overwrote comments the statement had just set. SharedCatalog replays a comment change as DROP COLUMN plus ADD COLUMN ... COMMENT, which is no comment alter and so never reaches the inner table, and a MODIFY QUERY after a COMMENT COLUMN rebuilds the view's columns without it. The comments a statement sets are now taken from its commands and applied over the copied columns; every other column keeps the inner table's comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #11075
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
ALTER TABLE <mv> COMMENT COLUMN <col> '...'and comment-onlyALTER TABLE <mv> MODIFY COLUMN <col> COMMENT '...'returning success and storing nothing on a materialized view with an inner table, which left no supported way to change a column comment on such a view afterCREATE.Description
In 26.8,
ALTER TABLE <mv> COMMENT COLUMN id 'changed'on a materialized view with an inner tablereturns
Ok.whilesystem.columnsandSHOW CREATE TABLEkeep the old comment, so there is nosupported way to change it after
CREATE. Measured on master, and unchanged since 26.3.checkAlterIsPossiblewhitelistscommand.isCommentAlter(), so the command is accepted andparams.applywrites the comment intonew_metadata.columns. For an inner table,alterthenreplaces the whole
ColumnsDescriptionwith that table's(
new_metadata.columns = target_table_metadata->columns;), discarding it.The inner table already owns the comments given at
CREATE, so this forwards the column-commentcommands to it and lets that existing copy carry them back, instead of making the view a second owner. The view's own table comment is not forwarded, and the forward runs after
checkTargetTableHasQueryOutputColumnsbecause it commits separately from the view. A commandIF EXISTSturned into a no-op is not forwarded either, so aBufferinner table does not flush on it.Merges after #121469. The forward makes the pre-existing
ColumnsDescription::modify()ALIAS-subcolumn defect (#121421, reproduces on a plainMergeTreetable) newly reachable throughALTER TABLE <mv> COMMENT COLUMN, where the discarded no-op used to mask it, soSELECT arr.size0 FROM mvfails withNO_SUCH_COLUMN_IN_TABLE. #121449 removed it at the root and merged on 2026-09-24.Not addressed here, both pre-existing on master:
MODIFY QUERYdropping column comments on aTO-target view, and a comment command afterMODIFY QUERYnaming a column the new query drops,which raises a
LOGICAL_ERROR. #121469 fixes the second and carries its regression arm.The four materialized-view assertions read
initialon master and the new value with the fix; theregular-view and
TO-clause rows are controls with no inner table.Related:notCloses:for #11075: it asks for propagation to all replicas, which this does not do.Reproducer
Workflow [PR]
Sync PR [sync-upstream/pr/119469]
Version info
26.10.1.973-master(included in26.10and later)