Skip to content

Fix column loss when a column dropped and re-added with IF NOT EXISTS in the same ALTER statement - #117825

Open
zoomxi wants to merge 53 commits into
ClickHouse:masterfrom
zoomxi:fix-re-add-if-not-exists-zero-column
Open

zoomxi wants to merge 53 commits into
ClickHouse:masterfrom
zoomxi:fix-re-add-if-not-exists-zero-column

Conversation

@zoomxi

@zoomxi zoomxi commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

A single ALTER statement that drops a column and re-adds it under the same name with ADD COLUMN IF NOT EXISTS silently drops the column for good. The re-added column never comes back, so a table whose columns are all re-added this way ends up with an empty column list; any later ALTER on it then aborts with Cannot alter table ... metadata doesn't have structure (LOGICAL_ERROR).

Closes: #117824

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

Fix re-adding a column with ADD COLUMN IF NOT EXISTS after it was dropped in the same ALTER statement.


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

@zlareb1

This comment was marked as low quality.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7439188]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

At 7439188a1add545e476ebabd40251cbc891a68c2, this PR confines freed-name bookkeeping to ADD COLUMN IF NOT EXISTS. The reduced change fixes the reported column-definition loss and the previously reported conditional rename regression; 05459_alter_readd_if_not_exists_zero_column passes in the current Fast test report. No new inline findings. The six outstanding findings below remain in the current code, but are pre-existing bugs whose deferral is accepted. Complete their follow-up tracking before approval; restoring the removed storage changes is unnecessary.

Findings

❌ Blockers — previously reported data correctness bugs, deferred from this PR

⚠️ Majors — previously reported validation bugs, deferred from this PR

Missing context / blind spots
  • ⚠️ The older cases were verified against current source paths, without local execution because this review job has no ClickHouse binary. Their original threads contain reproductions. The overlapping PR tracks the Nested and repeated-drop cases; no specific follow-up tracker was found for the Memory, pending-read, conditional-parent validation, or codec-validation cases.
Final Verdict

Status: ⚠️ Request changes

Link follow-up issues for the four untracked deferred cases and record the relationship to #127897. These can remain separate fixes. The conditional rename finding is resolved; no duplicate inline comments or new review batch were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 3, 2026
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e9adc8324 with master da3dc325b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 31628339d; 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.

Object file sizes

57 object files changed (+294.18 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageMemory.cpp.o 744.27 KiB 885.36 KiB +141.09 KiB (+18.96%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromMergeTree.cpp.o 2.71 MiB 2.75 MiB +38.61 KiB (+1.39%)
src/CMakeFiles/dbms.dir/Storages/AlterCommands.cpp.o 901.11 KiB 936.98 KiB +35.87 KiB (+3.98%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTask.cpp.o 2.07 MiB 2.11 MiB +34.98 KiB (+1.65%)
src/CMakeFiles/dbms.dir/Storages/MutationCommands.cpp.o 132.21 KiB 148.36 KiB +16.15 KiB (+12.22%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 2026
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). labels Sep 9, 2026
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Sep 15, 2026
…t stores.

The wide path already remapped via the source-part name, but compact/non-wide
mutations still tested `part_columns.has(command.column_name)` and then replayed
the rename as `READ_COLUMN`, so stale values survived a same-statement or
pending `RENAME` plus `DROP`/`CLEAR`. Share that lookup and skip the rename
replay for dropped or cleared sources.

https: //github.com/ClickHouse/pull/117825
Co-authored-by: Cursor <[email protected]>
zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Sep 15, 2026
…me name.

`nameStoredInPart` fell back to the finished `AlterConversions` map, so
`DROP a, RENAME b TO a` dropped `b`'s files and left `a`'s data in place.
That broke `01281_alter_rename_and_other_renames`,
`03526_columns_substreams_in_wide_parts`, and
`03990_alter_rename_column_swap_different_types` in Fast test.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117825&sha=51ce014581e7d1eec9aab9b29fa497324a2a412e&name_0=PR&name_1=Fast%20test
ClickHouse#117825
Comment thread src/Storages/AlterCommands.cpp Resolved
zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Sep 16, 2026
…d files.

`prepare` treated a Nested parent as present for every command, so `MODIFY COLUMN IF EXISTS n` threw instead of no-op'ing. The wide-part DROP path also expanded `hasNested` without `share_nested_offsets`, so `DROP COLUMN n` deleted independent `n.a` files on parts written before `n` existed.

ClickHouse#117825
zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Sep 16, 2026
`hasNested` matches any dotted prefix, so a UNIQUE KEY table with only
an `ALIAS` column `` `n.x` `` rejected `CLEAR COLUMN IF EXISTS n` with
`SUPPORT_IS_DISABLED` while `prepare`/`validate`/`getMutationStageDecision`
treated it as a no-op. Use `hasColumnOrNested` with `AllPhysical` for the
nested arm.

ClickHouse#117825
Comment thread src/Storages/AlterCommands.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed, and the fix is in flight. Both PRs you found are mine and still open:

One extra data point: on 25cccdf8 the other seven amd_asan_ubsan, db disk shards all finished success, and 7/8 died in the pre-pull step before any test ran, so nothing in the ALTER diff is reachable from it. In the last 24 hours that exact job hit this denial on 107 distinct (PR, commit) runs and finished success on 259 others, and the denial covers 17 integration job flavours and 6 master commits, so it tracks whether the runner already holds the images rather than the branch.

Nothing to change on your side. Re-running that single job is usually enough to clear it, along with the Bugfix validation drop that cascaded from it.

zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Sep 17, 2026
`DROP_COLUMN` dropped `auto_minmax_index_<column>` before the `clear` /
`partition` guard, so `CLEAR COLUMN x` and `CLEAR COLUMN x IN PARTITION`
removed the index even though the column definition stayed. Move the
exact-index removal onto the full metadata-drop path.

ClickHouse#117825
zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Sep 18, 2026
`hasColumnOrNested` previously inspected only the first `n.*` match, so a
UNIQUE KEY table with `` `n.x` UInt32 ALIAS id, `n.y` UInt32 `` treated
`CLEAR COLUMN n` as a no-op while `n.y` remained stored.

ClickHouse#117825
zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Sep 21, 2026
…nt `RENAME COLUMN`.

The guard used pre-ALTER names, so `RENAME COLUMN a TO b, CLEAR COLUMN b` skipped the reject path while the mutation still rewrote stored `a` and dropped `unique_key_index.sst`.

ClickHouse#117825
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Outdated
{
if (!command.clear) /// CLEAR column is Ok even if there are dependencies.
/// `CLEAR` and `IN PARTITION` keep the column for later commands in this ALTER.
if (!command.clear && !command.partition)

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.

[Major] Keep conditional parent no-ops out of the validation snapshot

prepare and apply deliberately preserve n.* for DROP COLUMN IF EXISTS n when there is no exact n, but this branch still removes the children from all_columns. Reproduced with this head's Fast test binary:

CREATE TABLE t (id UInt8, n Nested(a UInt8))
ENGINE = MergeTree ORDER BY id;
ALTER TABLE t DROP COLUMN IF EXISTS n, COMMENT COLUMN `n.a` 'retained';

This fails with NOT_FOUND_COLUMN_IN_BLOCK for n.a, although the drop is a no-op and commenting the retained child is valid. Apply the same exact-name IF EXISTS no-op predicate here before dependency checking, removing columns, or retiring pending defaults. Add a regression with an unconditional command on the retained child after the no-op.

Comment thread src/Storages/AlterCommands.cpp Resolved
…izes.

A replacement default that reads a subcolumn of a column recreated in the same `ALTER` was stored with zero rows. A cleared or missing `Nested` member was filled as an empty array instead of the sibling's sizes.
`CLEAR COLUMN ... IN PARTITION` was applied to a lightweight-update patch in another partition, so that update was lost on read and after a later mutation.
…aves.

`prepare` ignored a subcolumn codec after a type change in the same statement. `DROP COLUMN IF EXISTS` of a `Nested` parent that is not an exact column removed the children during validation. `CLEAR` of an alias-only parent was emitted as a mutation and rejected on `UNIQUE KEY` tables.
Use `COMMENT COLUMN` to verify that the retained child remains available after a no-op parent drop, and remove the `StorageMemory` diagnostics reported by `clang-tidy`.

Related: ClickHouse#117825
The previous commit replaced the rename assertion with `COMMENT COLUMN` without updating the expected output.

Related: ClickHouse#117825
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
Keep untouched missing columns at their read defaults when the last stored column is dropped. Evaluate defaults only for replaced or newly added identities, and establish the saved row count before constant alias evaluation.

Related: ClickHouse#117825
…o fix-re-add-if-not-exists-zero-column

# Conflicts:
#	src/Storages/StorageMemory.cpp
Use `getSettingsChanges` to reconstruct the settings AST after `StorageInMemoryMetadata` switched to serialized settings.

Related: ClickHouse#117825
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
- Evaluate default dependencies through aliases and subcolumns recursively.
- Respect flatten_nested when tracking added physical columns.
- Replace unbounded rewrite history with a short exclusive publication phase.
- Evaluate expressions before taking the lock so dictionary self-reads do not deadlock.

Related: ClickHouse#117825
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026
Resolve explicitly declared dotted columns before tuple subcolumns. Extract required subcolumns before conversion and avoid converting unused tuple members.

Related: ClickHouse#117825
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
Convert a parent before extraction when its old type lacks the requested subcolumn, and use scalar defaults instead of sibling array offsets for missing scalar dependencies.

Skip tests in Replicated database and ParallelReplicas configurations that reject the tested SQL or table plan.

Related: ClickHouse#117825
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Outdated

/// The checks above read the column as the previous commands left it. Record this command's
/// own properties so the next command, and the final default check, see them too.
all_columns.modify(column_name, [&](ColumnDescription & column)

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.

[Major] Advance the subcolumn codec state in validation too

The new property replay only reaches ordinary columns. The subcolumn branch at AlterCommands.cpp:2496-2498 validates a codec and immediately continues without updating the parent's subcolumn_codecs, so later commands still see the old state.

Reproduced with this head's Fast test binary:

SET enable_subcolumn_codecs = 1;
CREATE TABLE t (a Tuple(v UInt64)) ENGINE = MergeTree ORDER BY tuple();
ALTER TABLE t
    MODIFY COLUMN a Tuple(v UInt64, w UInt64),
    MODIFY COLUMN a.w CODEC(ZSTD),
    MODIFY COLUMN a.w REMOVE CODEC;

This throws BAD_ARGUMENTS: Subcolumn a.w doesn't have CODEC, cannot remove it. Running the modifications separately succeeds. The earlier type change is now visible, but the codec installed by the next command is absent from the validation snapshot.

Apply each validated subcolumn codec change to all_columns before that branch continues, and cover setting/removing a codec on a subcolumn introduced earlier in the same statement.

Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Outdated
columns.remove(command.column_name);
}
else if (command.type == AlterCommand::RENAME_COLUMN && columns.has(command.column_name))
columns.rename(command.column_name, command.rename_to);

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.

[Blocker] Hide the renamed source from a replacement using its old name

Making the replacement add effective exposes the old part column through both names while the rename mutation is pending. AlterConversions maps x_old back to the stored x, but the reader also finds that same stored x for the newly created column. Reproduced with this head's Fast test binary:

CREATE TABLE t (id UInt8, x UInt8) ENGINE = MergeTree ORDER BY id
SETTINGS min_rows_for_wide_part = 0, min_bytes_for_wide_part = 0;
INSERT INTO t VALUES (1, 7);
SYSTEM STOP MERGES t;
ALTER TABLE t RENAME COLUMN x TO x_old,
    ADD COLUMN IF NOT EXISTS x UInt8 DEFAULT 9
SETTINGS alter_sync = 0;
SELECT x_old, x FROM t;
SYSTEM START MERGES t;

The read returns (7, 7), rather than (7, 9); after mutation completion it changes to (7, 9) without another write. Preserve column identity in pending-read conversions so the rename destination retains the old data and the recreated source reads its default. Please cover both pending and completed reads.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Not a regression. This is an existing bug on master and should be fixed in a separate PR.

@asya-ch asya-ch self-assigned this Nov 24, 2026

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). external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Cannot alter table A metadata doesn't have structure (STID: 3623-38a4)

7 participants