Repository navigation
Conversation
`AlterCommands::prepare` precomputes each command's no-op flag for the `IF (NOT) EXISTS` variants, but it tested column presence against a snapshot taken once before the statement and never advanced it, while `AlterCommands::validate` and `AlterCommands::apply` both walk the command list sequentially. So for `ALTER TABLE t DROP COLUMN IF EXISTS x, ADD COLUMN IF NOT EXISTS x String` prepare saw `x` in the pre-statement snapshot, marked the add redundant, and apply dropped `x` and skipped the re-add: the column was silently lost, with no error and no warning. The unguarded spelling `DROP COLUMN x, ADD COLUMN x String` was always correct, so only the documented idempotent form was affected. The same asymmetry silently dropped a conditional `RENAME` or `MODIFY` of a column added earlier in the same statement. When the affected column was the table's only one the result had zero columns. The stored column list is written only when it is non-empty, so the metadata came out with no columns at all: every later `ALTER` then threw `Cannot alter table X metadata doesn't have structure`, which aborts the server in debug and sanitizer builds, and after a restart the table failed to load with `Missing definition of columns`, making its data unreachable. That exception is how this surfaced, in the AST fuzzer. Advance prepare's working snapshot for the commands that change column presence, mirroring `AlterCommand::apply` exactly and reusing `columnsAddedByAlter` so prepare, validate and apply model the same schema, including `flatten_nested` expansion and the nested `n`/`n.*` equivalence. `CLEAR COLUMN` and `IN PARTITION` keep the column, as apply does. The rejection of `MODIFY COLUMN ... ADD ENUM VALUES` on a column created in the same statement is preserved on purpose: that command merges against the type the column already has. One expectation in `01318_alter_add_column_exists` changes accordingly. A conditional rename of a nested child added by the same statement is now applied, which is what the unguarded spelling asserted already; the previous coverage of a still-ignored later command is kept by a new scenario in the same file. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings), adjudicated against
Severity: ❌ blocker / My own cold pass, for the record, plus the nits I decided not to act on:
Session id: cron:clickhouse-review-slot-8:20260901-212300 |
|
Workflow [PR], commit [dd6402e] Summary: ❌
AI ReviewSummaryThis PR fixes the stale pre- Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit dd6402e.
Changed lines: Changed C/C++ lines covered: 50/50 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260901-171800 |
|
cc @Michicosun @Algunenano, could you review this? |
| { | ||
| if (command.type == AlterCommand::ADD_COLUMN) | ||
| { | ||
| for (auto & column : columnsAddedByAlter(columns, ColumnDescription(command.column_name, command.data_type), |
There was a problem hiding this comment.
This shadow ADD only keeps name and type, but after this patch a later MODIFY COLUMN IF EXISTS can stop being ignored and start relying on the rest of the added column metadata too.
For example, ALTER TABLE t ADD COLUMN b UInt64 DEFAULT key, MODIFY COLUMN IF EXISTS b String now executes the MODIFY, but prepare never back-fills the DEFAULT from the preceding ADD, so AlterCommand::apply rewrites b into a plain String column and silently drops the default expression. The same root cause also means a same-statement ADD COLUMN ... ALIAS ..., MODIFY COLUMN IF EXISTS ... CODEC(...) no longer sees the alias-only validation that an existing column would.
If this path is going to make conditional MODIFY commands live, the working snapshot here needs the full ColumnDescription (and validate needs the same), not just the type.
There was a problem hiding this comment.
Measured on two binaries from this tree: the patch (Build ID 7986e64f...) and a same-tree mutant with only the snapshot-advance block reverted (7fbed92b...). clickhouse local, default settings.
The control that decides this is the same statement without IF EXISTS.
after CREATE TABLE t (key UInt64), (y UInt64) or (y UInt64, x UInt64 ALIAS y) |
mutant | patch |
|---|---|---|
ADD COLUMN b UInt64 DEFAULT key, MODIFY COLUMN IF EXISTS b String |
b UInt64 DEFAULT key |
b String |
ADD COLUMN b UInt64 DEFAULT key, MODIFY COLUMN b String |
b String |
b String |
ADD COLUMN x UInt64 ALIAS y, MODIFY COLUMN IF EXISTS x String |
x UInt64 ALIAS y |
x String |
ADD COLUMN x UInt64 ALIAS y, MODIFY COLUMN x String |
x String |
x String |
ADD COLUMN x UInt64 ALIAS y, MODIFY COLUMN IF EXISTS x CODEC(ZSTD) |
rc 0, codec discarded | Code: 36 ... Cannot specify codec for column type ALIAS |
ADD COLUMN x UInt64 ALIAS y, MODIFY COLUMN x CODEC(ZSTD) |
Code: 36 |
Code: 36 |
ADD COLUMN x UInt64 DEFAULT y, MODIFY COLUMN IF EXISTS x CODEC(ZSTD) |
rc 0, compression_codec empty |
CODEC(ZSTD(1)) |
MODIFY COLUMN IF EXISTS x String on the pre-existing alias |
x String ALIAS y |
x String ALIAS y |
Rows 1-4: losing the default is what MODIFY COLUMN <col> <type> has always done for a column the same statement introduced, and the patch makes the guarded spelling agree with the unguarded one. docs/reference/statements/alter/column.mdx:44 documents that a command in a chain of actions sees columns added by previous actions.
Rows 5-7 invert the codec claim: the mutant skips the guarded MODIFY and silently discards a legal codec, while the patch applies it and, for an ALIAS target, refuses the statement atomically (fresh process on the same path: table still (y UInt64), 7 rows, no x). That guard runs on the rewritten metadata, never on a shadow column: applyMetadataChangesToCreateQuery calls validateCreateQuery at DatabasesCommon.cpp:282, which re-parses the CREATE and rejects the combination inside InterpreterCreateQuery::getColumnsDescription. A name-and-type shadow cannot weaken it.
validate already advances its own snapshot with the identical ColumnDescription(column_name, command.data_type), at AlterCommands.cpp:2114 on master. This patch does not touch that line, and the new shadow mirrors it deliberately.
I am not widening the shadow to a full ColumnDescription: row 8 shows the back-fill at prepare:1999-2002 keeps the alias precisely when it sees a full description, so a full shadow would make MODIFY COLUMN IF EXISTS x String yield x String ALIAS y while MODIFY COLUMN x String still yields x String. That is the asymmetry this PR removes, mirrored.
The default reset itself is if (default_expression || data_type) in apply at AlterCommands.cpp:825. It is pre-existing, identical for the unguarded spelling, and fixed at its source in #114807, which also deletes the prepare:1999-2002 back-fill, after which nothing in prepare reads a shadow column's default_desc.
| { | ||
| if (command.type == AlterCommand::ADD_COLUMN) | ||
| { | ||
| for (auto & column : columnsAddedByAlter(columns, ColumnDescription(command.column_name, command.data_type), |
There was a problem hiding this comment.
Advancing the working snapshot with only ColumnDescription(command.column_name, command.data_type) is enough for existence checks, but not for the new MODIFY COLUMN IF EXISTS path. prepare later relies on the shadow column's default_desc at 1999-2002, and validate relies on the shadow column kind for checks like all_columns.hasAlias() / getDefault().
A concrete regression is:
ALTER TABLE t
ADD COLUMN x UInt64 ALIAS y,
MODIFY COLUMN IF EXISTS x String;After this patch the guarded MODIFY no longer gets ignored, but the shadow ADD still forgets that x is an ALIAS, so apply resets default_desc at 825-828 and silently turns the just-added alias into a stored String column. The same gap drops DEFAULT expressions, and ... MODIFY COLUMN IF EXISTS x CODEC(...) can now miss the Cannot specify codec for column type ALIAS guard for a just-added alias.
The shadow ADD COLUMN needs to carry the full column definition that the command introduces (at least the default kind/expression, and validate needs the same shape), not just the name and type.
There was a problem hiding this comment.
Same finding as the sibling comment on this line; answered with the measurement matrix at #117593 (comment). Short form: the patched guarded spelling is byte-identical to the unguarded spelling in all three cases, validate already uses the same name-and-type shadow at AlterCommands.cpp:2114, the codec guard fires with the patch and is missed without it, and the default reset at AlterCommands.cpp:825 is fixed at its source in #114807, which deletes the prepare:1999-2002 back-fill this asks me to feed.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units147 translation units recompiled, 1453 s compile time in total, 147 of them have a recent master baseline. |
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) |
the job's log scanner flags an error that a stateless test asserts on purpose: all 357 lines of upgrade_error_messages.txt carry one signature, Code: 16 ... Unexpected const virtual column: _table: While executing MergeTreeSequentialSource from MutatePlainMergeTreeTask retrying part all_1_1_0_2 of test_1.t_mut_local |
#117218 (mine, open) |
The attribution is complete rather than sampled: reducing upgrade_error_messages.txt to its distinct signature set gives exactly one entry, and the count of lines carrying anything else is 0. t_mut_local is created by exactly one file in the tree, tests/queries/0_stateless/04510_mutation_query_plan_only_virtual_columns.sql, whose DELETE WHERE _table != '' mutation is asserted to fail because _table cannot be materialized in a mutation. #117218 adds that message to the upgrade_runner.sh allowlist. I measured the entry ABSENT from this tree (0 occurrences at dd6402e50c30) against 1 at #117218's head 16058d92c542, with master at 0 as the negative control.
The row is not specific to this pull request: the signature has 45 recorded failures across 45 distinct pull requests since 2026-08-30 22:48Z, every one of them on Upgrade check (amd_release), and 0 on master. This PR changes src/Storages/AlterCommands.{cpp,h}, src/Interpreters/InterpreterAlterQuery.cpp and 01318_alter_add_column_exists, none of which is on the mutation read path that raises the message.
Attempt order is applied rather than assumed: the check ran twice at this head, 01:46:01 success then 02:01:25 failure, so the newest attempt is the red one and the row is owed instead of retried to green. Two concurrent PR workflow runs exist at this head and they disagree on this one job, but the CIDB row and the leaf artifact (Failures: 1/12) both carry the failure, so the disagreement does not discharge it.
No master merge is owed here, because #117218 is open and there is nothing merged to pick up.
Mergeable Check reports Failed: Upgrade check (amd_release), so this row is gating. The table above is the complete non-OK, non-SKIPPED node set of result_pr.json at this head (150 OK, 19 SKIPPED, 1 FAIL). CH Inc sync was success here, so no exempt row was owed.
Session id: cron:our-pr-ci-monitor:20260902-040000
|
|
||
|
|
||
| void AlterCommands::prepare(const StorageInMemoryMetadata & metadata, bool share_nested_offsets) | ||
| void AlterCommands::prepare(const StorageInMemoryMetadata & metadata, ContextPtr context, bool share_nested_offsets) |
There was a problem hiding this comment.
@groeneai can we just refuse to add the column back if it is dropped, modified or renamed in the same alter?
There was a problem hiding this comment.
Yes, and I will implement it if you prefer it, but the two readings of "refuse" have very different prices, so tell me which one you mean.
Refuse every spelling. The unguarded form is correct on master today, and five statements in three tests pin it: 01281_alter_rename_and_other_renames.sql:19,53 (RENAME COLUMN value2 TO value2_old, ADD COLUMN value2 Int64 DEFAULT 7), 03748_default_minmax_indices_alter.sql:64, and 04872_read_renamed_then_dropped_and_readded_column.sh:54,79, whose entire subject is RENAME a TO b, DROP b, ADD b in one ALTER. docs/reference/statements/alter/column.mdx:44 also states that an action can reference a column added by a previous action. So that reading is a backward-incompatible change plus three test rewrites.
Refuse only the IF-guarded spelling, the one this PR changes. No test on master exercises it (this PR adds the first two, at 01318_alter_add_column_exists.sql:257,274, and they would flip to expecting the error), and it closes the reported failure because the statement no longer runs. It is a small check in AlterCommands::validate, which already walks the commands with a running all_columns. Two consequences to price: IF NOT EXISTS becomes stricter than the plain spelling rather than only suppressing an error, and the reverse order stays as it is. ALTER TABLE t ADD COLUMN b UInt64, MODIFY COLUMN IF EXISTS b String yields b UInt64 on master and b String with this patch, measured on this tree, because the same precomputed no-op flag also skips a MODIFY, DROP or RENAME that follows an ADD of the same column.
Which one do you want?
There was a problem hiding this comment.
Either one can introduce a backward-incompatible change, so let's keep it as it is.
There was a problem hiding this comment.
Keeping it as it is; I am not adding the refusal check, so the diff stays as published.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
ALTER TABLE ... DROP COLUMN IF EXISTS c, ADD COLUMN IF NOT EXISTS c <type>silently losingc: the column was dropped and never re-added. Inside a singleALTER,IF EXISTSandIF NOT EXISTSare now evaluated against the columns the preceding commands of the same statement produce. When the affected column was the table's only one, the table was left with no columns at all, which made every laterALTERfail withCannot alter table ... metadata doesn't have structureand made the table impossible to load after a restart.Description
AlterCommands::preparedecides which commands are no-ops for theIF (NOT) EXISTSspellings, but it tested column presence against a snapshot taken once before the statement and never advanced it, whileAlterCommands::validateandAlterCommands::applyboth walk the command list sequentially. So forDROP COLUMN IF EXISTS x, ADD COLUMN IF NOT EXISTS x Stringprepare sawxin the pre-statement snapshot, marked the add redundant, and apply droppedxand skipped the re-add. The unguarded spellingDROP COLUMN x, ADD COLUMN x Stringwas always correct; only the documented idempotent form was affected. Measured on master with 500 rows in the table: the column disappears, return code 0, no warning.If
xwas the only column the result had zero columns, and the column list is written only when it is non-empty, so the stored metadata came out asATTACH TABLE _ UUID '...' ENGINE = MergeTree ORDER BY tuple(). Every laterALTERthen threwLOGICAL_ERROR: Cannot alter table X metadata doesn't have structure, which aborts the server in debug and sanitizer builds, and after a restart the table failed to load withEMPTY_LIST_OF_COLUMNS_PASSED: Missing definition of columns, making its data unreachable. That logical error is how this surfaced, inAST fuzzer (amd_debug, targeted): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117320&sha=c2bbd70230105a47c417f6118a2f2d38d56d79e6&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29The fix advances prepare's working snapshot for the commands that change column presence, mirroring
AlterCommand::applyexactly and reusingcolumnsAddedByAlterso all three passes model the same schema. The rejection ofMODIFY COLUMN ... ADD ENUM VALUESon a column created in the same statement is preserved deliberately. I did not guard the site that throws, because that would leave the silent column loss unfixed. A table already persisted with zero columns stays unloadable.No related open issue found.
Workflow [PR]
Sync PR [sync-upstream/pr/117593]