Skip to content

Cherry pick #104822 to 26.3: Fix race between ALTER RENAME COLUMN and merge causing data loss (#80648) - #109320

Merged
robot-ch-test-poll2 merged 30 commits into
backport/26.3/104822from
cherrypick/26.3/104822
Jul 3, 2026
Merged

robot-ch-test-poll2 merged 30 commits into
backport/26.3/104822from
cherrypick/26.3/104822

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #104822

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 29 commits May 13, 2026 10:39
Reported in #80648 by @Avogar (RCA) and reproduced by @zlareb1 via
`ClickFawkes` at 2-6 attempts per 100 with concurrent execution.

In `StorageMergeTree::alter`, `setProperties` publishes the new
in-memory metadata (with the renamed column) before `startMutation`
registers the rename mutation in `current_mutations_by_version`.
A background merge picked up in that window observes the new column
name (`d1`) but does not see the pending rename mutation, so its
`mutations_snapshot` carries no `AlterConversions` for it. The merge
then reads the old parts using the new name `d1`, finds no on-disk
file, and fills the new column with default values. The subsequent
rename mutation runs on the merged part, sees no `d` column to
rename, and is a no-op — the renamed column's data is gone.

The fix holds `currently_processing_in_background_mutex` across both
`setProperties` and the mutation registration, so the merge-selecting
thread (and the merge task's later `getMutationsSnapshot` call) only
ever observe a consistent pair of (in-memory metadata, pending
mutations). Without the fix the regression test triggers data loss
on ~20% of iterations; with the fix it passes 200/200.

A new private overload `startMutation(commands, query_context, lock)`
performs the mutation-registration steps assuming the caller already
holds the lock, so the existing locking inside `startMutation` is
preserved for the public overload.

Closes #80648
Address reviewer feedback from `clickhouse-gh[bot]` on PR #104822:
`wait "$pid_alter" "$pid_optimize"` only returns the status of the last
PID in Bash. If `ALTER` failed but `OPTIMIZE` succeeded, the iteration
would silently pass and the regression signal would be weakened.

Split the call into two separate `wait`s and capture each exit status,
then fail the iteration if either side exited non-zero. `set +e` is
used around the wait block so we can report both statuses in the
failure message instead of bailing on the first one.

Bot review: #104822 (comment)
PR #104822 review (clickhouse-gh[bot]) pointed out that delegating the
public `StorageMergeTree::startMutation` overload to the private (alter)
overload via `std::lock_guard lock(currently_processing_in_background_mutex);
return startMutation(commands, query_context, lock);` had widened the lock
scope of the regular `mutate` path: every mutation submission was now
holding `currently_processing_in_background_mutex` for the full duration
of `MergeTreeMutationEntry::commit` (`writeFile` + `sync` + `moveFile`
on disk), blocking background merge selection and other users of the
mutex for the file I/O duration. The original critical section guarded
only `current_mutations_by_version` insertion and mutation counters.

Restore the previous narrow critical section in the public overload:
the entry's file I/O happens outside the mutex, and only the in-memory
state update (`current_mutations_by_version.try_emplace` and
`incrementMutationsCounters`) stays inside it.

The private (alter-only) overload is unchanged: the caller holds the
lock throughout `setProperties` and the mutation registration so the
two operations appear atomic to background merge selection — that is
the correctness guarantee that fixes #80648, and it is preserved here.
File I/O under the wide lock on the alter path is acceptable because
`ALTER` is rare and the atomicity is required for correctness.

Regression test `04238_alter_rename_column_merge_race.sh` continues to
pass 100/100 iterations with this change.

Bot inline review: #104822 (comment)
The regression test for the `ALTER RENAME COLUMN` + merge race
(04238_alter_rename_column_merge_race) was timing out under sanitizer
builds (TSan ~20x slower than Debug, MSan/ASan+UBSan ~3-5x): each
iteration spawns `clickhouse-client` 7 times for setup and the loop
ran 100 times, so under TSan the test consistently exceeded the
600s per-test timeout in flaky-check runs.

Two changes that preserve the regression signal:

1. Lower `ITERATIONS` from 100 to 50. At the observed 2-6%
   per-attempt race rate on the buggy master, a single run misses
   the regression with probability between ~5% (at the 6% high
   end) and ~36% (at the 2% low end), so each sanitizer/build
   variant catches the bug 64-95% of the time. We run on 4+ build
   variants with multiple flaky-check repeats, which drives the
   combined miss probability deep into the noise.

2. Batch DROP / CREATE / 5x INSERT into a single `clickhouse-client`
   invocation per iteration. Each `INSERT` statement still creates
   its own part (semantics unchanged), but the per-iteration cost
   drops by ~6x process spawns.

Locally on Debug the test now finishes in ~44 seconds per run and
passes 3/3 consecutive runs. Under TSan, projected wall time per
run stays comfortably under the 600s timeout.
…able validation

Holding `currently_processing_in_background_mutex` (M1) across
`setProperties` and `startMutation` closes the data-loss race fixed
in this PR, but the wide lock also held across `alterTable` introduces
a lock-order inversion under TSan (STID 4119-5a23):

  - the ALTER path takes M1 then enters `alterTable` ->
    `applyMetadataChangesToCreateQuery` -> `validateCreateQuery` ->
    `validateColumnsDefaultsAndGetSampleBlock` -> `QueryAnalyzer` ->
    `MergeTreeData::getStorageSnapshot` -> `getStorageSnapshotCache`
    which acquires `QueryMetadataCache::storage_snapshot_cache_mutex`
    (M0)

  - any query that uses the analyzer takes M0 via the same
    `getStorageSnapshot` path, then descends into
    `createStorageSnapshot` -> `getMutationsSnapshot` which acquires
    M1 at `StorageMergeTree.cpp:3115`

So one direction is M1 -> M0 and the other is M0 -> M1: TSan flags
this as a potential deadlock and `03404_dynamic_in_interval_bug`
"server died" confirmed a real cross-thread cycle.

The validation done inside `alterTable` is redundant with the one
`AlterCommands::validate` runs upstream in `runCommandSegments`
(same `validateColumnsDefaultsAndGetSampleBlock` call before `alter`
is invoked). Skipping it by passing `validate_new_create_query=false`
removes the M0 acquisition from the M1-held window and breaks the
cycle. This mirrors the existing pattern used by
`StorageReplicatedMergeTree::setTableStructure`.

The data-loss race fix (M1 held atomically around `setProperties`
and the mutation registration) is preserved.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104822&sha=0e0da9e99095d9ae0aa9d028135d9c073e676fd3

PR: #104822
Signed-off-by: Groene AI <[email protected]>
The previous lock-order-inversion fix (commit 708c2ee) skipped
`alterTable`'s `validateCreateQuery` in `StorageMergeTree::alter` by
passing `validate_new_create_query=false` under the
`currently_processing_in_background_mutex` (M1) critical section. That
removed the M0 acquisition from inside M1 — but it also stopped catching
errors the upstream `AlterCommands::validate` does not detect, in
particular `MULTIPLE_EXPRESSIONS_FOR_ALIAS` for `MATERIALIZED`
expressions whose aliases collide with already-existing columns. CI
caught this as regressions in
`tests/queries/0_stateless/03224_invalid_alter.sql` and
`03274_aliases_in_udf.sql`.

`AlterCommands::validate` only runs
`validateColumnsDefaultsAndGetSampleBlock` on the alter commands' own
default expressions; it does not re-parse and re-analyze the full
resulting CREATE query, so it misses alias collisions introduced by an
`ALTER ADD/MODIFY COLUMN ... MATERIALIZED <expr>` against the existing
column set.

Fix: run the full validation as `StorageReplicatedMergeTree::alter`
already does — call `applyMetadataChangesToCreateQuery` on a fresh AST
fetched from the database BEFORE entering the M1 critical section. That
triggers the same `validateCreateQuery` ->
`validateColumnsDefaultsAndGetSampleBlock` -> `QueryAnalyzer` path that
catches the alias collisions, without holding M1 while the analyzer
acquires `QueryMetadataCache::storage_snapshot_cache_mutex` (M0). The
in-`alterTable` validation then remains skipped, preserving the
lock-order-inversion fix for STID 4119-5a23.

The data-loss-race fix for issue #80648 is unchanged: M1 still wraps
`setProperties` and the mutation registration atomically.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104822&sha=708c2ee2b276924914801a03b071bb9a20755e9e

PR: #104822
Signed-off-by: Groene AI <[email protected]>
…ents, drop no-parallel

Extract the prepare/commit-entry and metadata-registration steps that the two
startMutation overloads shared into prepareMutationEntry and
addPreparedMutationEntry helpers. Each overload becomes a small driver that
acquires (or assumes) currently_processing_in_background_mutex and calls the
helpers, eliminating the duplicated entry/block-allocation/txn body.

Shrink the two long comments in alter that recapped the CI/TSan history of
the lock-order fix to compact lock-order explanations.

Drop the no-parallel tag from 04238_alter_rename_column_merge_race: the test
only touches its own table in the per-slot database, no cross-slot interference.
…n lock-order cycle

`StorageMergeTree::loadMutations` is called only from the constructor at
`StorageMergeTree.cpp:213`, before the storage is registered with any database.
No other thread can hold a reference yet, so the
`currently_processing_in_background_mutex` lock_guard there is unnecessary.

Holding it created a TSan lock-order edge between `DatabaseAtomic::mutex`
(M0, held by `tryCreateSymlink` from `attachTable`/`renameTable` while lazily
constructing storages) and `currently_processing_in_background_mutex` (M1).
Combined with the reverse-direction edge introduced by holding M1 across
`alterTable` in `StorageMergeTree::alter` (the fix for #80648), TSan reported
`STID: 3367-4813` lock-order-inversion. The cycle is provably benign in
practice: the M1 in `loadMutations` is on an unpublished instance, but TSan
tracks edges by source location so the warning fires anyway.

Removing the lock breaks the M0 -> M1 edge from lazy storage construction,
clearing the cycle without weakening the data-loss protection (M1 still wraps
`setProperties + startMutation` in `alter`). Added a `chassert` for the
constructor invariant and a comment.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104822&sha=0b0693505dd3e84b33f0bc9eff1088377b720ca9&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20parallel%2C%201%2F2%29
PR: #104822
Issue: #80648
…ical section

`StorageMergeTree::alter` held `currently_processing_in_background_mutex` (M1)
across `setProperties` + `alterTable` + private `startMutation`. `alterTable`
calls `DatabaseAtomic::waitDatabaseStarted`, which takes `DatabaseAtomic::mutex`
(M2). Combined with these pre-existing edges:

  - M0 to M1: `BackgroundSchedulePoolTaskInfo::execute` to
    `StorageMergeTree::scheduleDataProcessingJob`
  - M2 to M3: `DatabaseAtomic::renameTable` to
    `StorageTableProxy::renameInMemory`
  - M3 to M0: `StorageTableProxy::flushAndPrepareForShutdown` (called from
    `InterpreterDropQuery`) to
    `StorageMergeTree::flushAndPrepareForShutdown` to
    `BackgroundJobsAssignee::finish` to
    `BackgroundSchedulePoolTaskInfo::deactivate`

ThreadSanitizer reported the resulting four-mutex cycle as STID 4546-4e53 on
the merged-master HEAD `cef26a2328a9`. The cycle was hidden until the master
merge brought in new code paths that exercise the M2-to-M3 and M3-to-M0 edges
under the right interleaving.

Fix:
  - Move `alterTable` out of the M1 critical section in
    `StorageMergeTree::alter` (the else branch).
  - Read `getInMemoryMetadataPtr` inside the same M1 critical section in
    `StorageMergeTree::scheduleDataProcessingJob`.

The data-loss race protection from #80648 is preserved because the atomicity
that matters is between `setProperties` (in-memory metadata update) and the
rename mutation registration in `current_mutations_by_version`, not the
on-disk metadata write. Background merge selection still cannot observe new
in-memory metadata without the matching pending rename mutation, because both
the in-memory metadata update / mutation registration in `alter` and the
metadata read / mutation queue lookup in `scheduleDataProcessingJob` are
serialized by the same mutex.

A best-effort rollback of the on-disk metadata is added if the in-memory
commit throws, so a subsequent restart sees a schema consistent with the
data in parts.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104822&sha=cef26a2328a9b84f2f3661b0b03677a0b57403e6&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%2C%201%2F2%29
PR: #104822
Issue: #80648

Co-Authored-By: Claude Opus 4.7 <[email protected]>
In `StorageMergeTree::alter`, when the rename path commits the new
in-memory metadata via `setProperties` and then registers the rename
mutation via the private `startMutation`, the catch block only rolled
back on-disk metadata and settings. If `startMutation` threw after
`setProperties` had already published the new metadata (mutation file
write/sync failure, OOM in the per-mutation map insertion, etc.), reads
would see the renamed column names while the on-disk parts still had
the old ones, returning defaults until restart - the same data-loss
class the rest of the PR is fixing, just on the error path.

Revert the in-memory metadata under `currently_processing_in_background_mutex`
before the on-disk rollback so concurrent merge selection cannot observe the
half-applied state. Keep the on-disk rollback outside the mutex to preserve
the M1->M2 edge removal from the earlier commit.

Regression test `04296_alter_rename_column_in_memory_rollback.sh` uses
a new `mt_alter_throw_in_start_mutation` failpoint to force the catch
path and verifies the renamed-from column is still queryable after the
failed ALTER. Without the fix the test fails with `UNKNOWN_IDENTIFIER`
on the original column name.

Addresses inline review on PR #104822
(#104822 (comment)).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Previously the lock in the publish block was a `std::lock_guard`, which is
destroyed during stack unwinding before the catch handler runs. That left a
race window where another thread could lock the mutex and observe the
just-published `new_metadata` without the pending rename mutation, the same
data-loss shape as #80648 but on the error-rollback path.

Move the lock outside the try as a `std::unique_lock` so it stays held through
the catch. Roll back in-memory metadata while still holding the lock (atomic
with the publish), then explicitly unlock before the on-disk rollback so the
broken `M1->M2` edge from `alterTable` is preserved.

Adjust the locked `startMutation` overload to take `std::unique_lock<std::mutex>`
to match.
…alter-rename-merge-race

Resolve include conflict in src/Storages/StorageMergeTree.cpp by keeping both
`#include <Core/UUID.h>` (added by master commit 2d04d90 for UUIDHelpers
fan-out) and `#include <Databases/DatabasesCommon.h>` (kept from this branch).

Per @PedroTadim 2026-06-01: resolve master conflicts then re-trigger CI.
`StorageMergeTree::prepareMutationEntry` calls `entry.commit` (which renames
`tmp_mutation_*.txt` to `mutation_*.txt` on disk) before
`addPreparedMutationEntry` registers the entry in
`current_mutations_by_version`. If anything between the two throws
(`txn->addMutation`, `try_emplace`, lock acquisition), the outer `alter` catch
rolls back metadata to `old_metadata` but the committed mutation file is left
on disk with no in-memory counterpart. After a restart, `loadMutations` reads
the file and re-registers the rename mutation. The matching metadata change
has already been reverted, so a subsequent part mutation runs against the
wrong schema and reintroduces the same data-loss class on the rollback path.

Track an `is_registered` flag on `MergeTreeMutationEntry`. The flag is set
when the entry is registered in `current_mutations_by_version` or loaded from
disk by `loadMutations`. The destructor of `MergeTreeMutationEntry` now also
removes the orphaned `mutation_*.txt` when `is_temp` is false and
`is_registered` is false. Move semantics handle the success path: once
`addPreparedMutationEntry` moves the entry into the map, the moved-from
`file_name` is empty and the destructor of the source skips cleanup.

Add fail point `mt_throw_after_mutation_commit` to deterministically inject
a throw between `entry.commit` and registration. The new regression test
`04308_alter_rename_column_prepared_mutation_cleanup` runs `ALTER RENAME
COLUMN` with the fail point enabled, asserts the ALTER throws, then
detaches and re-attaches the table to force `loadMutations` and verifies
that no orphaned mutation entry surfaces in `system.mutations`. Without the
fix, the test reports the orphan as `mutation_2.txt (RENAME COLUMN d TO d1)`.

CI Fix or Improvement (changelog entry is not required).

PR: #104822
Closes: #80648
The defaulted move constructor left the moved-from object's `file_name`
in a "valid but unspecified" state. With small-string optimization the
short `mutation_*.txt` name is typically not cleared, so the moved-from
source destructed as a spurious owner and removed the on-disk file that
the destination had just taken over (the `!is_temp && !is_registered`
orphan-removal path added for #80648). This reintroduced the data loss
the orphan cleanup was meant to prevent whenever an entry was moved
(returned from `prepareMutationEntry`, emplaced in
`current_mutations_by_version`, or pushed into `mutations_to_delete`).

Define an explicit `noexcept` move constructor that clears the source's
ownership token (`file_name`, `is_temp`, `is_registered`) via
`std::exchange`, so only the destination owns the file. `noexcept` also
keeps the move-on-reallocation path for `std::vector<MergeTreeMutationEntry>`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The OPTIMIZE TABLE FINAL path read the in-memory metadata snapshot before
acquiring currently_processing_in_background_mutex. During an ALTER RENAME
COLUMN that publishes new_metadata via setProperties and then throws in
startMutation, a concurrent merge could latch that transient new_metadata
outside the mutex; after the alter rolled back, the merge would proceed with
stale renamed metadata and no rename mutation, reading old parts under the new
column name and refilling the renamed column with defaults (the #80648
data-loss). Reading the snapshot inside the mutex, as scheduleDataProcessingJob
already does, makes merge selection observe a consistent (metadata, mutations)
pair. getContext() carries no query context, so the read takes the lockless
metadata.get() path and does not touch the query metadata snapshot cache,
keeping the M1 critical section free of the M0 cache mutex (no lock-order
inversion).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…MergeTree::alter`

The recent rollback path in `StorageMergeTree::alter` re-calls
`alterTable(old_metadata)` to keep the on-disk metadata file in sync with
in-memory state when `setProperties` or `startMutation` throws. That works for
`Atomic` / `Ordinary`, but under `Replicated` the metadata update goes through a
single-shot `ZooKeeperMetadataTransaction`. The first call (with `new_metadata`)
already commits the transaction inside `DatabaseAtomic::commitAlterTable`, so
the rollback call lands in `DatabaseReplicated::commitAlterTable` and tries
`txn->addOp` on an `EXECUTED` transaction, which raises `LOGICAL_ERROR
"Cannot add ZooKeeper operation because query is executed"` and aborts the
server.

The CI sighting was on PR #104822 commit `fe701d15a99` in
`Stateless tests (amd_llvm_coverage, old analyzer, s3 storage,
DatabaseReplicated, WasmEdge, sequential)`: test
`04308_alter_rename_column_prepared_mutation_cleanup` enables the
`mt_throw_after_mutation_commit` failpoint, the `ALTER RENAME COLUMN` enters
the rollback branch, and the second `alterTable` aborts the server.

Gate the on-disk rollback on `database->hasReplicationThread()`. For non-
replicated engines the existing behaviour is preserved. For `Replicated`,
on-disk rollback is fundamentally not possible after the ZK txn commit point;
the local file is left ahead of in-memory state, which is the existing
behaviour for any failure after that commit point under `Replicated`. In-memory
metadata is still rolled back atomically under
`currently_processing_in_background_mutex`, the orphan-mutation-file destructor
still runs, and the server stays alive.

Tag `04308_alter_rename_column_prepared_mutation_cleanup` with
`no-replicated-database` because its post-`DETACH`/`ATTACH` assertion that the
renamed-from column is still queryable requires on-disk rollback, which cannot
hold under `Replicated`. The orphan-mutation-file cleanup the test exercises
is engine-agnostic and remains covered for the non-replicated path.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104822&sha=fe701d15a9967461521f9063f0140193905f86c7

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Addresses the bot review on PR #104822 (#104822)
that flagged the rollback path under `Replicated` databases:

  Skipping rollback for `Replicated` keeps the server alive, but this leaves
  the durable state as `new_metadata` without the matching rename mutation.
  After restart or metadata reload, the table is loaded with the renamed
  column from the durable metadata, but there is no `RENAME COLUMN` mutation
  file left to convert old parts from `d` to `d1`, so the same default-value
  data-loss shape can reappear.

Reorder `StorageMergeTree::alter` so that:

1. `prepareMutationEntry` writes `mutation_*.txt` to disk BEFORE the durable
   `alterTable(new_metadata)` commit. If anything throws between the file
   write and `addPreparedMutationEntry`, `~MergeTreeMutationEntry` removes
   the orphan because `is_registered == false`.
2. Inside `currently_processing_in_background_mutex`, `addPreparedMutationEntry`
   runs FIRST, before `setProperties(new_metadata)`. Once registered, the
   file is preserved (`is_registered == true`) regardless of any later
   unwinding.

The combined invariant: once the durable metadata commit succeeds AND the
mutation registers, the matching rename mutation is always present (in
`current_mutations_by_version` and on disk). Under `Replicated`, even if
`setProperties` then fails, the durable metadata + the registered rename
mutation file stay matched, so `loadMutations` on the next reload re-finds
the file and the rename converts old parts to the new schema.

The lock-aware `startMutation` overload becomes unused and is removed.

The failpoint `mt_alter_throw_in_start_mutation` is moved into the new alter()
flow, firing before `addPreparedMutationEntry` so the orphan-cleanup path
exercised by `04296_alter_rename_column_in_memory_rollback` still runs.

`04308_alter_rename_column_prepared_mutation_cleanup` keeps its
`no-replicated-database` tag because the test uses `DETACH TABLE` /
`ATTACH TABLE` to force `loadMutations`, and `DETACH TABLE` is rejected
under `Replicated`. The underlying durable consistency invariant exercised
by the test holds under `Replicated` too: the failpoint inside
`prepareMutationEntry` fires before durable commit, so `~prepared` cleans
the orphan and durable metadata is unchanged.

Verified with build-asan / clang-21:
  - 04308, 04296, 04238: 5 runs each, 0/15 failures
  - Replicated DB scenario: ALTER throws, server stays alive, no orphan
    `mutation_*.txt`, in-memory metadata reverted, subsequent ALTER works.

Session id: cron:clickhouse-ci-task-worker:20260604-075400

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address the three inline review comments on PR #104822 about the rollback
gaps that survived the previous round (commit cc452d7):

CR1 (Replicated, post-durable, pre-registration): when the durable
`alterTable(new_metadata)` succeeds and a subsequent throw fires before
`addPreparedMutationEntry` (the failpoint, an allocator failure, or any
other interruption), the moved-from `prepared` was destroyed with
`is_registered = false` and `~MergeTreeMutationEntry` removed the
`mutation_*.txt` file. After restart the table loaded `new_metadata` from
the durable copy with no matching rename mutation, so old parts read the
renamed column as default. Bind the file to the durable commit by
flipping `prepared->entry.is_registered = true` immediately after
`alterTable` returns; any later throw now preserves the file so
`loadMutations` finds it on reload.

CR2 (non-replicated, post-registration): once `addPreparedMutationEntry`
succeeded the entry was registered with `is_registered = true` and the
file was kept, but the catch handler unconditionally rolled durable
metadata back to `old_metadata`. After restart `loadMutations` re-loaded
the rename mutation against rolled-back metadata and a subsequent part
mutation ran against the wrong schema, reintroducing the same data-loss
class. Track `mutation_registered` in the alter scope; in the
non-replicated rollback branch, decrement counters and erase the entry
under `currently_processing_in_background_mutex`, transferring file
ownership back to the destructor (which removes it). When registration
did not happen yet, clear the `is_registered` flag set after `alterTable`
so `~prepared` removes the file. Either way the rename mutation file and
the durable metadata move together.

CR3 (silent file removal): the orphan-cleanup branch in
`~MergeTreeMutationEntry` deleted a committed `mutation_*.txt` without a
log message, leaving operators no signal that a mutation was removed
before `loadMutations` could see it. Add a `LOG_INFO` matching the
visibility of `killMutation` and `clearOldMutations`.

Add a new failpoint `mt_alter_throw_after_mutation_registered` that fires
after `addPreparedMutationEntry` but before `setProperties`, exercising
the post-registration rollback path. Add regression test
`04309_alter_rename_column_post_registration_rollback` that runs the
failpoint, expects the ALTER to throw, then verifies the in-memory
rollback (column `d` still queryable, `d1` not visible), the
unregistration (`system.mutations` empty), and recovery via
DETACH/ATTACH (no orphaned mutation persisted across reload).

CI Fix or Improvement (changelog entry is not required).

PR: #104822
Closes: #80648

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…kiness

The regression test for #80648 flakes in the private-sync runners: under the
parallel test runner on slower sanitizer builds, 50 iterations x 4
clickhouse-client spawns push the test toward the per-test timeout. Locally a
single run took 39-65s with randomized settings (CIDB shows ASan flaky-check
runs at ~500-540s, close to the 600s wall).

Two changes cut wall time without weakening the test:

- Add no-random-settings and no-random-merge-tree-settings. The randomized
  query/MergeTree settings are irrelevant to this metadata race (it is about
  the merge-vs-rename registration window, not read/aggregation paths) and they
  added 33-60% of variable wall time. Removing them drops a 50-iteration run
  from ~40-65s to a steady ~27s with no variance, and removes the main timeout
  driver. Precedent: 34 long tests, including merge tests like 00155_long_merges,
  pin both.

- Reduce iterations 50 -> 25. The original fix commit measured ~20% per-attempt
  data loss on buggy master, so 25 attempts still catch a regression with >99%
  probability per build (and ~100% across the 4+ build variants). Combined with
  the setting changes a run is now ~13s steady.

The test still passes on the fixed binary (verified 5/5) and the assertion logic
is unchanged. Reference output (OK) is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…:alter

Follows up on the alter rollback paths introduced for #80648, addressing two
consistency gaps found by review on PR #104822. Both reproduce deterministically
via the existing failpoints.

1. Settings rollback. changeSettings(new) was published before the durable
   metadata commit but outside the try block that reverts it. A throw in
   checkTTLExpressions or prepareMutationEntry (for example the
   mt_throw_after_mutation_commit failpoint, a disk write error, or
   txn->addMutation) escaped with the new settings live in memory while columns
   and durable metadata stayed old. A failed mixed
   ALTER RENAME COLUMN ..., MODIFY SETTING ... then left the table running with
   the new setting until restart. changeSettings, checkTTLExpressions,
   prepareMutationEntry and the durable alterTable now run in one try whose catch
   restores the old settings, so every pre-commit exception reverts them.

2. Replicated in-memory rollback. For a MergeTree table inside a Replicated
   database the durable metadata commit lives in ZooKeeper and cannot be rolled
   back. The previous catch reverted in-memory metadata to old_metadata while the
   durable metadata stayed new_metadata and the rename mutation stayed registered.
   A background merge selected in that window ran the rename against the old
   schema snapshot, filled the renamed column with defaults and discarded the
   data, reopening the exact #80648 data loss this work closes. The Replicated
   branch now converges to the successful-alter state instead: it registers the
   prepared mutation if the throw happened before registration (the file is
   already durable) and publishes new_metadata, so the registered rename targets
   metadata that already has the renamed column and is a harmless no-op. The
   non-replicated branch is unchanged: it reverts in-memory metadata, unregisters
   and removes the rename mutation file under the lock, and rolls durable metadata
   and settings back to old.

Adds two regression tests:
- 04310_alter_rename_column_settings_rollback: asserts the table setting is
  reverted after a mixed RENAME COLUMN + MODIFY SETTING fails before the durable
  commit.
- 04311_alter_rename_column_replicated_db_rollback: asserts the renamed column's
  data survives a failed ALTER on a MergeTree table in a Replicated database,
  across OPTIMIZE FINAL and a reload.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The non-replicated rollback in StorageMergeTree::alter removed the
registered rename mutation_*.txt before the durable metadata rollback
alterTable(old_metadata) succeeded. If that durable rollback threw, or the
server stopped in that window, durable metadata stayed at new_metadata
(renamed column) while the only conversion mutation was already gone. On
restart loadMutations then loaded the renamed column with no rename mutation
to convert old parts, so the renamed column read back default values,
reopening the #80648 data loss on the rollback path.

Reorder the rollback so the durable metadata and the mutation file move
atomically. While the durable rollback runs, in-memory metadata is reverted
to old_metadata and the mutation is removed from the in-memory map (so merge
selection cannot observe new_metadata without a matching mutation), but the
committed mutation_*.txt is held alive in a local entry instead of being
deleted. Only after alterTable(old_metadata) durably succeeds is the file
removed and the settings reverted. If the durable rollback fails, converge to
the successful-alter state instead: re-register the on-disk rename mutation
and republish new_metadata so in-memory matches durable and a later merge
applies the rename. Settings stay at new_metadata to match the durable commit.

Add the mt_alter_throw_in_durable_rollback failpoint and a regression test
(04312) that injects a durable rollback failure and asserts data survives a
DETACH/ATTACH reload and OPTIMIZE FINAL.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
StorageMergeTree::alter committed the durable metadata before running the
setting-dependent metadata validation. The new-CREATE-AST pre-validation
only checks the CREATE query through the analyzer; it does not run
checkProperties under the freshly applied MergeTree settings. So a mixed
ALTER such as

    ALTER TABLE t RENAME COLUMN d TO d1,
                  MODIFY SETTING allow_part_offset_column_in_projections = 0

on a table with a _part_offset projection passed the pre-validation, the
durable alterTable committed new_metadata, and setProperties then rejected
the now-invalid projection after the commit. That left durable metadata at
new_metadata while the in-memory state stayed at old_metadata with the rename
mutation registered, which is the old-metadata + registered-mutation data
loss window this PR (#80648) closes, reached through a new path.

Restore the master invariant: validate before the durable commit. Add
MergeTreeData::checkMetadataProperties, a side-effect-free wrapper over
checkProperties that does not publish new_metadata, and call it in alter()
after changeSettings/checkTTLExpressions and before prepareMutationEntry and
the durable alterTable. The call is inside the existing try, so a rejection
reverts settings and rethrows with no durable change. This is general: it
validates all setting-dependent metadata, not only the _part_offset case.

Add regression test 04313_alter_rename_column_projection_setting_validation:
without the fix the rejected ALTER enters the post-commit rollback path and
logs "may be inconsistent until restart"; with the fix it is rejected before
the durable commit and that path is never entered.

Also rename 04312_alter_rename_column_durable_rollback_failure to
..._durable_rollback_throw: the style check forbids the substring "fail" in
stateless test file names.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two CI-driven fixups after merging master into the branch:

1. checkProperties drift. Master removed the reverse sorting key sanity
   check, so checkProperties no longer takes an allow_reverse_key
   parameter. Our new checkMetadataProperties wrapper still passed it,
   which compiled on the stale base but failed the merge-onto-master
   build (arm_tidy: "use of undeclared identifier allow_reverse_key").
   Drop the argument so the wrapper matches the current signature; the
   wrapper keeps passing allow_nullable_key as before. Also update the
   declaration comment to stop referencing the removed member.

2. Style. 04313_alter_rename_column_projection_setting_validation.sh
   used a global SYSTEM FLUSH LOGS, which check_style forbids
   (various_checks.sh: prefer a per-table flush). The test only reads
   system.text_log, so flush only that table: SYSTEM FLUSH LOGS text_log.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Master introduced a lifetime-safe StorageMetadataHandle wrapper:
getInMemoryMetadataPtr() now returns StorageMetadataHandle by value, and
the rvalue-to-StorageMetadataPtr conversion is deleted (StorageInMemoryMetadata.h)
to prevent dangling. The two metadata_snapshot assignments added by this PR in
StorageMergeTree::merge() and scheduleDataProcessingJob() assigned that rvalue
temporary directly, which no longer compiles after merging fresh master.

Bind the handle to a named lvalue first (matching the existing idiom elsewhere in
the file), then assign; the lvalue conversion operator is allowed and owning.
No behavior change: metadata is still read under
currently_processing_in_background_mutex, preserving the #80648 fix invariant.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ame-merge-race

Fix race between ALTER RENAME COLUMN and merge causing data loss (#80648)
@robot-ch-test-poll robot-ch-test-poll added the pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! label Jul 3, 2026
Resolve the cherry-pick of #104822 ("Fix race between `ALTER RENAME COLUMN`
and merge causing data loss (#80648)") onto the 26.3 release branch.

The only real conflict was in `StorageMergeTree.cpp`: on master the fix reads
in-memory metadata under `currently_processing_in_background_mutex` via the
two-argument `getInMemoryMetadataPtr(context, bypass_cache)` which returns a
`StorageMetadataHandle`. That signature and `StorageMetadataHandle` do not exist
on 26.3, where `getInMemoryMetadataPtr()` returns a `StorageMetadataPtr` directly.
Adapted the two moved reads (in `merge` and `scheduleDataProcessingJob`) to
`metadata_snapshot = getInMemoryMetadataPtr();`, dropping the handle indirection
while preserving the fix's intent of reading metadata under the mutex.

Also kept the fix's new `#include <Databases/DatabasesCommon.h>` (needed for
`applyMetadataChangesToCreateQuery`) and followed the release branch in not
re-adding `#include <Core/UUID.h>`.

Original pull-request #104822
@robot-ch-test-poll2
robot-ch-test-poll2 merged commit 174f612 into backport/26.3/104822 Jul 3, 2026
1 check passed
@robot-ch-test-poll2
robot-ch-test-poll2 deleted the cherrypick/26.3/104822 branch July 3, 2026 16:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! pr-critical-bugfix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants