Skip to content

[WIP] ALTER command sees previous commands - #127497

Draft
vitlibar wants to merge 5 commits into
ClickHouse:masterfrom
vitlibar:alter-prepare-evolving-columns
Draft

vitlibar wants to merge 5 commits into
ClickHouse:masterfrom
vitlibar:alter-prepare-evolving-columns

Conversation

@vitlibar

@vitlibar vitlibar commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

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

ALTER command sees previous commands

Inside a single ALTER with several commands, every command should see the table as the previous commands of the same statement left it, not as it was before the statement.

Example. Take a table with a column b and run one ALTER that drops it and adds it back with a new type:

CREATE TABLE t (a Int64, b UInt64);
ALTER TABLE t DROP COLUMN b, ADD COLUMN IF NOT EXISTS b String;
SHOW CREATE TABLE t;

Before this branch, the IF NOT EXISTS check looked at the table as it was before the ALTER started. There b still existed, so the ADD COLUMN IF NOT EXISTS was marked as "nothing to do". Then the commands ran in order: b was dropped, the ADD COLUMN IF NOT EXISTS was skipped, and the column was silently gone.

Closes #127444, also fixes scenarios #123966 (comment) and #123966 (comment).
Closes #117824


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

@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [616bcf5]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_merge_tree_s3/test.py::test_s3_disk_apply_new_settings[node] FAIL cidb
Upgrade check (amd_release) FAIL
Changed settings are not reflected in the settings changes history (see changed_settings.txt) FAIL cidb

AI Review

Summary

PR #127497, reviewed at 616bcf54b3e4a28666aa717624935e09a24c0e17, makes column preparation follow preceding commands within an ALTER TABLE, expands nested drops into member mutations, and rejects renaming re-added columns. ❌ Block: rename/drop/re-add still retains deleted values in wide parts, and the new rejection also breaks supported Memory schema changes.

PR Metadata

💡 The required changelog entry, ALTER command sees previous commands, does not explain the within-statement behavior or conditional checks. Suggested replacement: “Fix multi-command ALTER TABLE statements so column operations observe the schema produced by earlier commands in the same statement, including IF EXISTS and IF NOT EXISTS checks.”

Findings

❌ Blockers

  • [P1] Dropped values survive an earlier rename — src/Storages/AlterCommands.cpp:1807. On a wide MergeTree part containing n.a = [11], RENAME COLUMN n.a TO n.c, DROP COLUMN n, ADD COLUMN IF NOT EXISTS n.c Array(UInt32) returns the old [11] instead of []. The expanded drops use the renamed member names, while wide-part mutation replay still reasons about the source-part identities. Every generated mutation reports completion, and OPTIMIZE TABLE ... FINAL preserves the wrong value. The scalar sequence RENAME COLUMN q TO r, DROP COLUMN IF EXISTS r, ADD COLUMN IF NOT EXISTS r UInt32 DEFAULT 7 likewise retains 42 instead of 7. Compact parts and split statements return the expected defaults. Preserve physical identity through rename/drop replay, or reject this unsafe order before committing metadata; the new guard only rejects the reverse order.

⚠️ Majors

  • [P2] A part-specific restriction rejects valid Memory alterations — src/Storages/AlterCommands.cpp:2618. CREATE TABLE t (id UInt64, q UInt32) ENGINE = Memory; ALTER TABLE t DROP COLUMN q, ADD COLUMN q UInt32, RENAME COLUMN q TO r; succeeds on 0fd5386d4 and yields id UInt64, r UInt32, but head rejects it with NOT_IMPLEMENTED. StorageMemory::alter applies metadata directly and has no wide-part mutation replay. Move or scope the guard to affected engines.

  • [P2] Preparation still invents subcolumns for a newly added alias — src/Storages/AlterCommands.cpp:2188. [dismissed by author -- https://github.com/[WIP] ALTER command sees previous commands #127497#discussion_r4358141349] The added-column snapshot still omits default_kind and default_expression. On a table with id UInt64, ADD COLUMN p Tuple(a UInt32) ALIAS tuple(toUInt32(id)), MODIFY COLUMN IF EXISTS p.a CODEC(LZ4) with enable_subcolumn_codecs = 1 is retargeted to the alias and fails because aliases cannot have codecs; the absent storage subcolumn should make the conditional modification a no-op. Reconfirmed on head. Carry the alias metadata into both snapshots.

Tests
  • ⚠️ Add a focused stateless regression for rename/drop/re-add on existing wide-part rows, asserting values after mutation completion. Include scalar and nested columns; compact and split-statement controls demonstrated the discrepancy.
  • ⚠️ Add a stateless case preserving the supported empty-Memory drop/add/rename sequence.
Final Verdict

❌ Block. Required changes: prevent deleted data from surviving rename/drop/re-add, scope the mutation-specific rejection to affected engines, and add the focused regressions above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 22, 2026
`AlterCommands::prepare` used the columns before the ALTER, so a MODIFY COLUMN
of a column added by the same statement was bound to a subcolumn with the same
name, and IF EXISTS skipped columns added or dropped by a previous command.

ClickHouse#127444
@vitlibar
vitlibar force-pushed the alter-prepare-evolving-columns branch from f68871a to f57deb8 Compare October 22, 2026 23:29
Comment thread src/Storages/AlterCommands.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Oct 23, 2026
The snapshots appended every added column at the end, so DROP COLUMN of a
Nested group could remove other columns than `apply` does and a later
IF NOT EXISTS was decided against the wrong columns. The snapshots now insert
the added columns and move modified columns the way `apply` does.
SELECT '======= ADD COLUMN THEN ADD ENUM VALUES IN ONE STATEMENT ===============';
CREATE OR REPLACE TABLE enum_add_then_modify (y Int8) ENGINE = Memory;
ALTER TABLE enum_add_then_modify ADD COLUMN x Enum8('a' = 1), MODIFY COLUMN x ADD ENUM VALUES('b' = 2); -- { serverError NO_SUCH_COLUMN_IN_TABLE }
ALTER TABLE enum_add_then_modify ADD COLUMN x Enum8('a' = 1), MODIFY COLUMN x ADD ENUM VALUES('b' = 2);

@vitlibar vitlibar Oct 23, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Now the ALTER statement sees the changes made by itself, so ALTER TABLE enum_add_then_modify ADD COLUMN x Enum8('a' = 1), MODIFY COLUMN x ADD ENUM VALUES('b' = 2) gives a enum with two values a and b

CREATE TABLE default.add_nested_exact_sno0\n(\n `key` UInt64,\n `n` String\n)\nENGINE = MergeTree\nORDER BY key\nSETTINGS share_nested_offsets = 0, index_granularity = 8192
CREATE TABLE default.add_nested_rename_child\n(\n `n.a` Array(UInt32),\n `m` Array(String)\n)\nENGINE = MergeTree\nORDER BY tuple()\nSETTINGS share_nested_offsets = 0, index_granularity = 8192
CREATE TABLE default.add_nested_cond_rename\n(\n `n.a` Array(UInt32),\n `n.b` Array(String)\n)\nENGINE = MergeTree\nORDER BY tuple()\nSETTINGS share_nested_offsets = 0, index_granularity = 8192
CREATE TABLE default.add_nested_cond_rename\n(\n `n.a` Array(UInt32),\n `m` Array(String)\n)\nENGINE = MergeTree\nORDER BY tuple()\nSETTINGS share_nested_offsets = 0, index_granularity = 8192

@vitlibar vitlibar Oct 23, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Since the ALTER statement now sees the changes made by itself, the last rename n.b to m works now:

CREATE TABLE add_nested_cond_rename
(
    `n.a` Array(UInt32)
)
ENGINE = MergeTree()
ORDER BY tuple()
SETTINGS share_nested_offsets = 0;

ALTER TABLE add_nested_cond_rename ADD COLUMN IF NOT EXISTS n Nested(a UInt32, b String), RENAME COLUMN IF EXISTS `n.b` TO `m`;

Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
`apply` skipped `DROP COLUMN IF EXISTS n` when only `n.a`, `n.b` existed,
while `prepare`, `validate` and the mutation planning treated `n` as the
Nested group. The mutation then deleted the data of `n.*` and the columns
stayed in the table, reading as empty.
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 616bcf54b3e4a28666aa717624935e09a24c0e17 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ ], "data": [ ], "rows": 0, "exception": "Code: 24…).

See the job log for details.

Comment thread src/Storages/AlterCommands.cpp Resolved
@vitlibar vitlibar changed the title Prepare each ALTER command against the columns left by the previous ones ALTER command sees previous commands Oct 23, 2026
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
`DROP COLUMN n` of the Nested group `n.a`, `n.b` became one mutation command
`DROP COLUMN n`, but a mutation matches the columns of a part by their exact
names. When the table had a column named like a member again by the time the
mutation ran, after `DROP COLUMN n, ADD COLUMN IF NOT EXISTS n.b` or a
separate `ADD COLUMN n.b`, a wide part kept the data of the dropped member
and the new column showed it. The mutation now drops each member by name.
@vitlibar
vitlibar force-pushed the alter-prepare-evolving-columns branch from 6ff8b2e to 0fd5386 Compare October 23, 2026 22:23
Comment thread src/Storages/AlterCommands.cpp Resolved
`DROP COLUMN q, ADD COLUMN q ..., RENAME COLUMN q TO r` put `DROP COLUMN q`
and `RENAME COLUMN q TO r` into one mutation. The mutation finds `q` in a
part by its name, so it renamed the data of the dropped column to `r` while
the drop removed the files, and the part listed `r` without any data for it.
Separate ALTER queries are refused while the drop's mutation is pending, so
the rename is rejected in the same ALTER too.
auto member_ast = make_intrusive<ASTAlterCommand>();
member_ast->type = ASTAlterCommand::DROP_COLUMN;
member_ast->if_exists = if_exists;
member_ast->set(member_ast->column, make_intrusive<ASTIdentifier>(nested_column.name));

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.

[P1] Handle drop/re-add after an earlier rename

Expanding the group into its current member names still loses the identity of a member renamed earlier in this statement. Reproduced with the fast-test binary for 616bcf54:

CREATE TABLE t (id UInt64, n Nested(a UInt32, b UInt32))
ENGINE = MergeTree ORDER BY id
SETTINGS min_rows_for_wide_part = 0, min_bytes_for_wide_part = 0;
INSERT INTO t VALUES (1, [11], [42]);
ALTER TABLE t
    RENAME COLUMN `n.a` TO `n.c`,
    DROP COLUMN n,
    ADD COLUMN IF NOT EXISTS `n.c` Array(UInt32)
SETTINGS mutations_sync = 1;
SELECT id, `n.c` FROM t;

This returns (1, [11]), although the replacement column should be empty. The generated mutations are RENAME COLUMN n.a TO n.c, DROP COLUMN n.c, and DROP COLUMN n.b; all report is_done = 1, and OPTIMIZE TABLE t FINAL preserves the old value. Compact parts and splitting the operations into separate statements return (1, []).

The scalar form also retains deleted data: starting with q = 42, RENAME COLUMN q TO r, DROP COLUMN IF EXISTS r, ADD COLUMN IF NOT EXISTS r UInt32 DEFAULT 7 returns 42 instead of 7 in a wide part. The new validation guard catches only a rename after a drop, so this opposite order remains accepted.

Preserve the source-part identity through preceding renames when executing these drops, or reject the unsafe combination on affected engines before committing metadata. Please cover this order with a stateless test that reads existing wide-part data after mutation completion.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@groeneai There are always some gaps, can you make your own PR, move my work from this PR there and then try to correctly fix all the gaps?

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.

Acknowledged. I'll open my own PR from master carrying your commits (authorship kept), work through the remaining gaps, including the rename-then-drop/re-add case above and the Memory rename guard, and post the link here. It also covers the DROP b, ADD COLUMN IF NOT EXISTS b case of my open #117593, which I'll reconcile with the new PR.

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.

I opened #127897 with your five commits (authorship kept) and these fixes on top: the mutation names the columns a part stores, so the rename, drop and re-add cases from this thread read the new column (7, []) instead of the dropped data; the NOT_IMPLEMENTED rename guard is removed (it also hit ENGINE = Memory); prepare builds an added column with the code apply uses, so an ALIAS keeps its kind; and the empty-part check follows the renames of the ALTER. Not covered: CLEAR COLUMN combined with RENAME COLUMN, which the open #118500 and #117825 change.

/// The column exists here only because it was added again after the drop. The mutation of the ALTER would
/// rename the data of the dropped column instead of removing it, because it finds the column in the parts
/// by its name.
if (dropped_columns.contains(command.column_name))

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.

[P2] Restrict the mutation-specific rename guard to affected engines

This validation runs for every storage, including Memory, whose schema alteration applies metadata directly and does not use the wide-part mutation path that motivates this restriction:

CREATE TABLE t (id UInt64, q UInt32) ENGINE = Memory;
ALTER TABLE t DROP COLUMN q, ADD COLUMN q UInt32, RENAME COLUMN q TO r;

The preceding PR binary (0fd5386d4) accepts this and produces id UInt64, r UInt32. The current head throws NOT_IMPLEMENTED at this guard, even though the table is empty and there is no stored part to corrupt. StorageMemory::checkAlterIsPossible explicitly supports all three operations, and StorageMemory::alter applies them through AlterCommands::apply without mutation replay.

Keep this restriction in the affected engine's eligibility check, or condition it on the relevant mutation behavior, so existing Memory schema migrations remain supported. Add a small stateless regression for the sequence above.

@vitlibar
vitlibar marked this pull request as draft October 26, 2026 10:51
@vitlibar vitlibar changed the title ALTER command sees previous commands [WIP] ALTER command sees previous commands Oct 26, 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

comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants