Repository navigation
Fix a renamed and dropped column being read from the wrong file while the mutation is pending - #114601
Conversation
`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]>
|
Workflow [PR], commit [104d9f5] Summary: ❌
AI ReviewSummaryThis PR changes Final Verdict✅ No new blocking findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units7 translation units recompiled, 12 s compile time in total, 7 of them have a recent master baseline. |
`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]>
40c63db to
79ca494
Compare
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
left a comment
There was a problem hiding this comment.
Please fix tests in the private repo. The newly added test has failed.
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]>
Related: #114562
Problem
A column that is renamed, dropped and added again in one
ALTERsilently returns the droppedcolumn's data instead of its own default, while the mutation is still pending:
No error and nothing in the log; it affects
WideandCompactparts alike. The addedbis adifferent 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
Widepart still returns the dropped column's data — a separate, pre-existing defect that lives inMutateTask, see the follow-ups at the end.Root cause
AlterConversionsrecords a pending drop under the name the command used:while every consumer of
isColumnDroppedasks about a column under the name it has in the part:IMergeTreeReader::isColumnDroppedByPendingMutationtakes the name out ofcolumns_to_read, which isbuilt from
getColumnInPartand therefore already has the rename mapping applied(
IMergeTreeReader.cpp:81);injectRequiredColumnsRecursivelypassescolumn_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 forb, thecheck asks about
a, finds nothing, and the reader streams theafile into the newb.Solution
Consume the ordering in
DROP_COLUMN, where both halves of it are needed anyway. Commands arrive asissued, 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:
Every existing caller of
isColumnDroppedalready passes a part-side name, so all of them become correctat once and none of them changes.
Retiring the mapping matters on its own.
RENAME a TO b, DROP b, RENAME c TO bused to leave twoentries pointing at
b— from the droppedaand from the livec— and the lookup returns whichevercomes first, so
bread the wrong column. Writing aRenamePairasto <- from, wheretois the namein the metadata and
fromthe name in the part, and remembering thatdropped_columnsnow holdspart-side names:
rename_mapdropped_columnsRENAME a TO b[b <- a]{}DROP bb <- agives the part'saand is erased in the same step[]{a}RENAME c TO bbis free, insert[b <- c]{a}getColumnOldName("b")then answersc, andastays dropped so nothing reads it. Both halves areneeded to get this right:
min(b), max(b), want5000 5999master100 1099— the dropped column's data0 0— the default5000 5999✔Why in the drop and not when the name is taken over
Retiring the entry in
RENAME_COLUMNinstead — erase whatever maps onto the new target and is alreadydropped — 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 bupdates the existingd <- centry in place rather than appending, so anerase placed on the appending path alone leaves
[b <- a, b <- c]again. That variant does not misread —it fails outright, because
bresolves to the droppedaand the part-side name reaches the storagesnapshot:
Reaching it takes
ReplicatedMergeTree: a singleALTERrejects transitive renames(
Transitive renames in a single ALTER query are not allowed), andStorageMergeTree::alteralwayswaits for the previous mutation before a metadata change (
StorageMergeTree.cpp:548, "alters should beexecuted 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_COLUMNhas nothing to clean up and the chained path needsno special handling. The two were measured equivalent on both the read path (all of
04872) and thematerialisation path (the mutation run to completion with
alter_sync = 2forRENAME a TO b, DROP b, ADD b,RENAME a TO b, DROP b, RENAME c TO b,RENAME a TO b, DROP band thechained 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
AlterConversionsstate, and01281_alter_rename_and_other_renamesalready pins the required behaviour for it:
Here the drop hit a different column that merely carried that name, and
value2's data is live andmust be readable as
value2_old. The only thing separating the two situations is where the drop sitsamong the renames, which the readers cannot see. Measured with the reader-side variant applied, live
data is replaced by defaults:
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: thedefect on
Wideand onCompact, theRENAME/DROP/RENAMEcase above and its chained variant, plusthree 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 theold 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 isload-bearing: with the retirement placed on the appending path of
RENAME_COLUMNit fails withNO_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:
master1000 100 1099✗1000 100 1099✔1000 7 7✔1000 0 0✗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_queryand04011_detach_rename_attach_columnall pass.Notes for reviewers
The retirement relies on the command sequence reaching
AlterConversionswithout gaps, and it does.Metadata mutations are exempt from every
paramsswitch —needIncludeMutationToSnapshot(
MergeTreeData.cpp:653, "Metadata mutations must be included into the snapshot regardless of theparameters") and
addSupportedCommands(MergeTreeData.cpp:704) both admitRENAME_COLUMNandDROP_COLUMNunconditionally, so no caller can ask for a snapshot holding the renames but not thedrops. Per-part filtering then takes a contiguous suffix, never a middle slice: both
getOnFlyMutationCommandsForPartimplementations walk in reverse and stop at the first mutation ator below the part's version (
StorageMergeTree.cpp:3549,ReplicatedMergeTreeQueue.cpp:2355). A gapwould need
RENAME a TO bin the window withDROP bcut 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_versionwhile testingalter_version, so the suffix iscontiguous 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 onetryMultithat also carries
set /metadatawith a CAS on the current metadata version(
StorageReplicatedMergeTree.cpp:7001, andalter_versionis that version plus one) andset /mutationswith a CAS on its own version. Either CAS makes two of them serialise, and the sequentialnumber 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 — leavesalter_versionat-1and is handled by the loop's other branch. Confirmed by reading the raw znodesthrough
system.zookeeper: withALTER UPDATEs interleaved between the renames the metadatasubsequence is
1, 2, 3, 4in znode order, and ten concurrent renames from separate clients land asalter_version1..9matching the znode sequence exactly.isColumnDroppednow consistently answers about part-side names. That matches all four existing callsites, 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 itsrenamed-to name and testing the drop under that, so that a single-statement
RENAME a TO b, DROP bisrecognised 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 isdeliberately 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,04011and01281_alter_rename_and_other_renamesall still pass, so the cleanup is safe.Changelog category (leave one):
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
ALTERreturning 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
MutateTaskrather thanAlterConversions, and were measured identicalon 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 7still returns1000 100 1099after the mutation hasmaterialised. This PR fixes the answer only while the mutation is pending. Measured:
Widepartsonly (a
Compactpart gives the correct7 7), plainMergeTreeandReplicatedMergeTree,with default
alter_syncand no fault injection at all;OPTIMIZE TABLE ... FINALandDETACH/ATTACHdo not repair it. The same statement without theADDleavesb.binorphaned inthe part while neither the table nor the part lists the column any more.
RENAME a TO b, DROP b, RENAME c TO bwithalter_sync = 2makes the mutation fail permanently withCode: 424 ... b.bin already exists and has a different inode ... (CANNOT_LINK), because the retireda -> brename and the livec -> bcollide on one destination file.Version info
26.9.1.5(included in26.9and later)