Repository navigation
Fix race between ALTER RENAME COLUMN and merge causing data loss (#80648) - #104822
alexey-milovidov merged 28 commits into
Conversation
Reported in ClickHouse#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 ClickHouse#80648
|
Pre-PR validation gate (TASK.md Phase 4): a) Deterministic repro? ✅ Yes. The 100-iteration regression test reliably triggers the data loss on master — 41/200 iterations failed (~20%) using an HTTP-driven loop. The race window is consistent across runs. b) Root cause explained? ✅ Yes. In c) Fix matches root cause? ✅ Yes. Holding d) Test intent preserved? / New test added? ✅ Yes. A new test e) Both directions demonstrated? ✅ Yes.
f) Fix is general, not a narrow patch? ✅ Yes for Session: cron:clickhouse-ci-task-worker:20260513-094500 |
|
cc @alesapin @CurtizJ @KochetovNicolai @Avogar — could you review this? Fixes the ALTER RENAME COLUMN + merge race you analyzed in #80648. |
|
Workflow [PR], commit [7f91e47] Summary: ✅
AI ReviewSummaryThis PR closes the original Findings❌ Blockers
Final VerdictStatus: Minimum required actions:
|
Address reviewer feedback from `clickhouse-gh[bot]` on PR ClickHouse#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: ClickHouse#104822 (comment)
|
Pushed 124a5882d10 to address the inline review on Session: cron:clickhouse-ci-task-worker:20260513-114500 |
PR ClickHouse#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 ClickHouse#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: ClickHouse#104822 (comment)
|
Addressed @clickhouse-gh[bot]'s lock-scope review (0e0da9e): the public The private overload used by Regression test Pre-PR Validation Gate (fix-up)
|
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.
|
PR-caused CI failures on 4 sanitizer builds (TSan flaky check, MSan flaky check, ASan+UBSan flaky check, ARM ASan+UBSan targeted) on commit 0e0da9e were all Pushed
Pre-PR gate (re-validated for this change)
Local Debug timing: 3 consecutive runs at 45.46s / 44.26s / 43.21s. Projected TSan: 130-440s per run (depending on whether IO-bound work dominates), all comfortably under 600s. |
…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: ClickHouse#104822
Signed-off-by: Groene AI <[email protected]>
|
Pushed 708c2ee to address the TSan lock-order inversion (STID 4119-5a23) reported by the PR monitor on the previous commit. Root cause The wide M1 lock (
Two directions on the same pair of locks -> TSan reports lock-order inversion, and the failing companion test Fix Pass The data-loss race fix (atomic Pre-PR validation gate
CI report (previous deadlock): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104822&sha=0e0da9e99095d9ae0aa9d028135d9c073e676fd3 cc @alesapin @CurtizJ @KochetovNicolai @Avogar -- ready for re-review. Session: cron:clickhouse-ci-task-worker:20260514-001500 |
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 ClickHouse#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: ClickHouse#104822 Signed-off-by: Groene AI <[email protected]>
|
🔧 Fix-up pushed: 8dd14cb Restores the What brokeFast tests Fix shape (Option A from the bot's discussion)Hoist the validation outside the M1 critical section — same pattern as // In StorageMergeTree::alter, in the else branch, BEFORE the M1 lock:
{
auto create_ast = DatabaseCatalog::instance()
.getDatabase(table_id.database_name)
->getCreateTableQuery(table_id.table_name, local_context);
applyMetadataChangesToCreateQuery(create_ast, new_metadata, local_context);
}
Pre-PR validation gate
Bot lock-scope feedback (commit 0e0da9e) — already resolved. Reviewers still tagged: @alesapin @CurtizJ @KochetovNicolai @Avogar. Session: cron:clickhouse-ci-task-worker:20260514-044500 |
Avogar
left a comment
There was a problem hiding this comment.
The changelog should be Critical Bug Fix.
|
Updated the changelog category to |
|
@groeneai check my review comments and address them |
… trim comments, 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.
|
@Avogar — addressed all four inline review comments in 0b06935. Summary of changes:
Pre-PR validation gate: a) Deterministic repro? Yes for the data-loss bug (original commit). The refactor preserves the same critical section. b) Root cause explained? Yes — race window between c) Fix matches root cause? Yes — both overloads now go through d) Test intent preserved? Yes — e) Both directions demonstrated? The data-loss repro vs fix demonstration was done on the original commit ( Session: cron:clickhouse-ci-task-worker:20260520-160000 |
|
@groeneai the CI found some potential deadlock, check if it's an actual issue and if it's related to the changes |
…n every ALTER The narrowing in the previous commit fired the allow_part_offset_column_in_projections / allow_commit_order_projection gates only for projections introduced by the current operation, which lets ALTER MODIFY/RESET SETTING turn the gate off under a pre-existing matching projection. That regressed 04313 (PR ClickHouse#104822): a table with a _part_offset projection must not be able to disable the feature. Fire the CREATE-only gates when this operation is responsible for the invalid pairing: the projection is introduced now (CREATE / ADD PROJECTION) with the gate off, or this ALTER flips the gate from enabled to disabled while the projection already exists. Still never on ATTACH (issue ClickHouse#102445) and never for an unrelated ALTER that leaves an already-disabled gate untouched or a mixed enable+ADD PROJECTION. Rewrite 04545 as a parallel-safe .sh test: the ClickHouse#102445 ATTACH path is now reached via an on-disk metadata edit (a cross-version default flip) since the ALTER-disable is rejected; add the disable-flip rejection cases for both CREATE-only gates. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… path 04296_alter_rename_column_in_memory_rollback fails on every run of the two DBReplicated llvm_coverage job flavours, and on no other flavour, with "Code: 47. Missing columns: 'd'". It is deterministic, not flaky. It stayed invisible because the diagnostics rerun drops the job's --replicated-database flag, so the rerun passes, the test is labelled flaky, and the llvm_coverage job force-sets OK. PR ClickHouse#112247 fixes that forwarding, after which these two jobs start failing for real. The engine is behaving correctly. --replicated-database makes the test database ENGINE=Replicated (tests/clickhouse-test:806), so DatabaseReplicated::hasReplicationThread is true and StorageMergeTree::alter's in-memory-commit error handler takes the converge-forward branch (StorageMergeTree.cpp:638-661): the durable commit already went to ZooKeeper and cannot be rolled back, so the handler publishes new_metadata at :653 rather than reverting to old_metadata. Reverting there while the rename mutation stays registered would let a background merge run the rename against the old schema and reopen the ClickHouse#80648 data loss, which is exactly the behaviour commit 4676040 removed. Column d is therefore gone by design, and the test's SELECT id, d correctly raises UNKNOWN_IDENTIFIER. The test asserts the non-replicated revert contract, so its scope declaration was simply missing. 04296 is the only one of the seven tests added by ClickHouse#104822 that lacks no-replicated-database: it was added before the replicated branch existed and was never revisited. Tag it, with a reason comment in the same style as its six siblings, and add 04352 covering the cell the tag excludes: mt_alter_throw_in_start_mutation on an explicitly created Replicated database. That combination has no coverage today and is the only way to reach the "if (!mutation_registered && prepared)" sub-branch at :647, where the handler must register the prepared mutation itself before publishing. Total coverage strictly increases and no assertion is weakened. Validated on a Debug build: the failure reproduces with the flag and the same binary passes without it; after the change 04296 is SKIPPED under --replicated-database and still passes plainly; 50/50 randomized runs green for both files with no no-random-* tag. 04352 reddens under three independent mutations: removing its failpoint, changing the converge-forward line to revert, and deleting the handler's mutation self-registration at :647 (which loses the mutation and also defaults the renamed column's data, the ClickHouse#80648 shape). Its system.mutations assertion reads the in-memory mutation map, so it pins that registration step rather than a later re-read of the durable mutation file. Related: ClickHouse#104822
|
The Why the backport did not repair Checked at each live head, The metadata_snapshot = getInMemoryMetadataPtr(/*bypass_metadata_cache=*/true);In CI since 109336 merged, filtering on MeasurementsPlease filter on that signature. Master lineage does show 18 failures of this test in the window, but they are 13 Tight I have not opened a One open item on the test: it launches The ask: do you want the one-line |
Address reviewer feedback from `clickhouse-gh[bot]` on PR ClickHouse#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: ClickHouse#104822 (comment)
PR ClickHouse#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 ClickHouse#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: ClickHouse#104822 (comment)
…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: ClickHouse#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 ClickHouse#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: ClickHouse#104822 Signed-off-by: Groene AI <[email protected]>
… trim comments, 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 ClickHouse#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: ClickHouse#104822 Issue: ClickHouse#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 ClickHouse#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: ClickHouse#104822
Issue: ClickHouse#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 ClickHouse#104822 (ClickHouse#104822 (comment)). Co-Authored-By: Claude Opus 4.7 <[email protected]>
`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: ClickHouse#104822 Closes: ClickHouse#80648
…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 ClickHouse#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 ClickHouse#104822 (ClickHouse#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 ClickHouse#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: ClickHouse#104822 Closes: ClickHouse#80648 Co-Authored-By: Claude Opus 4.8 <[email protected]>
…:alter Follows up on the alter rollback paths introduced for ClickHouse#80648, addressing two consistency gaps found by review on PR ClickHouse#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 ClickHouse#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]>
…-alter-rename-merge-race Fix race between ALTER RENAME COLUMN and merge causing data loss (ClickHouse#80648)
STOR: RENAME COLUMN racing OPTIMIZE FINAL / background merge (StorageMergeTree) -> data (column replaced by defaults). Effect in the production build a394e92: its upstream test(s) 04296_alter_rename_column_in_memory_rollback, 04308_alter_rename_column_prepared_mutation_cleanup, 04309_alter_rename_column_post_registration_rollback, 04310_alter_rename_column_settings_rollback fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv). Upstream patch unchanged, with its test(s): 04296_alter_rename_column_in_memory_rollback,04308_alter_rename_column_prepared_mutation_cleanup,04309_alter_rename_column_post_registration_rollback,04310_alter_rename_column_settings_rollback. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes #80648.
In
StorageMergeTree::alter,setPropertiespublishes the new in-memory metadata (with the renamed column) beforestartMutationregisters the rename mutation incurrent_mutations_by_version. A background merge selected in that race window observes the new column name (e.g.d1) but does not see the pending rename mutation, so itsmutations_snapshotcarries noAlterConversionsfor it. The merge then reads old parts using the new named1, finds no on-disk file, and fills the new column with default values. The subsequent rename mutation runs on the already-merged part, sees nodcolumn to rename, and is a no-op, so the renamed column's data is gone.The fix holds
currently_processing_in_background_mutexacross bothsetPropertiesand the mutation registration, so the merge-selecting thread (and the merge task's latergetMutationsSnapshotcall) can only ever observe a consistent pair of (in-memory metadata, pending mutations). A new private overloadstartMutation(commands, query_context, lock)performs the mutation-registration work assuming the caller already holds the lock, so the existing locking inside the publicstartMutationis preserved.Reproducer from #80648 by @Avogar (RCA) and @zlareb1 (validated via
ClickFawkes):The regression test
04238_alter_rename_column_merge_raceexercises this with 100 iterations. Before the fix the race triggers on ~20 % of iterations (HTTP-driven reproducer); with the fix it passes 200/200.Note:
StorageReplicatedMergeTree::alterhas a similarsetPropertiesthen ZK ops then mutation-dispatch shape but uses ZooKeeper-mediated mutation queue dispatch; this PR is scoped to non-replicatedStorageMergeTree. If a similar race exists there it should be tracked separately.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a race between
ALTER TABLE ... RENAME COLUMNand a concurrentOPTIMIZE TABLE ... FINAL(or any background merge) inMergeTreethat could silently replace the renamed column's data with default values. The race window between publishing the new in-memory metadata and registering the rename mutation incurrent_mutations_by_versionis now closed by holdingcurrently_processing_in_background_mutexacross both operations.Documentation entry for user-facing changes
Session: cron:clickhouse-ci-task-worker:20260513-094500
Version info
26.7.1.491(included in26.7and later)26.6.2.28,26.5.6.21,26.4.5.119,26.3.17.20,25.8.29.6