Skip to content

Fix an ALTER through an Alias table overwriting enum values added concurrently to its target - #130528

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-alias-alter-prepare-under-target-lock
Nov 13, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-alias-alter-prepare-under-target-lock

Conversation

@groeneai

@groeneai groeneai commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #130322

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 ALTER TABLE ... MODIFY COLUMN ... ADD ENUM VALUES executed through an Alias table overwriting the enum values that a concurrent ALTER of the target table had added. Both queries succeeded, but the target's values were lost, and with enable_shared_storage_snapshot_in_query = 0 the target table could no longer be attached after a restart.

Description

On 26.10.2.103, two concurrent ALTER TABLE ... MODIFY COLUMN e ADD ENUM VALUES (...), one through an Alias table and one on its target, both succeed, but the values added on the target are lost. With enable_shared_storage_snapshot_in_query = 0 the target also gets a MODIFY COLUMN mutation written without a type, and after a restart the table cannot be attached (MODIFY COLUMN mutation command doesn't specify type, LOGICAL_ERROR). Found while answering #130322 (comment).

Root cause: InterpreterAlterQuery validates and prepares the commands under the alias's locks, and StorageAlias::alter locks the target only afterwards. For ADD ENUM VALUES, AlterCommands::prepare stores the merged enum type, computed from the column type read before that lock, so it overwrites any value that a direct ALTER of the target committed in between.

Change: after locking the target, StorageAlias::alter clears the query metadata cache (as #130322 does), prepares a copy of the commands again against the target's current metadata and runs the target's checkAlterIsPossible on it. Without it, the target's alter compares the new type with metadata cached before that lock, and writes an untyped mutation when a concurrent ALTER dropped enum values. prepare gives createEnumAdd a copy of the ADD ENUM VALUES list, which it numbers in place, so a second prepare still sees them as implicit. validate still runs before that lock, as it needs unprepared commands.

Validation: 05618 races 20 ADD ENUM VALUES through an Alias against 20 on the target (master loses the target's values in 10 of 10 runs) and against 20 ALTERs replacing the target's enum (19 untyped mutations per run without the clear). With the fix it passes 50 of 50 randomized runs. 05619 checks that values added without a number through an Alias follow the target's largest value. Also checked: ReplicatedMergeTree and Memory targets, and a restart on raced data.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2166-master (included in 26.11 and later)

`InterpreterAlterQuery` validates and prepares the commands under the
alias's own DDL guard and alter lock, and `StorageAlias::alter` only then
locks the target. `AlterCommands::prepare` stores the complete merged type
for `MODIFY COLUMN ... ADD ENUM VALUES`, computed from the column type read
before the target was locked, so an `ADD ENUM VALUES` executed directly on
the target while the alias ALTER waited for its lock was overwritten. Both
ALTERs succeeded, the target's values were lost, and with
`enable_shared_storage_snapshot_in_query = 0` the overwrite dropped enum
values, so the target started a `MODIFY COLUMN` mutation serialized without
a type: the table could not be attached after a restart (LOGICAL_ERROR).

Copy the commands, prepare them against the target's current metadata
(bypassing the query metadata cache) and run the target's
`checkAlterIsPossible` under the target's alter lock, as
`StorageMaterializedView::alter` does for its inner table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

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

Pre-publication review by an independent model (engine: codex; 4 findings) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 ❌ At enable_shared_storage_snapshot_in_query = 1 a concurrent ADD COLUMN on the target is still lost, because StorageMergeTree::alter reads the query cache's pre-lock copy DISAGREE (separate PR) Same on master without this change (53 of 101 columns kept at setting 1); the enum values this PR is about are all kept in the reviewer's own run. The cache clear after the target's lock is #130322, at this same spot.
2 ❌ A second prepare keeps an ignore set by MODIFY COLUMN IF EXISTS before the column appeared DISAGREE prepare only ever sets ignore, so this forwards the same skip as before. The result equals running the alias ALTER first, and the concurrent ADD COLUMN is kept.
3 ⚠️ The race test may pass without the fix DISAGREE Without the fix it failed 13 of 13 runs (both settings, and randomized through the runner), each keeping at most 2 of the 20 target values.
4 💡 Use Critical Bug Fix DISAGREE That category is left to maintainers to request.
5 💡 The re-run checkAlterIsPossible reads through the query cache at setting 1 Noted It reads the same copy the target's alter reads (the #130322 half); not blocking.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261110-140200

@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7335498]

Summary: ✅


AI Review

Summary

This PR prevents concurrent ALTER operations through an Alias from overwriting enum values or persisting malformed mutations. It refreshes the query caches and prepares commands against current target metadata under the target lock, while preserving implicit enum numbering across preparation passes. Both earlier findings are addressed, and no new findings remain. The added concurrency and implicit-numbering regression tests passed in the Fast test report for the reviewed head, 7335498774f0. No tests were run locally.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05618 (20 ADD ENUM VALUES through an Alias racing 20 on the target) fails on the unfixed build in 5 of 5 runs at the default settings and 5 of 5 with enable_shared_storage_snapshot_in_query = 0, under 1 s per run.
b Root cause explained? InterpreterAlterQuery prepares the commands under the alias's locks; StorageAlias::alter locks the target later. prepare stores the merged enum type from the pre-lock column type, so apply overwrites values a direct ALTER of the target committed in between. With the setting at 0 the dropped values also start a MODIFY COLUMN mutation serialized without a type.
c Fix matches root cause? Yes. The commands are prepared again, and checked, against the target's committed metadata under the target's alter lock, the order the direct path already uses.
d Test intent preserved / new tests added? New test 05618 (an Alias and an Alias of an Alias; asserts every value is kept and no mutation is created). No existing test changed.
e Both directions demonstrated? Unfixed: 10 of 10 runs lose the target's values (20 mutations per case at setting 0). Fixed: 10 of 10, 50 of 50 randomized, and 20 + 20 with the setting forced to 0 and 1, all pass.
f Fix is general across code paths? Of the places that forward commands to another table's alter, only StorageAlias::alter forwards a type derived from metadata read under a different lock: StorageMaterializedView::alter forwards only comments and checks them under the inner table's lock; StorageProxy forwards to its own nested storage. Alias chains recurse through the fix (tested).
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked Enum8, Enum16, Nullable(Enum8), Nullable(Enum16), a sorting-key Enum8; MergeTree, ReplicatedMergeTree and Memory targets; two ADD ENUM VALUES in one statement; IF EXISTS; both setting values and randomized settings.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or lock-order change; sequential ALTERs through an Alias give byte-identical results before and after.
i Invariants and contracts preserved? An ALTER's commands are prepared and checked against the table they change, under that table's alter lock. The second prepare and checkAlterIsPossible run before the target's alter, so an exception leaves the target untouched; a second prepare can only set ignore, never clear it.

Session id: cron:clickhouse-impl-self-slot-57:20261109-163500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @tavplubix, could you review this and add the can be tested label so CI runs? An ALTER through an Alias prepares its commands before StorageAlias::alter locks the target, so ADD ENUM VALUES wrote back an enum type merged from the pre-lock column and dropped the values a concurrent ALTER of the target had added; the fix prepares a copy of the commands again against the target's metadata under the target's alter lock.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). labels Nov 10, 2026
Comment thread src/Storages/StorageAlias.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 733549877 with master 816b8458e (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

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

5 object files changed (+35.23 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageAlias.cpp.o 566.28 KiB 596.51 KiB +30.23 KiB (+5.34%)

711 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.61, programs/clickhouse-keeper ×0.67 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 13.2 s +9.6 s (+270%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.2 s +5.0 s (+236%)
Compile time of recompiled translation units

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

Job report

groeneai and others added 2 commits November 10, 2026 18:14
`createEnumAdd` rewrites the elements written without a number into
`'name' = N` in place, and the relative meaning of `N` survives only in
the temporary enum type. `AlterCommands::prepare` passed it the command's
own AST, so a second `prepare` of the same commands, which
`StorageAlias::alter` now does under the target's lock, read `N` as an
explicit number: `ADD ENUM VALUES ('new')` through an `Alias` of a column
`Enum8('old' = 10)` committed `'new' = 1` instead of `'new' = 11`, and
with `'old' = 1` it was refused with `BAD_ARGUMENTS`. Give `createEnumAdd`
a copy instead.

Found by the automated review of ClickHouse#130528.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`SharedMergeTree` records even a metadata-only `ALTER` in
`system.mutations`, so the test's zero-mutation check cannot hold there
(same note as in `04307_add_to_enum`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim PedroTadim self-assigned this Nov 12, 2026
Comment thread src/Storages/StorageAlias.cpp Resolved
PedroTadim and others added 2 commits November 12, 2026 12:19
…its target

The commands are prepared again against the target's current metadata, but
`checkAlterIsPossible` and the target's `alter` then read the metadata the
query cached before the target's lock (`enable_shared_storage_snapshot_in_query = 1`).
When a concurrent ALTER of the target dropped enum values in between, the
re-prepared `ADD ENUM VALUES` looked like a type change against that stale copy
and was persisted as a mutation without a type, so the table could no longer be
attached (`MODIFY COLUMN mutation command doesn't specify type`).

`QueryMetadataCache::clear` and the clear in `StorageAlias::alter` are the same
as in ClickHouse#130322.

05618 gains a case where the target's enum is replaced concurrently.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 6036d47 Nov 13, 2026
203 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 13, 2026
The clear in `StorageAlias::alter` that 05617 tested now comes from ClickHouse#130528,
and its test 05618 fails without that clear as well (19 mutations instead of 0,
5 of 5 runs; 05617 gives 21 columns instead of 41).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... and removed comp-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). labels Nov 22, 2026
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-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... 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