Skip to content

Let a comment command in the same ALTER see the columns MODIFY QUERY introduces - #122213

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:alter-modify-query-comment-added-column
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:alter-modify-query-comment-added-column

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121469
Related: #119469

Changelog category (leave one):

  • Improvement

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

Now a COMMENT COLUMN or MODIFY COLUMN ... COMMENT written in the same ALTER TABLE statement as a MODIFY QUERY on a materialized view can name a column the new query introduces. Previously the statement was rejected with NOT_FOUND_COLUMN_IN_BLOCK, or silently applied nothing when written with IF EXISTS, although writing the two commands as two separate ALTER statements worked.

Description

Provenance: #121469 (comment) (automated review).

A comment command in the same ALTER as a MODIFY QUERY cannot name a column the new query adds:

CREATE MATERIALIZED VIEW mv TO dst AS SELECT id FROM src;
ALTER TABLE mv (MODIFY QUERY SELECT id, id + 1 AS id2 FROM src), (COMMENT COLUMN id2 'c');
-- Code: 10. Cannot find column `id2` to comment.

Two separate ALTERs both succeed, so the end state is legitimate; with IF EXISTS the statement returns success and applies nothing.

A materialized view's columns are its query's output, so MODIFY QUERY replaces the whole set, but neither AlterCommands::validate() nor AlterCommands::prepare() has a MODIFY_QUERY case: both screen names against a pre-alter snapshot. So both stop screening once a MODIFY QUERY precedes them, and AlterCommand::apply, which walks the commands in order against the real metadata, owns the check.

An absent column is still rejected, one layer later, drawing any hint from the new query's columns. Nothing changes unless a MODIFY QUERY precedes a column-named command in the same statement, and a materialized view is the only storage that admits MODIFY QUERY. The test's negative control asserts NOT_FOUND_COLUMN_IN_BLOCK, so a regression there reds CI.

The new test reddens on the base commit; 250 randomized runs of it and four neighbours are green; per-half controls show each screen needs fixing.

Left alone: ADD COLUMN with COMMENT COLUMN IF EXISTS on a plain table; a MODIFY QUERY written last still discards a preceding comment; inner-table persistence is #119469. In a Replicated database the combination stays refused, for mixing replicated and non-replicated commands in one ALTER.

Improvement, not a bug fix: this pairing was never a supported spelling, so no release misbehaves on one.


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

groeneai and others added 2 commits September 25, 2026 10:22
…introduces

ALTER TABLE mv (MODIFY QUERY SELECT id, id + 1 AS id2 FROM src), (COMMENT COLUMN
id2 'c') on a materialized view was rejected with

  Code: 10. Wrong column name. Cannot find column `id2` to comment.
            Maybe you meant: ['id']. (NOT_FOUND_COLUMN_IN_BLOCK)

although writing the two commands as two separate ALTER statements makes both
succeed, so the requested end state was already reachable. The hint was wrong too:
it offered the pre-alter column, while id2 is exactly what the view has after the
MODIFY QUERY. Written with IF EXISTS the statement instead returned success and
applied no comment at all.

A materialized view's columns are its query's output, so MODIFY QUERY replaces the
whole set. AlterCommands::validate() advances its working snapshot for ADD, DROP and
RENAME COLUMN but has no MODIFY_QUERY case at all, and AlterCommands::prepare() keeps
a second copy of the pre-alter columns with the same gap. Because validate() runs
first (InterpreterAlterQuery.cpp:373 validate, :379 prepare, :380
checkAlterIsPossible, :381 alter), that stale screen pre-empts the sequential model in
AlterCommand::apply that would have been right, and prepare()'s stale copy marks an
IF EXISTS comment command ignore, so apply() skips it outright.

validate() cannot be made right here. Deriving a view's new columns means analysing
the query, which reads the SOURCE tables' metadata under their own short-lived locks
(Analyzer/TableNode.cpp:91-93) while the ALTER holds locks only on the view itself
(InterpreterAlterQuery.cpp:362-364), so two analyses can see two different source
schemas; and validate() is documented as the opposite kind of work, "This check is
lightweight and base only on metadata" (AlterCommands.h:246). Its one existing
analyzer use runs over a StorageDummy built from the column list, never over another
table.

So both pre-apply screens now stop screening column names once a MODIFY QUERY earlier
in the same statement has replaced the set, and AlterCommand::apply, which walks the
commands in order against an accumulating StorageInMemoryMetadata, owns the check. It
needs no second analysis and no context reconstruction, and its error draws hints from
the columns the new query really produces: for a name close enough to one of them the
message now offers the new query's column where the pre-alter snapshot could offer
nothing. The apply-side user error this relies on arrived in 711f560; before it
an absent column reached ColumnsDescription::modify and threw LOGICAL_ERROR, so the
two changes belong together, and the new test's negative control asserts
NOT_FOUND_COLUMN_IN_BLOCK to keep it that way.

The latch is on MODIFY QUERY alone. ADD COLUMN followed by COMMENT COLUMN IF EXISTS
on a plain table keeps its existing behaviour, which is a separate compatibility
question, and ADD ENUM VALUES keeps its explicit throw because merging enum values
needs the column present. The DROP and RENAME COLUMN throws are untouched:
StorageMaterializedView::checkAlterIsPossible never admits those commands, and it
rejects them before apply() either way, measured.

Non-materialized-view storages are unaffected. MergeTreeData::checkAlterIsPossible
applies the commands itself (MergeTreeData.cpp:5626) before rejecting MODIFY QUERY by
type, and the apply-side check reuses validate()'s wording, so such a statement
reports the identical error as before.

Measured on a debug build: the new test reddens on 711f560 and passes with this
change; 250 randomized runs of it and of 05237, 04046, 02931 and 03022 pass; and
reverting either half of the change alone leaves the other half's spellings broken,
so both screens needed fixing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Cut the design narration and the refuted alternative from the validate() latch comment, keeping the column-set property and the pointer to where the check now runs.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (two independent passes; 1 blocker refuted, 2 majors actioned)

Round 1 sent two wording corrections back for a fix; the code was not changed. A second cold review and a second gate pass over the corrected tree returned no findings.

# Finding Verdict
❌ Shared Catalog secondaries evaluate the following comment against the old column set, because MODIFY_QUERY returns early before replacing the columns Disagreed. That early return is in AlterCommand::apply, which this diff has no hunk in. One metadata snapshot is taken under the alter lock and validate, prepare and apply all read it: if the secondary's metadata already carries the column, base and fix both apply the comment; if it does not, base raised NOT_FOUND_COLUMN_IN_BLOCK from validate() and this change raises the same code from apply(), with IF EXISTS silently skipping either way.
⚠️ The negative control does not prove the promised hint, and absent is too far from id/id2 to produce one Agreed, fixed. NamePrompter's early return kills both candidates (6/4 = 1 and 6/3 = 2, both < 3), so that arm produces no hint at all; the mechanism is measured separately. The arm's comment and one commit-message sentence overstated it and were corrected, and the arm keeps the property it uniquely guards, that an absent name stays a user error rather than an internal one.
⚠️ The combination remains rejected in Replicated databases, and the test excludes that mode Agreed, scope stated. validateReplicatedDatabaseSegments refuses one ALTER that mixes replicated and non replicated commands, which this pairing is, so the statement is refused before validate() runs. Supporting it there is a replication-semantics change well outside this diff, so I qualified the description and recorded the reason next to the test tag.
💡 MODIFY COLUMN IF EXISTS <absent> ADD ENUM VALUES(...) after a MODIFY QUERY now reports a missing column instead of an unsupported alter Noted, not blocking. Such a command is not a comment alter, so no engine admits it beside MODIFY QUERY; it was rejected before and is rejected now, only with a different message.

Also checked and found clean: the latch's placement in both if/else chains; no use-after-skip; no lost validation, because a materialized view admits MODIFY COLUMN only as a comment-only alter; all five readers of the ignore flag; the inner-table overwrite path, where a missing column still fails on the inner table; and test liveness arm by arm, 6 of 7 reddening on the base commit.

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dca2656]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
formats_columns_sampling #10 FAIL dashboard
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
read_in_reverse_order_final #0 FAIL dashboard
read_in_reverse_order_final #1 FAIL dashboard

AI Review

Summary

This PR moves the column-existence check for COMMENT COLUMN and comment-only MODIFY COLUMN behind MODIFY QUERY, so a materialized view can comment a column that the new query introduces in the same ALTER. I did not find an actionable correctness or coverage issue in the current implementation.

Missing context / blind spots
  • ⚠️ I could not validate the CLICKHOUSE_CLOUD shared-catalog secondary-replay path from this OSS checkout. AlterCommand::apply still returns early there for MODIFY_QUERY, so confidence in that path depends on the replay machinery presenting already-updated metadata before the follow-on comment command runs.
Final Verdict

✅ No actionable findings on the current PR head.

LLVM Coverage Report

Measured on commit dca2656.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.40% -0.10%

Changed lines: Changed C/C++ lines covered: 34/35 (97.14%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A 4-statement script (two CREATE TABLE, CREATE MATERIALIZED VIEW ... TO, the paired ALTER) returns Code: 10 on every run, with no randomization involved.
b Root cause explained? Yes. MODIFY QUERY replaces a materialized view's whole column set, but neither AlterCommands::validate() nor AlterCommands::prepare() has a MODIFY_QUERY case: both screen column names against a pre-alter snapshot, before the sequential AlterCommand::apply that holds the real metadata.
c Fix matches root cause? Yes. The two impossible pre-apply screens stop at a MODIFY QUERY and defer to apply(), so the check is relocated rather than removed: an absent column is still rejected, which arm A4 and the test's negative control both assert.
d Test intent preserved / new tests added? Yes. New 05257_alter_modify_query_comment_added_column with 7 scenarios, one per guarded line plus the controls; no existing test weakened, and 05237, the nearest neighbour, still passes.
e Both directions demonstrated? Yes. The new test reddens on the base binary (return code: 10) and passes with the fix; per-half controls show validate() alone fixes the plain spellings and prepare() alone the IF EXISTS spellings, so neither half is a no-op.
f Fix is general across code paths? Yes. Both pre-apply screens are fixed, not only the reported one, and all four guarded lines have their own test arm; sibling throws are left alone because DROP/RENAME COLUMN are never admitted on a materialized view and ADD ENUM VALUES needs the column present.
g Fix generalizes across inputs? Yes. Both command spellings, both IF EXISTS states, present/absent/nonexistent names, TO-target and inner-table views, same and cross database, non-materialized-view storages, and MODIFY QUERY beside a column-less comment command are all covered.
h Backward compatible? Yes. No setting, format or on-disk change, so no SettingsChangesHistory.cpp entry; the one widening is by design, (MODIFY QUERY ...), (COMMENT COLUMN IF EXISTS <new column>) now applying the comment instead of silently returning success.
i Invariants and contracts preserved? Yes. validate()'s documented metadata-only contract is respected rather than stretched, the snapshot is never mutated, the widening in prepare() can only let through a comment command or a DROP/RENAME COLUMN that checkAlterIsPossible rejects either way (measured), and no lock, concurrency or on-disk state is touched.

Session id: cron:clickhouse-impl-slot-6:20260925-090600

@PedroTadim PedroTadim self-assigned this Sep 25, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dca265615 with master 4cafc2605 (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dca2656

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 4/6) / formats_columns_sampling #10 dashboard-verdict red: client_time 0.0325 -> 0.0387 (+19.2%), confirmed_regression. Job info 4 too long; 1 confirmed regression(s) on the performance dashboard, so the shard's own report calls this query neither slower nor unstable, and CIDB carries no failing test row for it. The fixture creates table_{format} ENGINE = File({format}) and runs the single template SELECT WatchID FROM table_{format} FORMAT Null, index #10 being the Native substitution: no MergeTree table and no ALTER anywhere in the file. This diff changes only AlterCommands::validate() and AlterCommands::prepare(), which run solely while an ALTER statement is being prepared, so the changed code is never entered. Rule 3d, measured at the tree the job actually built (dca2656 merged into master d8b1c8c2) rather than at this head: #121847 is an ancestor of that base and the verdict fired anyway, so #121847 does not own this row ClickHouse/performance-comparison#5 (external, open): the dashboard's confidence scoring, which @ fm4v named on 2026-09-23 as where these verdicts are handled after #121847. That repository is not publicly readable, so its state cannot be measured from here
Performance Comparison (arm_release, master_head, 5/6) / read_in_reverse_order_final #0 and #1 dashboard-verdict red on both queries the fixture has: client_time 0.0067 -> 0.0092 (+36.9%) and 0.0107 -> 0.0135 (+25.9%), both tier confirmed_regression. Job info 3 too long, 1 faster, 1 unstable; 2 confirmed regression(s) on the performance dashboard, and the shard's own report calls #0 merely unstable. The fixture is a ReplacingMergeTree (x UInt64, y UInt64) ORDER BY x read as SELECT x, y FROM read_in_reverse_order_final FINAL ORDER BY x DESC LIMIT 10 / 100000; it issues no ALTER either, so this diff cannot reach it. CIDB flags the fixture unstable on 23 distinct pull requests and slower on 19 over the last 7 days, master runs included, and the 5/6 shard red 256 distinct pull requests in that window ClickHouse/performance-comparison#5 (external, open), the same owner as the row above
Mergeable Check, PR rollup rows with no independent failure of their own. Mergeable Check reports Failed: 2, matching exactly the two shards above ClickHouse/performance-comparison#5 (external, open), the same owner as the rows above

All 176 check runs completed (131 pass, 41 not selected, 4 red) with the last completion at 15:38:22Z,
Finish Workflow is green, and CH Inc sync passed on this head, so no sync row is owed.
Mergeable Check and PR are commit statuses rather than check runs.

No master merge is pushed for this, and that is measured rather than a preference: the one
ClickHouse-side fix in this family, #121847, is already an ancestor of the base the jobs built, so
there is nothing to pick up, and the remaining half lives in the dashboard service, which cannot be
merged from here.

Session id: cron:our-pr-ci-monitor:20260925-160221

@PedroTadim

Copy link
Copy Markdown
Member

We don't have to implement this right now

@PedroTadim PedroTadim removed their assignment Sep 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, I won't push anything further here. Closing it is fine with me.

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-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants