Skip to content

Fix LOGICAL_ERROR on ALTER RENAME COLUMN combined with another command in one statement - #116063

Merged
Algunenano merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-implicit-minmax-index-rename-collision
Aug 24, 2026
Merged

Algunenano merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-implicit-minmax-index-rename-collision

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 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 LOGICAL_ERROR: Index with name auto_minmax_index_<column> already exists when a single ALTER TABLE statement combined RENAME COLUMN with another command, such as MODIFY SETTING, on a table with implicit minmax indices (add_minmax_index_for_numeric_columns and friends). Renaming a plain column also no longer leaves a following DROP COLUMN failing with UNKNOWN_IDENTIFIER, nor a following ADD COLUMN without its implicit index.

Description

ALTER TABLE t (RENAME COLUMN a TO b), (MODIFY SETTING fsync_part_directory = 1) raised a LOGICAL_ERROR on any table with an implicit minmax index for a: an exception in release builds, an abort under debug and sanitizers. No related open issue; surfaced by BuzzHouse (arm_asan_ubsan), STID 3219-3899 (report).

Root cause: an implicit index's name and column_names are derived from its definition_ast, but the RENAME COLUMN branch of AlterCommands::apply replaced only the AST, and both are re-derived only at the end of the statement. Commands apply in order against one accumulating metadata copy, so a later command read the stale record: the MODIFY SETTING refresh missed its name-keyed drop and created a second index on its column_names-keyed add. Both re-derived to one name, which checkProperties rejects.

The fix assigns those two fields where they go stale. name is auto_minmax_index_ plus the new column name by construction. column_names is skipped for ALIAS columns, whose index covers what the expression expands to and is unaffected by the rename.

Two further symptoms are fixed for plain columns: (RENAME a TO b), (DROP COLUMN b) returned UNKNOWN_IDENTIFIER naming an index that no longer existed, and (RENAME a TO b), (ADD COLUMN a) left a without one.

Pre-existing defects here are unchanged and pinned at baseline, since each needs a cached key repaired on an index this branch does not own: an EXPLICIT minmax index on the renamed column, or an ALIAS column whose expression names its own output, leave a following ADD COLUMN of that name unindexed until a reload; and mixing MODIFY SETTING with another command can resurrect an index dropped earlier, or drop one a later ALIAS index shadows.

Regression arms were added to 03748_default_minmax_indices_alter, and validated with 44 base-versus-fix probes covering every intra-statement reader, all column kinds, ten type wrappers and replication.


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

An implicit minmax index's name and column_names are both derived from its
definition_ast by getIndexFromAST, and AlterCommands::apply re-derives them only
after every command in the statement has been applied. The RENAME COLUMN branch
replaced only the AST, so within one statement the record still described the old
column on both keys, and the commands are applied in order against a single
accumulating metadata copy.

A following MODIFY SETTING therefore missed on its name-keyed
dropImplicitIndicesForColumn and created a second index via its
column_names-keyed addImplicitIndicesForColumn. Both records re-derived to the
same name, and MergeTreeData::checkProperties rejected the duplicate with
LOGICAL_ERROR: an exception in release builds, an abort in debug and sanitizer
builds. Found by BuzzHouse (arm_asan_ubsan), STID 3219-3899, on an unrelated
carrier PR:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114054&sha=052eff9243e13d2a88492f793dba153e14f8c119&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29

Assign the two derived keys in that branch. The name is the reserved prefix plus
the new column name by construction. column_names is skipped for ALIAS columns:
getIndexFromAST expands an ALIAS column's expression, gated on
ColumnsDescription::hasAlias, so such an index's column_names holds the
expansion's output name, which never mentions the alias and is therefore
unaffected by the rename. Writing the new column name there instead would claim
the index covers a column it does not, and stop it suppressing a same-named
column's own implicit index.

Two further symptoms of the same stale keys are fixed. (RENAME a TO b),
(DROP COLUMN b) returned UNKNOWN_IDENTIFIER quoting auto_minmax_index_a, an index
that no longer existed, because the name-keyed drop missed and the surviving index
outlived its column; it now succeeds, matching the contract that implicit indices
must not prevent ALTERs. (RENAME a TO b), (ADD COLUMN a) silently left the new
column without an implicit index until the table was reloaded.

Three pre-existing defects are deliberately left unchanged and pinned at baseline
by the validation matrix, since none of them forms a duplicate name and each would
require repairing an explicit index's cached keys mid-statement: an explicit
minmax index on the renamed column still leaves a following ADD COLUMN of the old
name unindexed until a reload; a statement mixing MODIFY SETTING with another
command still resurrects an implicit index dropped by an earlier statement; and
that refresh still drops an implicit index whose name a later column's ALIAS index
shadows.

Validated with 44 base-versus-fix probes covering every intra-statement reader,
all six column kinds, ten type wrappers and the replicated path, plus three
mutation controls showing each part of the change is load-bearing. Regression arms
were added to 03748_default_minmax_indices_alter, which aborts the server without
this change.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 24, 2026
@groeneai

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

Two independent cold review passes ran against this diff before publication. Both raised one
finding; I disagreed with both after tracing the code, and recorded why. Verdicts below.

# Finding Verdict
❌ An ALIAS column whose expression names its own output, e.g. al Int32 ALIAS (a + 1 AS al), keeps column_names = {"al"} across the rename, so a following ADD COLUMN al is suppressed and the new physical column gets no implicit index. Correct as a fact, but pre-existing and not caused here. The hasAlias guard skips the column_names assignment for that column, so this branch writes only name, and the ADD COLUMN path reads column_names alone. Before this change the field was not written either, so base and fix compute the identical record for that statement. Repairing it means rewriting a cached key on an index this branch does not own, which was measured and rejected during design. Now disclosed in the description alongside the other pre-existing cases.
⚠️ The last regression arm still passes when the fix is reverted, so it is not live. Correct, and intended. That arm is a non-regression arm: (MODIFY COLUMN a String), (RENAME COLUMN al TO al2), (MODIFY COLUMN a Int32) pins that the fix does not analyse an ALIAS column while a sibling command has its underlying column transiently String, which is a failure an earlier design produced. Its contract is to stay green, so reddening on revert would contradict its purpose. ALIAS liveness is covered by the third arm, which aborts before the fix and passes after. Removing this arm would drop a real guard.
💡 DROP INDEX and ADD INDEX ... AFTER also resolve an index by name inside the same statement, so the reader list in my notes was two entries short of complete. Noted. Both move in the same direction as the described DROP COLUMN change, since after the rename the new name is the one that exists. Neither is a new failure mode and neither is claimed as fixed.

The first finding did falsify one clause of my draft changelog, which had claimed the
ADD COLUMN symptom was fixed without qualification. That claim is now scoped to plain
columns, and the output-alias case is listed with the other untouched pre-existing defects.

Session id: cron:clickhouse-review-slot-9:20260824-063800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (c0 Int32, c2 Int32) ENGINE = MergeTree ORDER BY tuple() SETTINGS add_minmax_index_for_numeric_columns = 1; then ALTER TABLE t (RENAME COLUMN c2 TO c13), (MODIFY SETTING fsync_part_directory = 1);. Aborts every time on a debug build; no randomization needed. The oracle is the exit code plus the system.data_skipping_indices list, since the LOGICAL_ERROR text reaches neither stdout nor stderr under clickhouse local.
b Root cause explained? Yes. An implicit index's name and column_names are derived from definition_ast by getIndexFromAST, and both are re-derived only at the end of AlterCommands::apply. The RENAME COLUMN branch replaced only the AST, so inside one statement the record described the old column on both keys. MODIFY SETTING's refresh then missed its name-keyed dropImplicitIndicesForColumn and created a second index via its column_names-keyed addImplicitIndicesForColumn; both re-derived to one name, which MergeTreeData::checkProperties throws on. Pinned by P1 and not P2 (rename alone is correct), P2 and not P3 (order matters), P2 and not P4 (one statement only), and G1 (reproduces with a single index, so no index reordering is involved).
c Fix matches root cause? Yes. It assigns the two stale keys at the point they go stale, in the same branch. No widened bound, no no-random-* tag, no data reduction, and no guard at the throw site: the LOGICAL_ERROR in checkProperties remains a true internal invariant.
d Test intent preserved / new tests added? Yes. Six arms appended to 03748_default_minmax_indices_alter. The pre-existing reference is a byte-exact prefix of the new one, so no arm was deleted or weakened. Arms cover the abort (numeric, String, Date), the ALIAS-column carrier, the DROP COLUMN relaxation, the ADD COLUMN reader, and one non-regression statement.
e Both directions demonstrated? Yes. clickhouse local: base RC=134, fix RC=0 with the expected two indices. Server side, the committed test aborts a server built from pristine HEAD with the verbatim CI text Logical error: 'Index with name auto_minmax_index_c13 already exists' (abort log build id matches the base binary) and passes on the fixed build. 50 of 50 randomized runs pass.
f Fix is general across code paths? Yes. All four intra-statement readers were enumerated and each measured: the MODIFY SETTING refresh (17 carriers now returning 0), DROP COLUMN (Code 47 becomes success), ADD COLUMN (the new column is now indexed), and the virtual-column pair (an index alias named _block_number, and all virtual flags on). Fixed at the source rather than at any reader. ReplicatedMergeTree and SharedMergeTree share AlterCommands::apply, so both are covered by the same edit; the replicated path is verified by 03305_rename_with_implicit_index_replicated and 00837_minmax_index_replicated_zookeeper_long against real ZooKeeper. ReplicatedMergeTreeTableMetadata's own all-columns loop runs on freshly parsed metadata with no rename in flight, so it is not a carrier and is untouched. Projections build their own metadata and never rename.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. All six column kinds measured: plain, MATERIALIZED, DEFAULT, ALIAS <expression>, ALIAS <bare identifier> and EPHEMERAL. Ten type wrappers renamed in one fixture (Nullable, LowCardinality(String), LowCardinality(Nullable(String)), Array, Map, DateTime64, Decimal, UUID, Enum8, Float64): base aborts, fix returns 0 with output byte-identical to DETACH/ATTACH ground truth. The wrapped types get no implicit index at all, because the add-side predicates isNumber/isString/isDateOrDate32OrTimeOrTime64OrDateTimeOrDateTime64 do not strip wrappers, so this branch cannot fire for them and the coverage is complete by construction rather than by omission. All three type flags and both alterable virtual flags are independent triggers and each was measured; multi-column minmax is covered too.
h Backward compatible? Yes. No setting default changed, no new setting, no serialization or on-disk format change, so no SettingsChangesHistory.cpp entry and no experimental gate. Implicit indices are not persisted (IndicesDescription excludes them from the serialized AST and they are recreated at load), so nothing on disk is reinterpreted and ATTACH is unaffected, verified by DETACH/ATTACH rounds. The one behaviour change is a relaxation: (RENAME a TO b), (DROP COLUMN b) no longer returns UNKNOWN_IDENTIFIER naming an index that did not exist.
i Invariants and contracts preserved? Yes. The invariant is that an IndexDescription's name must agree with its definition_ast at every point another command in the same apply can read it, and that no command may key the implicit-index set off a field the rename leaves stale. The edit makes the record self-consistent earlier than before. expression, sample_block and data_types stay deferred to the end-of-batch reparse, which is the subsystem's designed behaviour and is what the deferred-validation non-regression arms protect. type and is_implicitly_created are rename-invariant. Two string assignments on a local metadata copy, so no lock, allocation or concurrency contract is involved, and any throw still discards the copy leaving live metadata untouched. The IF EXISTS early return precedes this loop and is unchanged. No crash or restart re-entry obligation: the state is in-memory within one call, and implicit indices are not persisted.

Session id: cron:clickhouse-impl-slot-40:20260824-054900

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [11945f2]

Summary: ✅


AI Review

Summary

This PR repairs the renamed column's own implicit minmax index inside AlterCommands::apply, which addresses the direct duplicate-name failure. One correctness gap still remains: when a different implicit ALIAS index still expands through the old plain-column name, a following ADD COLUMN in the same ALTER can still suppress the new column's implicit index. Verdict: request changes.

Findings

❌ Blockers

  • [src/Storages/AlterCommands.cpp:1275] The rename branch only refreshes the implicit index owned by the renamed column. A case like CREATE TABLE t (value Int32, al Int32 ALIAS value > 0) ENGINE = MergeTree ORDER BY tuple() SETTINGS add_minmax_index_for_numeric_columns = 1; ALTER TABLE t (RENAME COLUMN value TO value2), (ADD COLUMN value Int32); still leaves the new value column without auto_minmax_index_value: auto_minmax_index_al keeps cached column_names = {'value'} until the final reparse, and StorageInMemoryMetadata::addImplicitIndicesForColumn treats that stale cache as proof that a minmax index for value already exists. Suggested fix: when renaming a plain column, also refresh any implicit index whose cached column_names still mention column_name, or stop using stale column_names for same-statement duplicate detection.
Tests
  • ⚠️ Add a focused stateless regression arm that renames a plain column still referenced by an implicit ALIAS index and then re-adds the old name, asserting that system.data_skipping_indices contains auto_minmax_index_value.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix the remaining alias-shadowed ADD COLUMN case above and add the focused regression test.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 6/6 (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 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @Algunenano, could you review this? An implicit minmax index derives its name and column_names from its definition AST, but the RENAME COLUMN branch of AlterCommands::apply replaced only the AST and both are re-derived at the end of the statement, so a second command in the same ALTER read the stale record and produced a duplicate index that checkProperties rejects with a logical error.

index.name = IMPLICITLY_ADDED_MINMAX_INDEX_PREFIX + rename_to;
/// For an ALIAS column the index covers the columns its expression expands to,
/// which the column's own name never appears in, so a rename does not affect them.
if (!metadata.columns.hasAlias(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.

This still leaves stale column_names on other implicit indices that expand through column_name. A concrete case is:

CREATE TABLE t
(
    `value` Int32,
    `al` Int32 ALIAS value > 0
)
ENGINE = MergeTree
ORDER BY tuple()
SETTINGS add_minmax_index_for_numeric_columns = 1;

ALTER TABLE t
    (RENAME COLUMN value TO value2),
    (ADD COLUMN value Int32);

After the rename, auto_minmax_index_value is repaired here, but auto_minmax_index_al still carries column_names = {'value'} until the final reparse because the else branch only rewrites its definition_ast. StorageInMemoryMetadata::addImplicitIndicesForColumn uses index.column_names.front() == column.name to detect an existing minmax index, so the later ADD COLUMN value arm suppresses the new column's implicit index and the table finishes without auto_minmax_index_value.

To make the ADD COLUMN part of the fix hold for plain-column renames, the rename path needs to refresh any implicit index whose cached column_names still mention column_name, not only the renamed column's own index. A focused regression arm for the case above would catch it.

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.

I ran your fixture on this head and on pristine master. The outcome you predict happens on master, not here.

After the ALTER, with both implicit indices confirmed created first:

master cc7cb8c3 this head 7d9ccfa5 reload ground truth
auto_minmax_index_al value2 > 0 value2 > 0 value2 > 0
auto_minmax_index_value absent value value
auto_minmax_index_value2 value2 value2 value2

So the new value does get its implicit index, and the in-memory list already matches DETACH/ATTACH.

auto_minmax_index_al is not the suppressor. Delete the ALIAS column and run the same ALTER on (value Int32) alone: master still leaves the new value unindexed. The colliding key belongs to the renamed column's own index, which is the one this patch assigns.

The premise about the alias index's cached key is also inverted. Add a column named greater(value, 0) instead and it is the one that goes unindexed on both builds, because ReplaceAliasByExpressionMatcher runs before the sample_block that column_names is derived from, so an ALIAS expression index caches the expansion's output name rather than value. It cannot suppress a column called value. The in-code comment at StorageInMemoryMetadata.cpp:975-979 says otherwise and is wrong on that point.

Causally, removing just the column_names = {rename_to} line from this patch reproduces your predicted output exactly, while removing either the name assignment or the hasAlias guard leaves this arm green. That line is the repair.

I also tried the sharpest version of the general claim, al Int32 ALIAS value, where the expansion output name genuinely is value: master leaves the new column unindexed, this head indexes it.

Coverage exists: arm 5 of 03748_default_minmax_indices_alter.sql is (RENAME COLUMN c2 TO c13), (ADD COLUMN c2 Int32), the same reader, without the ALIAS column that plays no causal role.

On the suggested remedy, refreshing every implicit index whose cached column_names mention the old name was measured during design and dropped. Re-keying an index this branch does not own either mis-keys multi-column and alias indices, or re-analyses an ALIAS expression against intermediate column state and fails a valid statement with Code: 43.

No change here.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 11945f2d5 with master 94a155312 (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 708.92 MiB 705.88 MiB -3.04 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, 15 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 11945f2

CI is fully finished at this commit and no check failed, so no ledger row is owed.

Evidence: 175 unique check runs (156 success, 19 skipped, 0 failures) with pagination complete
(182 of 182); Config Workflow, Style check and Finish Workflow all green; the praktika report
root is OK with 156 OK plus 18 SKIPPED nodes and none DROPPED; and CIDB independently
returns zero FAIL/ERROR rows at this exact 40-char commit against a 301,647-row control.

Session id: cron:our-pr-ci-monitor:20260824-133010

@Algunenano Algunenano self-assigned this Aug 24, 2026
@Algunenano
Algunenano added this pull request to the merge queue Aug 24, 2026
Merged via the queue into ClickHouse:master with commit d659d17 Aug 24, 2026
186 of 187 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 27, 2026
…ated lanes

05060_database_max_tables_rename_inner_tables,
03748_default_minmax_indices_alter and
04757_alter_modify_projection_settings fail the main pass of
Stateless tests (amd_llvm_coverage, s3 storage, DBReplicated, parallel, 2/3)
on every master commit, and the check still reports OK: 1023 whitewashed rows
over 7 days (341 each, 100% of their rows on that lane, 0 red). The lane's
DIAGNOSTICS stage reruns a failed test without --replicated-database, the
rerun passes, the test is labelled flaky, and llvm_coverage jobs force flaky
to OK.

Two intended DatabaseReplicated refusals are involved.
DatabaseReplicated::renameTable throws NOT_IMPLEMENTED (48) for a
cross-database RENAME before any existence check, so all 7 assertion arms of
05060 get 48 where they expect 724 TOO_MANY_TABLES.
validateReplicatedDatabaseSegments refuses one ALTER that mixes replicated and
non-replicated command kinds with QUERY_IS_PROHIBITED (392), and it runs
before every storage-level check, which is why 04757's mixed arm reports 392
instead of the 344 SUPPORT_IS_DISABLED it asserts.

Applying the tag-vs-split rule of ClickHouse#121863, which tags a whole file when the
refused statement is the file's subject and splits the refused minority out
otherwise:

- 05060: whole-file no-replicated-database tag. 7 of 7 arms are refused and
  the cross-database RENAME of a table group is the file's entire subject. Its
  siblings 04498_database_max_tables and
  05042_rename_full_database_error_order are tagged in ClickHouse#121863 with the same
  reason string.
- 03748: 4 of 14 assertion blocks are refused, split into
  05244_default_minmax_indices_alter_rename_with_setting. A whole-file tag
  would have made a coverage regression permanent, because the file had 1303
  clean rows on this lane until the week those four arms were added.
- 04757: 1 of 8 error arms is refused, split into
  05245_alter_modify_projection_fixed_granularity_guard. The settings-only arm
  stays in the parent: a lone MODIFY SETTING makes
  areNonReplicatedAlterCommands true, so it is not refused and reaches the
  storage guard that raises the SUPPORT_IS_DISABLED it expects.

Every moved statement is carried over verbatim, so no assertion is weakened.
A fixture rewrite was rejected for 03748 because the combined
(RENAME COLUMN), (MODIFY SETTING) shape is itself the regression under test
from ClickHouse#116063: a following settings ALTER is what re-derives the implicit
index's name-keyed entries, so splitting the statement in two would have
silently deleted that coverage.

Both changed references were regenerated with clickhouse-test --record. The
03748 reference loses exactly the 19 lines of the moved blocks and nothing
else; 04757's reference is byte-identical; 05245's is empty because its only
statement is a serverError arm.

Validated on a single-node Replicated rig with the master snapshot binary
26.10.1.1: before the change each test fails deterministically under
--replicated-database (48, 392, 392) and passes without it; after it, the
three tagged tests report SKIPPED with reason replicated-database while 03748
and 04757 pass on the lane for the first time. Misspelling a tag makes the
test run and fail again with the original code, which proves the skip comes
from the tag. 50 randomized runs of each test without the flag and 20 with it
produced no failure other than the local Code: 36 Invalid time zone
environment class.

Related: ClickHouse#121863

Co-Authored-By: Claude Opus 5 <[email protected]>
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 groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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