Skip to content

Fix a renamed and dropped column being read from the wrong file while the mutation is pending - #114601

Merged
tiandiwonder merged 6 commits into
masterfrom
fix-dropped-renamed-column-read
Aug 24, 2026
Merged

tiandiwonder merged 6 commits into
masterfrom
fix-dropped-renamed-column-read

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Related: #114562

Problem

A column that is renamed, dropped and added again in one ALTER silently returns the dropped
column's data instead of its own default, while the mutation is still pending:

CREATE TABLE t (a UInt64, h UInt8 DEFAULT 0) ENGINE = MergeTree ORDER BY tuple()
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO t SELECT number + 100, 0 FROM numbers(1000);

SET alter_sync = 0;   -- mutation left pending
ALTER TABLE t RENAME COLUMN a TO b, DROP COLUMN b, ADD COLUMN b UInt64 DEFAULT 7;

SELECT count(), min(b), max(b) FROM t;
-- 1000  100  1099     <- the old `a` values
-- expected: 1000  7  7

No error and nothing in the log; it affects Wide and Compact parts alike. The added b is a
different column from the one that was dropped, so its rows have to come from its DEFAULT.

Scope. This fixes the answer while the mutation is pending. Once the mutation has materialised a
Wide part still returns the dropped column's data — a separate, pre-existing defect that lives in
MutateTask, see the follow-ups at the end.

Root cause

AlterConversions records a pending drop under the name the command used:

else if (command.type == DROP_COLUMN)
{
    dropped_columns.emplace(command.column_name);
}

while every consumer of isColumnDropped asks about a column under the name it has in the part:

  • IMergeTreeReader::isColumnDroppedByPendingMutation takes the name out of columns_to_read, which is
    built from getColumnInPart and therefore already has the rename mapping applied
    (IMergeTreeReader.cpp:81);
  • injectRequiredColumnsRecursively passes column_name_in_part (MergeTreeBlockReadUtils.cpp:119).

Without a rename the two names are identical, so the hazard those checks exist for — a column dropped
and re-added under the same name, whose data in the part is stale — behaves correctly. That is why this
was never noticed. With a rename they diverge: the part holds a, the drop is recorded for b, the
check asks about a, finds nothing, and the reader streams the a file into the new b.

Solution

Consume the ordering in DROP_COLUMN, where both halves of it are needed anyway. Commands arrive as
issued, so the renames recorded so far are exactly those preceding the drop; the entry that gives the
drop its part-side name is also the entry the drop makes obsolete, so one lookup does both:

auto name_in_part = command.column_name;
auto it = std::ranges::find(rename_map, command.column_name, &RenamePair::rename_to);
if (it != rename_map.end())
{
    name_in_part = it->rename_from;
    rename_map.erase(it);
}

dropped_columns.emplace(std::move(name_in_part));

Every existing caller of isColumnDropped already passes a part-side name, so all of them become correct
at once and none of them changes.

Retiring the mapping matters on its own. RENAME a TO b, DROP b, RENAME c TO b used to leave two
entries pointing at b — from the dropped a and from the live c — and the lookup returns whichever
comes first, so b read the wrong column. Writing a RenamePair as to <- from, where to is the name
in the metadata and from the name in the part, and remembering that dropped_columns now holds
part-side names:

# command what happens rename_map dropped_columns
1 RENAME a TO b not chained, insert [b <- a] {}
2 DROP b b <- a gives the part's a and is erased in the same step [] {a}
3 RENAME c TO b b is free, insert [b <- c] {a}

getColumnOldName("b") then answers c, and a stays dropped so nothing reads it. Both halves are
needed to get this right:

variant min(b), max(b), want 5000 5999
master 100 1099 — the dropped column's data
part-side drop only 0 0 — the default
both 5000 5999 ✔

Why in the drop and not when the name is taken over

Retiring the entry in RENAME_COLUMN instead — erase whatever maps onto the new target and is already
dropped — reads as the more targeted fix, and it is where the first two commits of this PR put it. It has
to cover two paths, though, because a rename can reach the freed name through a chain:
RENAME c TO d, RENAME d TO b updates the existing d <- c entry in place rather than appending, so an
erase placed on the appending path alone leaves [b <- a, b <- c] again. That variant does not misread —
it fails outright, because b resolves to the dropped a and the part-side name reaches the storage
snapshot:

Code: 16. DB::Exception: There is no column a in table. (NO_SUCH_COLUMN_IN_TABLE)

Reaching it takes ReplicatedMergeTree: a single ALTER rejects transitive renames
(Transitive renames in a single ALTER query are not allowed), and StorageMergeTree::alter always
waits for the previous mutation before a metadata change (StorageMergeTree.cpp:548, "alters should be
executed in sequential order"
), so two of them can never both be pending there.

Doing it in the drop is the same thing one step earlier and needs no case analysis: a mapping onto a
dropped name simply never exists, so RENAME_COLUMN has nothing to clean up and the chained path needs
no special handling. The two were measured equivalent on both the read path (all of 04872) and the
materialisation path (the mutation run to completion with alter_sync = 2 for
RENAME a TO b, DROP b, ADD b, RENAME a TO b, DROP b, RENAME c TO b, RENAME a TO b, DROP b and the
chained Replicated case — byte-identical results).

Why not fix it in the reader

Checking the renamed-to name in the reader as well looks equivalent and is wrong. The opposite command
order produces exactly the same AlterConversions state, and 01281_alter_rename_and_other_renames
already pins the required behaviour for it:

ALTER TABLE t DROP COLUMN value2_old, RENAME COLUMN value2 TO value2_old;

Here the drop hit a different column that merely carried that name, and value2's data is live and
must be readable as value2_old. The only thing separating the two situations is where the drop sits
among the renames, which the readers cannot see. Measured with the reader-side variant applied, live
data is replaced by defaults:

 dropped, then the name reused by a rename
-1000	100	1099
+1000	0	0

Hence the ordering has to be consumed at construction time.

Tests

tests/queries/0_stateless/04872_read_renamed_then_dropped_and_readded_column.sh — seven cases: the
defect on Wide and on Compact, the RENAME/DROP/RENAME case above and its chained variant, plus
three controls that must not move — drop-and-re-add without a rename (what the check was written for),
a pending rename with no drop, and the mirror case.

The chained case runs the ALTERs with the partition detached and then attaches the part carrying the
old column names to a table whose merges are stopped, so the mutations stay unapplied while it is read —
the same shape as 03905_chained_rename_column_mutation. Verified on a local server that it is
load-bearing: with the retirement placed on the appending path of RENAME_COLUMN it fails with
NO_SUCH_COLUMN_IN_TABLE, while the non-chained control passes either way.

Because the two possible wrong answers fail in opposite directions, the result is checked three ways:

variant the defect the mirror case
master 1000 100 1099 ✗ 1000 100 1099 ✔
reader-side variant 1000 7 7 ✔ 1000 0 0 ✗
this change 1000 7 7 ✔ 1000 100 1099 ✔

01281_alter_rename_and_other_renames, 01278_alter_rename_combination,
03905_chained_rename_column_mutation, 04053_alter_add_rename_column_in_single_query and
04011_detach_rename_attach_column all pass.

Notes for reviewers

  • The retirement relies on the command sequence reaching AlterConversions without gaps, and it does.
    Metadata mutations are exempt from every params switch — needIncludeMutationToSnapshot
    (MergeTreeData.cpp:653, "Metadata mutations must be included into the snapshot regardless of the
    parameters"
    ) and addSupportedCommands (MergeTreeData.cpp:704) both admit RENAME_COLUMN and
    DROP_COLUMN unconditionally, so no caller can ask for a snapshot holding the renames but not the
    drops. Per-part filtering then takes a contiguous suffix, never a middle slice: both
    getOnFlyMutationCommandsForPart implementations walk in reverse and stop at the first mutation at
    or below the part's version (StorageMergeTree.cpp:3549, ReplicatedMergeTreeQueue.cpp:2355). A gap
    would need RENAME a TO b in the window with DROP b cut out, but the drop is the newer of the two,
    so cutting it necessarily cuts the rename that created the entry as well. Order is a documented
    contract: "@return list of mutation commands in order: oldest to newest" (MergeTreeData.h:617).
    The chained-rename collapsing that predates this PR rests on the same property.

    The replicated loop iterates by mutation_version while testing alter_version, so the suffix is
    contiguous only if the two are co-monotonic, and they are: the single site that creates a mutation
    entry with alter_version != -1 (StorageReplicatedMergeTree.cpp:7092) does so in one tryMulti
    that also carries set /metadata with a CAS on the current metadata version
    (StorageReplicatedMergeTree.cpp:7001, and alter_version is that version plus one) and set /mutations with a CAS on its own version. Either CAS makes two of them serialise, and the sequential
    number is assigned inside that atomic commit, so the k-th alter mutation to commit gets both the
    larger sequence number and the higher metadata version. mutate — the other creator — leaves
    alter_version at -1 and is handled by the loop's other branch. Confirmed by reading the raw znodes
    through system.zookeeper: with ALTER UPDATEs interleaved between the renames the metadata
    subsequence is 1, 2, 3, 4 in znode order, and ten concurrent renames from separate clients land as
    alter_version 1..9 matching the znode sequence exactly.

  • isColumnDropped now consistently answers about part-side names. That matches all four existing call
    sites, so it is a fix rather than a contract change for them, but a future caller holding a metadata
    name would have to resolve it first.

  • Overlaps with Fix NO_SUCH_COLUMN_IN_TABLE naming a column absent from the table when a part's columns were all renamed or all dropped #114562, in a way that is safe in either merge order. That PR adds a second lookup in
    the empty-candidate accounting loop of injectRequiredColumns, mapping a part name forward to its
    renamed-to name and testing the drop under that, so that a single-statement RENAME a TO b, DROP b is
    recognised as accounted for. This change makes the first lookup answer that correctly, because the
    drop is then already recorded as a, so the second lookup becomes dead code once both are in. It is
    deliberately left in place here rather than removed pre-emptively: while only Fix NO_SUCH_COLUMN_IN_TABLE naming a column absent from the table when a part's columns were all renamed or all dropped #114562 is merged the
    second lookup is what makes that case work. A small cleanup to delete it belongs after this merges.
    Checked on a scratch branch carrying both changes with that lookup deleted — 04870, 04871, 04872,
    03830, 04011 and 01281_alter_rename_and_other_renames all still pass, so the cleanup is safe.

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 a column that was renamed, dropped and added again in one ALTER returning the dropped column's values instead of its own default while the mutation was still pending.


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

Follow-ups found while testing, not fixed here

Both are pre-existing, live in MutateTask rather than AlterConversions, and were measured identical
on the pre-PR base and on this branch, so they are out of scope. Filed for follow-up:

  • RENAME a TO b, DROP b, ADD b UInt64 DEFAULT 7 still returns 1000 100 1099 after the mutation has
    materialised. This PR fixes the answer only while the mutation is pending. Measured: Wide parts
    only (a Compact part gives the correct 7 7), plain MergeTree and ReplicatedMergeTree,
    with default alter_sync and no fault injection at all; OPTIMIZE TABLE ... FINAL and
    DETACH/ATTACH do not repair it. The same statement without the ADD leaves b.bin orphaned in
    the part while neither the table nor the part lists the column any more.
  • RENAME a TO b, DROP b, RENAME c TO b with alter_sync = 2 makes the mutation fail permanently with
    Code: 424 ... b.bin already exists and has a different inode ... (CANNOT_LINK), because the retired
    a -> b rename and the live c -> b collide on one destination file.

Version info

  • Merged into: 26.9.1.5 (included in 26.9 and later)

`AlterConversions` recorded a pending drop under the name the `ALTER` command
used, while every consumer of `isColumnDropped` asks about a column under the name
it has in the part: `IMergeTreeReader::isColumnDroppedByPendingMutation` reads it
out of `columns_to_read`, which is built from `getColumnInPart` and so already has
the rename mapping applied, and `injectRequiredColumnsRecursively` passes
`column_name_in_part`. Without a rename the two names are the same, which is why
the hazard those checks were written for — a column dropped and then added again
under the same name, whose data in the part is stale — worked as intended and this
went unnoticed.

With a rename the names differ. After `RENAME a TO b, DROP b, ADD b` the part holds
`a` while the drop is recorded for `b`, so the check asks about `a`, finds nothing,
and the newly added `b` silently returns the dropped column's values instead of its
own default.

Checking the renamed-to name as well would be wrong, because the opposite order
leaves exactly the same state: after `DROP b, RENAME a TO b` the drop hit a
different column that merely had that name and the part's `a` is still live, as
`01281_alter_rename_and_other_renames` requires. The two are only distinguishable
by where the drop sits among the renames, which is information the readers do not
have. So resolve it while the commands are still ordered: a drop is stored under
the name the column has in the part, following the renames recorded so far, which
are exactly those issued before it. Every existing caller already passes a
part-side name, so none of them changes.

The same ordering also has to retire a rename mapping whose source was dropped once
that name is taken over: `RENAME a TO b, DROP b, RENAME c TO b` left two entries
pointing at `b`, from the dropped `a` and from the live `c`, and the lookup returned
whichever came first, so `b` read the wrong column. `master` answers that case with
the dropped column's data and recording the drop part-side alone would answer it with
a default, so both halves are needed to read `c`.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [104d9f5]

Summary: ❌

job_name test_name status info comment
AST fuzzer (arm_asan_ubsan) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb, issue

AI Review

Summary

This PR changes AlterConversions so a pending DROP COLUMN is recorded under the column's part-side name when it follows a pending RENAME COLUMN, and retires the obsolete rename mapping at the same time. The added tests cover the pending-read regression itself, the mirror case where a reused name must still read live data, and the chained target-reuse case. I did not find a new correctness issue in the current diff; the previously discussed wide/full materialization bug in MutateTask remains an acknowledged follow-up and does not contradict this PR's narrower "while the mutation is pending" contract.

Final Verdict

✅ No new blocking findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 9/9 (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 Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 104d9f581 with master 3c3a54e67 (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
Binary Master PR Δ
programs/clickhouse-stripped 705.71 MiB 702.68 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

`RENAME a TO b, DROP b, RENAME c TO b` leaves `rename_map` holding two entries keyed
by `b`, from the dropped `a` and from the live `c`, and the lookup returns whichever
comes first. The previous commit erases the obsolete one, but only where the last
rename appends a new entry. A rename can also reach `b` through a chain, as in
`RENAME c TO d, RENAME d TO b`, which updates the existing `d <- c` entry in place and
never runs the erase, so the two entries survive next to each other again.

Move the erase ahead of the chained lookup so both paths go through it. It cannot
remove the entry that lookup is about to update: that would require
`entry.rename_to == command.column_name == command.rename_to`, which is renaming a
column to the name it already has.

The read of `b` then resolves to the dropped `a`, and because the drop is now recorded
part-side, `a` reads as missing and the part-side name reaches the storage snapshot,
where it no longer exists:

    Code: 16. DB::Exception: There is no column a in table. (NO_SUCH_COLUMN_IN_TABLE)

Reaching it takes `ReplicatedMergeTree`: a single `ALTER` rejects transitive renames,
and `StorageMergeTree::alter` always waits for the previous mutation before a metadata
change, so two of them can never both be pending. The regression test runs the `ALTER`s
with the partition detached and attaches the part carrying the old column names to a
table whose merges are stopped, the same shape as
`03905_chained_rename_column_mutation`.

Co-Authored-By: Claude Opus 5 <[email protected]>
The two previous commits retire the mapping of a dropped column at the moment its
name is taken over by another rename, which put the same `std::erase_if` on both the
appending and the chained path of `RENAME_COLUMN` and left it depending on
`dropped_columns` to tell an obsolete entry from a live one.

Doing it in `DROP_COLUMN` instead is the same thing one step earlier: the drop already
walks `rename_map` to find the name the column has in the part, and that lookup finds
exactly the entry that the drop makes obsolete, so resolving and retiring become one
operation. `RENAME_COLUMN` then has nothing to clean up, because a mapping onto a
dropped name can no longer exist, and the chained path needs no special handling.

Measured equivalent on both paths. All seven cases of
`04872_read_renamed_then_dropped_and_readded_column`, including the chained one added
by the previous commit, pass. On the materialisation path — the mutation run to
completion with `alter_sync = 2` — `RENAME a TO b, DROP b, ADD b`,
`RENAME a TO b, DROP b, RENAME c TO b`, `RENAME a TO b, DROP b` and the chained
Replicated case all give byte-identical results to the previous commit.
`01281_alter_rename_and_other_renames`, `01278_alter_rename_combination`,
`03905_chained_rename_column_mutation`, `04053_alter_add_rename_column_in_single_query`
and `04011_detach_rename_attach_column` pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
@tiandiwonder
tiandiwonder force-pushed the fix-dropped-renamed-column-read branch from 40c63db to 79ca494 Compare August 20, 2026 11:28
Keep the part it changes -- `name` is the part-side name -- and drop the rationale
for it, which belongs in the commit that made the contract explicit.

Co-Authored-By: Claude Opus 5 <[email protected]>

@CurtizJ CurtizJ left a comment

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.

Please fix tests in the private repo. The newly added test has failed.

tiandiwonder and others added 2 commits August 24, 2026 02:01
The case needs a real `ReplicatedMergeTree`: a single `ALTER` rejects transitive
renames, so it stages four of them with the partition detached and re-attaches the
part to keep them pending. The `meta in keeper` lanes run `clickhouse-test` with
`--replace-replicated-with-shared`, which rewrites that engine to `SharedMergeTree`,
where the re-attached part does not carry the pending renames. `b` then resolves to no
file in the part, `injectRequiredColumns` falls back to injecting the part-side name
`c`, and resolving `c` against the table structure fails with `NO_SUCH_COLUMN_IN_TABLE`
-- 5 failures out of 5 runs on those lanes, while every public lane passes.

Give the case its own test tagged `no-shared-merge-tree`, which is what makes the
harness skip a test it would otherwise rewrite. Tagging the whole file would take the
five `MergeTree` cases out of those lanes too, and they are unaffected by the rewrite.
The moved SQL is unchanged.

Verified against a binary without the fix, so the results mean something: with
`--replace-replicated-with-shared` the new test is skipped and the old one still runs,
failing with the symptom the fix targets -- the re-added `b` returning the dropped
`a`'s data.

Co-Authored-By: Claude Opus 5 <[email protected]>
Same-number different-name tests coexist in the suite (`04033_` alone has 231), so the
case that moved out of `04872_read_renamed_then_dropped_and_readded_column` can keep
that number instead of taking a new one. It reads better next to the test it came from,
and leaves 04873 free.

Co-Authored-By: Claude Opus 5 <[email protected]>
@tiandiwonder
tiandiwonder added this pull request to the merge queue Aug 24, 2026
Merged via the queue into master with commit 83fede8 Aug 24, 2026
175 of 177 checks passed
@tiandiwonder
tiandiwonder deleted the fix-dropped-renamed-column-read branch August 24, 2026 09:44
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants