Skip to content

Fix a column silently lost by a combined DROP COLUMN IF EXISTS and ADD COLUMN IF NOT EXISTS - #117593

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-alter-if-exists-sequential-snapshot
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-alter-if-exists-sequential-snapshot

Conversation

@groeneai

@groeneai groeneai commented Sep 1, 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 ... DROP COLUMN IF EXISTS c, ADD COLUMN IF NOT EXISTS c <type> silently losing c: the column was dropped and never re-added. Inside a single ALTER, IF EXISTS and IF NOT EXISTS are 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 later ALTER fail with Cannot alter table ... metadata doesn't have structure and made the table impossible to load after a restart.

Description

AlterCommands::prepare decides which commands are no-ops for the IF (NOT) EXISTS spellings, 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 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 unguarded spelling DROP COLUMN x, ADD COLUMN x String was 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 x was 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 as ATTACH TABLE _ UUID '...' ENGINE = MergeTree ORDER BY tuple(). Every later ALTER then threw LOGICAL_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 with EMPTY_LIST_OF_COLUMNS_PASSED: Missing definition of columns, making its data unreachable. That logical error is how this surfaced, in AST 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%29

The fix advances prepare's working snapshot for the commands that change column presence, mirroring AlterCommand::apply exactly and reusing columnsAddedByAlter so all three passes model the same schema. The rejection of MODIFY COLUMN ... ADD ENUM VALUES on 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]

`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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

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

Pre-publication review by an independent model (engine: codex; 3 findings), adjudicated against
the recorded evidence. I reviewed the same diff cold myself first, before reading either the gate
output or my own validation notes; that pass found no blocker and no major, and its nits are listed
under the table.

# Sev Finding Verdict Evidence / action
1 ❌ DROP COLUMN IF EXISTS n, ADD COLUMN IF NOT EXISTS n Nested(...) on a flattened Nested group is still a no-op (src/Storages/AlterCommands.cpp) DISAGREE Unchanged by this change, and prepare and apply agree here by construction. The new shadow DROP (:2041) runs unless if_exists is set and the name is absent from the working snapshot, which is the exact negation of AlterCommand::apply's own should_skip_column_operation (:687, used for DROP at :745). For n Nested(a) neither of them removes the group, since both test the exact name, so the conditional add is correctly judged already present. On master the same statement gives the identical result: prepare marked the add ignored through hasNested (:1886) and apply skipped the drop through the exact has. The residual is real but separate: a guarded DROP COLUMN IF EXISTS n of a whole Nested group does nothing while the unguarded DROP COLUMN n removes it through ColumnsDescription::remove's prefix range. That asymmetry lives in apply's guard, is untouched here, and loses no column in the shape above. Noting it rather than raising it.
2 ❌ ADD COLUMN b UInt64 DEFAULT key, MODIFY COLUMN IF EXISTS b String now executes the modify but drops b's declared default DISAGREE The mechanism is real (:825-829 replaces the default whenever a type is given, which is why prepare back-fills it at :1999-2003), but it is neither introduced here nor part of this change's contract, and it is already being fixed at its source elsewhere. The unguarded twin ADD COLUMN b UInt64 DEFAULT key, MODIFY COLUMN b String takes the identical path on master: the back-fill sits inside if (has_column), which is false for a column the same statement adds, so that default is already dropped today. This change only makes the IF EXISTS spelling behave like the unguarded one, which is exactly what it promises. The source-level fix is my open #114807, which stops a restated type from replacing the default (`if (default_expression
3 ❌ MODIFY QUERY is not modelled, so a following COMMENT COLUMN IF EXISTS <new column> on a materialized view is still evaluated against the old output DISAGREE Unchanged by this change: master's prepare advances nothing at all, so that statement gives the same result before and after. prepare also cannot model MODIFY QUERY faithfully. apply recomputes the columns by running full select analysis and assigning metadata.columns (:1146-1160); StorageMaterializedView::alter runs that under a copied context whose current database differs (src/Storages/StorageMaterializedView.cpp:799-803); and on Shared Catalog secondary replicas it returns early without setting columns at all (:1140). A prepare-side model would therefore be free to disagree with apply, reintroducing the very divergence this change removes. The reachable consequence is bounded to a column comment silently not being applied, because StorageMaterializedView::checkAlterIsPossible (:840-864) rejects everything except MODIFY SQL SECURITY, comment alters, MODIFY QUERY and MODIFY REFRESH.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

My own cold pass, for the record, plus the nits I decided not to act on:

  • 💡 The repository rulebook prefers a new test over extending an existing one. I extended
    01318_alter_add_column_exists because one of its existing expectations flips with this change,
    which forces an in-place edit of that file, and because it is the test that owns this feature.
    Happy to split the four new scenarios out if you prefer.
  • 💡 The newly conditional-live DROP and COMMENT directions have no test of their own
    (RENAME COLUMN a TO b, DROP COLUMN IF EXISTS b used to keep b and now drops it, matching the
    unguarded spelling). DROP COLUMN, COMMENT COLUMN and RENAME COLUMN share the single
    ignore branch that add_then_rename_if_exists already covers, so I left it at three facets.
  • 💡 add_nested_absent_rename and the trailing serverError BAD_ARGUMENTS statement are
    controls, not regression tests. The first replaces the coverage lost when
    add_nested_cond_rename's expectation flipped; the second pins the pre-existing
    "cannot drop all columns" guard.
  • Verified independently while reviewing, since all three findings turn on it: ignore is read in
    exactly four places (AlterCommands.cpp:1563, :1664, :1749 and
    src/Interpreters/InterpreterAlterQuery.cpp:602). No storage's checkAlterIsPossible reads it,
    so a command that stops being ignored is not newly exposed to any engine override.

Session id: cron:clickhouse-review-slot-8:20260901-212300

@clickhouse-gh clickhouse-gh Bot closed this Sep 1, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dd6402e]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR fixes the stale pre-ALTER snapshot that made DROP COLUMN IF EXISTS x, ADD COLUMN IF NOT EXISTS x ... silently lose x, and the main sequential-snapshot direction looks right. I found one blocker, though: the new shadow state for ADD COLUMN still materializes only the name and type, so the newly-enabled guarded MODIFY COLUMN IF EXISTS path can silently lose the just-added column's DEFAULT / ALIAS semantics or bypass ALIAS-specific validation.

Findings

❌ Blockers

  • [src/Storages/AlterCommands.cpp:2032] The new sequential shadow for ADD_COLUMN stores only ColumnDescription(name, type), but later MODIFY_COLUMN logic reads default_desc / column kind from that shadow to preserve DEFAULT / ALIAS semantics and to validate ALIAS-only restrictions. As a result, ALTER TABLE t ADD COLUMN x UInt64 ALIAS y, MODIFY COLUMN IF EXISTS x String now silently turns the just-added ALIAS into a stored column, and ... MODIFY COLUMN IF EXISTS x CODEC(...) can bypass the Cannot specify codec for column type ALIAS guard. Suggested fix: advance the shadow snapshot with the full column definition produced by the ADD COLUMN command and keep validate in sync with the same shadow shape.
Tests
  • ⚠️ Add a focused stateless case for ADD COLUMN ... DEFAULT ... , MODIFY COLUMN IF EXISTS ... and ADD COLUMN ... ALIAS ... , MODIFY COLUMN IF EXISTS ... in one ALTER, so the new sequential guarded path proves it preserves the same column-kind/default semantics as a normal sequential MODIFY.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit dd6402e.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 81.00% +0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand with default settings, no fuzzer: CREATE TABLE t (a Int64, x Int64) ENGINE = MergeTree ORDER BY tuple(); INSERT INTO t SELECT number, number*10 FROM numbers(500); ALTER TABLE t DROP COLUMN IF EXISTS x, ADD COLUMN IF NOT EXISTS x String; leaves only a. The alter_sync = 0 / mutations_sync = 0 of the reported statements are incidental.
b Root cause explained? Yes. AlterCommands::prepare precomputes each command's no-op flag for the IF (NOT) EXISTS variants against a column snapshot taken once before the statement and never advances it, while AlterCommands::validate and AlterCommands::apply both walk the command list sequentially. So the add is marked redundant against the pre-statement columns, apply drops the column and skips the re-add, and when that column was the only one the metadata is left with no column list, which every later ALTER then rejects.
c Fix matches root cause? Yes. Prepare's working snapshot now advances for the commands that change column presence, mirroring AlterCommand::apply exactly, so all three passes model the same schema. No guard at the site that throws, no widened bound, no defensive check.
d Test intent preserved / new tests added? Yes. Seven scenarios added to 01318_alter_add_column_exists. One existing expectation changed (add_nested_cond_rename now renames the column the same statement added, matching the unguarded spelling asserted just above it); its previous purpose, an ignored later command whose mutation replay must not diverge, is preserved by a new add_nested_absent_rename scenario. 04307_add_to_enum's pinned NO_SUCH_COLUMN_IN_TABLE rejection still fires (probed directly).
e Both directions demonstrated? Yes. Silent column loss, the zero-column metadata plus the resulting exception, and the unloadable table after a restart were each measured on the unfixed and fixed binaries. Reverting only the snapshot-advance block and rebuilding makes 01318_alter_add_column_exists fail with exactly the reported exception; restoring it reproduced the fixed binary's Build ID bit for bit. 50/50 randomized runs green.
f Fix is general across code paths? Yes. All three presence-changing command types are handled (ADD_COLUMN, DROP_COLUMN, RENAME_COLUMN); MODIFY_COLUMN and COMMENT_COLUMN are covered because their own existence test now reads the advanced snapshot (measured: ADD COLUMN b UInt64, MODIFY COLUMN IF EXISTS b String used to skip the modify). MODIFY_ORDER_BY compares against the sorting key, not columns. prepare has a single caller, so every engine reaching applyMetadataChangesToCreateQuery is covered by the one fix. The four readers of the no-op flag were enumerated by grep, not by reasoning.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The shadow add reuses columnsAddedByAlter, so flatten_nested expansion and the nested n/n.* equivalence stay identical across the three passes; the nested cases are exercised with share_nested_offsets = 0. The shadow drop mirrors apply's CLEAR COLUMN and IN PARTITION exclusion, and both shadow drop and shadow rename reuse apply's own existence predicate, so the throwing ColumnsDescription operations can only be reached where apply reaches them. The boundary case of zero remaining columns is covered in both directions, including that dropping the last column with nothing re-adding it is still refused.
h Backward compatible? (maintainer-approved exception only) Yes. No stored-format change, no setting added or changed, so no SettingsChangesHistory.cpp entry. The only behaviour change is that a statement which used to lose a column now keeps it, plus the nested expectation in (d). A table already persisted with zero columns by an older server stays unloadable, which this change deliberately does not try to repair.
i Invariants and contracts preserved? Yes. prepare still only reads the metadata and writes command fields; the working snapshot is a local copy. The contract preserved on purpose is the rejection of MODIFY COLUMN ... ADD ENUM VALUES on a column created in the same statement, kept by tracking the columns this statement adds. On the error path nothing is committed: the reported statement is now refused atomically and the table is left exactly as it was.

Session id: cron:clickhouse-impl-slot-7:20260901-171800

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @Algunenano, could you review this? AlterCommands::prepare decided the IF (NOT) EXISTS no-op flags against a column snapshot taken once before the statement, while validate and apply both walk the commands sequentially, so DROP COLUMN IF EXISTS c, ADD COLUMN IF NOT EXISTS c <type> silently lost c, and left the table with no column list at all when c was its only column.

{
if (command.type == AlterCommand::ADD_COLUMN)
{
for (auto & column : columnsAddedByAlter(columns, ColumnDescription(command.column_name, command.data_type),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dd6402e50 with master d8a1c5042 (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

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

Job report

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dd6402e50c30a3a7642668211b78441cf7e2d6d4

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
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai can we just refuse to add the column back if it is dropped, modified or renamed in the same alter?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Either one can introduce a backward-incompatible change, so let's keep it as it is.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping it as it is; I am not adding the refusal check, so the diff stays as published.

@PedroTadim PedroTadim assigned PedroTadim and unassigned PedroTadim Sep 2, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

This is superseded by #127897: it fixes the same DROP COLUMN IF EXISTS x, ADD COLUMN IF NOT EXISTS x case as part of preparing every command of an ALTER against the columns the previous commands leave (the work of #127497), so this PR should not be merged alongside it.

@PedroTadim PedroTadim closed this Oct 28, 2026
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-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants