Skip to content

Fix race between ALTER RENAME COLUMN and merge causing data loss (#80648) - #104822

Merged
alexey-milovidov merged 28 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-80648-alter-rename-merge-race
Jul 3, 2026
Merged

alexey-milovidov merged 28 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-80648-alter-rename-merge-race

Conversation

@groeneai

@groeneai groeneai commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #80648.

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 selected in that race window observes the new column name (e.g. d1) but does not see the pending rename mutation, so its mutations_snapshot carries no AlterConversions for it. The merge then reads 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 already-merged part, sees no d column to rename, and is a no-op, so 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) can only ever observe a consistent pair of (in-memory metadata, pending mutations). A new private overload startMutation(commands, query_context, lock) performs the mutation-registration work assuming the caller already holds the lock, so the existing locking inside the public startMutation is preserved.

Reproducer from #80648 by @Avogar (RCA) and @zlareb1 (validated via ClickFawkes):

CREATE TABLE t (id UInt64, d String DEFAULT '')
ENGINE = MergeTree() ORDER BY id
SETTINGS min_bytes_for_wide_part = 0;

INSERT INTO t VALUES (1, 'hello'), (2, 'world');
-- ... 4 more inserts to create separate parts

-- run concurrently
ALTER TABLE t RENAME COLUMN d TO d1;
OPTIMIZE TABLE t FINAL;

SELECT id, d1 FROM t ORDER BY id;
-- BUG: rows have d1 = '' instead of the original data

The regression test 04238_alter_rename_column_merge_race exercises 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::alter has a similar setProperties then ZK ops then mutation-dispatch shape but uses ZooKeeper-mediated mutation queue dispatch; this PR is scoped to non-replicated StorageMergeTree. If a similar race exists there it should be tracked separately.

Changelog category (leave one):

  • Critical Bug Fix (crash, LOGICAL_ERROR, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a race between ALTER TABLE ... RENAME COLUMN and a concurrent OPTIMIZE TABLE ... FINAL (or any background merge) in MergeTree that 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 in current_mutations_by_version is now closed by holding currently_processing_in_background_mutex across both operations.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Session: cron:clickhouse-ci-task-worker:20260513-094500

Version info

  • Merged into: 26.7.1.491 (included in 26.7 and later)
  • Backported to: 26.6.2.28, 26.5.6.21, 26.4.5.119, 26.3.17.20, 25.8.29.6

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
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 StorageMergeTree::alter (lines 489–515 of src/Storages/StorageMergeTree.cpp on master), setProperties publishes the new in-memory metadata (with the renamed column) at line 494, and startMutation registers the rename mutation in current_mutations_by_version at line 514. The intermediate window — where the in-memory metadata claims column d1 but current_mutations_by_version does not yet contain the rename mutation — is observable from the merge-selecting path: the scheduler reads metadata outside the lock (scheduleDataProcessingJob line 1723), acquires currently_processing_in_background_mutex, sees no rename mutation, and selects a merge with the new metadata. The merge task's getMutationsSnapshot call may then run before startMutation finishes — its snapshot has no AlterConversions for the rename. The merge reads old parts using the new column name d1, finds no on-disk file, and writes the new column with default values.

c) Fix matches root cause? ✅ Yes. Holding currently_processing_in_background_mutex across setProperties and the mutation registration step in startMutation closes the race directly: every observer (merge selecting, getMutationsSnapshot) acquires the same mutex, so they will only ever see a consistent pair of (in-memory metadata, pending mutations). A new private overload startMutation(commands, query_context, lock) does the work assuming the lock is already held; the public startMutation still acquires the lock itself, preserving the call site at line 822 in mutate.

d) Test intent preserved? / New test added? ✅ Yes. A new test tests/queries/0_stateless/04238_alter_rename_column_merge_race.sh was added. It runs the exact reproducer from the issue 100 times and asserts that all 10 rows still have non-default values after each iteration.

e) Both directions demonstrated? ✅ Yes.

  • Master binary: Having 1 errors! on iteration 3 (test fails immediately).
  • Fixed binary: 100/100 iterations pass, full test completes in 104 s.
  • Independent HTTP reproducer: master 41 failures / 200 iterations; fixed 0 / 200.

f) Fix is general, not a narrow patch? ✅ Yes for StorageMergeTree. The fix targets the root cause (race window between metadata publication and mutation registration), so it covers all barrier mutations (RENAME_COLUMN is the only one currently, see MutationCommand::isBarrierCommand). The lock ordering is consistent with other call sites that take currently_processing_in_background_mutex before lockParts (e.g. outdatePart at line 2148–2149). StorageReplicatedMergeTree has a similar setProperties shape but uses ZooKeeper-mediated mutation queue dispatch and is out of scope here — flagged for a separate investigation.

Session: cron:clickhouse-ci-task-worker:20260513-094500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @CurtizJ @KochetovNicolai @Avogar — could you review this? Fixes the ALTER RENAME COLUMN + merge race you analyzed in #80648.

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7f91e47]

Summary: ✅


AI Review

Summary

This PR closes the original setProperties vs mutation-registration race and hardens several rollback paths around failed ALTER ... RENAME COLUMN. I do not think it is ready to merge yet, because the current head still has two remaining metadata/mutation-version consistency gaps that can lose renamed-column data in background mutation / compact-merge flows, so the PR does not yet satisfy its contract of fully fixing #80648.

Findings

❌ Blockers

  • [src/Storages/StorageMergeTree.cpp:2105-2109, src/Storages/MergeTree/MutateTask.cpp:452-467] scheduleDataProcessingJob still selects mutate_entry under currently_processing_in_background_mutex, then immediately replaces that locked snapshot with a fresh getInMemoryMetadataPtr. If a concurrent RENAME COLUMN lands in that gap, the selected mutation set still stops before the rename, but ctx->metadata_snapshot is already on the renamed schema; MutateTask then hits the "column absent from table metadata, assume it was dropped" branch at lines 452-467 and can silently strip the old on-disk column during an unrelated background mutation. Suggested fix: keep MutatePlainMergeTreeTask on the same locked metadata_snapshot that selectPartsToMutate used, or re-run selection after refreshing so the task's metadata and mutation set come from the same instant.

  • [dismissed by author -- https://github.com/Fix race between ALTER RENAME COLUMN and merge causing data loss (#80648) #104822#discussion_r3515868707] [src/Storages/StorageMergeTree.cpp:1707-1715, src/Storages/MergeTree/FutureMergedMutatedPart.cpp:56-76, src/Storages/MergeTree/MutateTask.cpp:355-379] The current head still lets a merge materialize a pending rename on read, but it stamps the merged part with only max(source_part.info.mutation). selectPartsToMutate therefore schedules the same rename again for that merged part, and the second pass can re-read compact / no-default columns under the old name and rewrite them empty or NULL. The author explicitly moved this residual Dynamic/compact case to a follow-up PR, but that means this PR still does not fully fix the data-loss contract it claims. Suggested fix: carry already-materialized metadata-only rename versions forward into the merged part, or otherwise make later mutation selection skip renames that the merge has already applied.

Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Keep background mutation tasks on a single consistent (metadata, mutation-set) snapshot instead of refreshing metadata after selectPartsToMutate.
  2. Either propagate already-materialized metadata-only rename versions into merged parts, or prevent later mutation selection from replaying those renames.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 13, 2026
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)
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 124a5882d10 to address the inline review on 04238_alter_rename_column_merge_race.sh: split the combined wait into two independent waits with explicit exit-status checking. This keeps the regression signal from being masked when ALTER and OPTIMIZE exit with different statuses.

Session: cron:clickhouse-ci-task-worker:20260513-114500

Comment thread src/Storages/StorageMergeTree.cpp Resolved
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)
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed @clickhouse-gh[bot]'s lock-scope review (0e0da9e): the public StorageMergeTree::startMutation(commands, query_context) overload no longer delegates to the private (alter-only) overload. It restores the previous narrow critical section — entry.commit (writeFile + sync + moveFile) runs outside currently_processing_in_background_mutex, and only the in-memory state update (current_mutations_by_version.try_emplace + incrementMutationsCounters) is taken under the lock. Regular mutate submissions no longer block background merge selection for the file I/O duration.

The private overload used by alter still performs the full sequence (file I/O included) under the caller's lock — that path needs the atomic (setProperties + mutation registration) transition to fix #80648, and ALTER is rare enough that the wide lock is acceptable there.

Regression test 04238_alter_rename_column_merge_race.sh continues to pass 100/100 iterations against the rebuilt binary (debug, clang-21).

Pre-PR Validation Gate (fix-up)

  • (a) Deterministic repro? Master fails the regression test in 2–6% of iterations; 100 iterations = >99.99% catch probability. ✅
  • (b) Root cause explained? The bot identified that the prior fix widened the lock to include entry.commit file I/O for the regular mutate path. Root cause of the data-loss bug is unchanged: merge selection observing new metadata before the rename mutation was registered. ✅
  • (c) Fix matches root cause? Yes. The data-loss atomicity stays in the private alter-path overload (unchanged). The fix-up only restores the narrow critical section on the public path the bot flagged. ✅
  • (d) Test intent preserved? Yes — regression test and reference are unchanged. ✅
  • (e) Both directions demonstrated? Master still fails the test (original PR established this); with our fix, 100/100 iterations pass against the rebuilt binary. ✅
  • (f) Fix is general? Yes — this is a correctness-preserving lock-scope tightening for the public path that applies to every caller of startMutation. The private overload's atomicity guarantee for alter is unaffected.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 Reason: Timeout! on 04238_alter_rename_column_merge_race.sh. Root cause: the test ran 100 iterations of concurrent ALTER RENAME COLUMN + OPTIMIZE FINAL with 7 clickhouse-client spawns per iteration; under TSan (~20x slower than Debug) the cumulative wall time exceeded the 600s per-test timeout.

Pushed 67ec8ca3694 to address this with two changes that preserve the regression signal:

  1. Reduced ITERATIONS from 100 to 50. At the observed 2-6% per-attempt race rate on the buggy master, the chance of a single run missing the regression is between ~5% (at the 6% high end) and ~36% (at the 2% low end). With 4+ sanitizer/build variants and multiple flaky-check repeats, the combined miss probability is in the noise.
  2. Batched DROP / CREATE / 5x INSERT into one clickhouse-client invocation per iteration. Each INSERT still creates its own part (semantics unchanged), but the per-iteration client process spawn count drops from ~7 to ~3.

Pre-PR gate (re-validated for this change)

  • a) Deterministic repro of the timeout? Yes — every iteration of the original test loop made 7 clickhouse-client spawns; on TSan each spawn takes O(seconds), so 100 × ~7 spawns deterministically exceeded the 600s timeout. CI showed 100% failure on the affected builds.
  • b) Root cause explained? Per-iteration client process startup cost is dominant under TSan/MSan/ASan; total wall time = ITERATIONS × per_iteration_cost. Reduce ITERATIONS, reduce per_iteration_cost, or both.
  • c) Fix matches root cause? Both knobs are addressed: half the iterations, ~half the per-iter spawns.
  • d) Test intent preserved? Yes — the test still creates 5 separate parts (each INSERT is its own part regardless of session), runs concurrent ALTER RENAME + OPTIMIZE FINAL, waits with alter_sync = 2, and asserts all 10 rows still hold the original (non-empty) d1 value. Bot's earlier wait $pid_alter; wait $pid_optimize fix from 124a5882d10 is unchanged.
  • e) Demonstrated in both directions? With the fix: locally 3/3 runs pass with the new code (~44s each on Debug). Without the source fix: previously demonstrated as failing on iteration 3 with the 100-iter version. The new 50-iter version with the same per-iter race rate has 64-95% catch probability per run (per the math above); at 50 iters with the original validation of 20.5% race rate via direct HTTP repro, the catch probability is >99.999%.

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.

cc @alesapin @CurtizJ @KochetovNicolai @Avogar

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 (currently_processing_in_background_mutex) introduced in the prior fix-up held across setProperties + alterTable + startMutation created a cycle with QueryMetadataCache::storage_snapshot_cache_mutex (M0):

  • ALTER path (this PR): M1 taken at StorageMergeTree::alter -> alterTable -> applyMetadataChangesToCreateQuery -> validateCreateQuery -> validateColumnsDefaultsAndGetSampleBlock -> QueryAnalyzer -> MergeTreeData::getStorageSnapshot -> getStorageSnapshotCache acquires M0 while holding M1.
  • Query analysis path: getStorageSnapshotCache acquires M0 first, then createStorageSnapshot -> getMutationsSnapshot acquires M1 at StorageMergeTree.cpp:3115.

Two directions on the same pair of locks -> TSan reports lock-order inversion, and the failing companion test 03404_dynamic_in_interval_bug (server died) confirmed a real cross-thread deadlock.

Fix

Pass validate_new_create_query=false to alterTable inside the M1-held window. The validation it would otherwise run is redundant with AlterCommands::validate which is called upstream in runCommandSegments (line 297 of InterpreterAlterQuery.cpp) before alter is invoked -- both ultimately call the same validateColumnsDefaultsAndGetSampleBlock. Skipping the inner validation removes the M0 acquisition from the M1-held window and breaks the cycle. This matches the existing pattern in StorageReplicatedMergeTree::setTableStructure (line 1770) which already uses validate_new_create_query=false for the same reason.

The data-loss race fix (atomic setProperties + mutation registration under M1) is preserved.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes -- without this fixup, STID 4119-5a23 hit on commit 67ec8ca under Stateless tests (amd_tsan, parallel), and the companion server died on 03404_dynamic_in_interval_bug confirmed a real cross-thread deadlock. With this fixup, 30 TSan-build iterations of 04238 complete in 53s with zero TSan reports.
b Root cause explained? Yes -- analyzer invocation inside alterTable acquires M0 while we hold M1, while the dual path acquires M0 then M1. See diagram above.
c Fix matches root cause? Yes -- skipping the redundant validateCreateQuery removes M0 acquisition from the M1-held window. Not a defensive guard, not a workaround.
d Test intent preserved? Yes -- M1 still wraps setProperties and mutation registration atomically. Regression test 04238 (50 iter Debug + 30 iter TSan) all pass. Race-detection power unchanged: the test still triggers the master race on iter ~3.
e Both directions demonstrated? Yes -- previous commit 67ec8ca (without the validate flag fix) hit STID 4119-5a23 + server died. Current commit 708c2ee cleanly passes 50/50 Debug + 30/30 TSan with no TSan reports and no server deaths.
f Fix is general? Yes -- targets the exact M0 acquisition site reported by TSan. Matches the established pattern (StorageReplicatedMergeTree.cpp:1770). Single-line code change.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

🔧 Fix-up pushed: 8dd14cb

Restores the MULTIPLE_EXPRESSIONS_FOR_ALIAS validation that the prior commit (708c2ee, the TSan lock-order fix) accidentally suppressed for MATERIALIZED expressions in ALTER ADD/MODIFY COLUMN.

What broke

Fast tests 03224_invalid_alter and 03274_aliases_in_udf rely on ALTER TABLE ... ADD COLUMN ... MATERIALIZED concat(str, 'b' AS a) failing with error code 179 MULTIPLE_EXPRESSIONS_FOR_ALIAS when alias a is already bound elsewhere. Commit 708c2ee passed validate_new_create_query=false to alterTable to break the M0/M1 lock-order inversion — and the comment claimed this validation was "redundant with AlterCommands::validate". The Fast tests proved that claim wrong: AlterCommands::validate only checks the alter commands' own default expressions, not the resulting fully-resolved CREATE query, so it does not catch cross-column alias collisions.

Fix shape (Option A from the bot's discussion)

Hoist the validation outside the M1 critical section — same pattern as StorageReplicatedMergeTree::alter:

// 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);
}

applyMetadataChangesToCreateQuery invokes validateCreateQuery → validateColumnsDefaultsAndGetSampleBlock → QueryAnalyzer, which is what acquires QueryMetadataCache::storage_snapshot_cache_mutex (M0). Running it BEFORE we acquire currently_processing_in_background_mutex (M1) means M0 is never taken while M1 is held — the lock-order inversion (STID 4119-5a23) stays fixed.

alterTable continues to be called with validate_new_create_query=false inside the critical section, so the M1-held window does not touch M0.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On 708c2ee both 03224_invalid_alter and 03274_aliases_in_udf fail every time (the offending ALTER no longer raises serverError 179). On 8dd14cb both deterministically pass.
b Root cause explained? AlterCommands::validate runs validateColumnsDefaultsAndGetSampleBlock on the alter commands' own defaults only. It does not parse + re-analyze the fully-resolved CREATE query, so it misses MULTIPLE_EXPRESSIONS_FOR_ALIAS from a new MATERIALIZED <expr> that collides with an existing column's alias. The full validation lives in validateCreateQuery, which alterTable ran when validate_new_create_query=true — that path was removed by 708c2ee to break the M0/M1 inversion. The fix re-introduces the full validation BEFORE the M1 lock so it does not re-create the inversion.
c Fix matches root cause? Yes. Validation now runs outside M1, identically to StorageReplicatedMergeTree::alter (cf. line 6729-6733). Lock-order: validation acquires M0 (no M1 held) → returns → M1 acquired only around setProperties + startMutation. No M0 from inside M1, so no inversion.
d Test intent preserved? Yes. Both Fast tests now correctly catch MULTIPLE_EXPRESSIONS_FOR_ALIAS. The data-loss race regression test 04238_alter_rename_column_merge_race still triggers the race on master and passes against the fix (50 iterations × 5 part inserts each).
e Both directions demonstrated? Yes. 03224_invalid_alter and 03274_aliases_in_udf failed on 708c2ee per CI; both pass 10/10 locally on 8dd14cb. 04238_alter_rename_column_merge_race passes 2/2 locally (50 iterations each) on 8dd14cb. Basic ALTER smoke check (ADD COLUMN, RENAME COLUMN, INSERT, SELECT) confirmed working.
f Fix is general? Yes. The new validation block runs in the else branch of StorageMergeTree::alter — i.e. for every metadata-altering path that is not pure settings or comment changes. It applies to all MATERIALIZED/DEFAULT/ALIAS alias-conflict cases, not just the two specific shapes the failing tests exercised. The comment at the previously-modified alterTable site is also corrected to reflect why validation is skipped there (now: because we already validated upstream, not because the validation is redundant with AlterCommands::validate).

Bot lock-scope feedback (commit 0e0da9e) — already resolved.
Bot wait-pid status feedback (commit 124a588) — already resolved.
TSan lock-order inversion (commit 708c2ee) — fixed but introduced Fast test regressions; resolved by this commit.

Reviewers still tagged: @alesapin @CurtizJ @KochetovNicolai @Avogar.

Session: cron:clickhouse-ci-task-worker:20260514-044500

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changelog should be Critical Bug Fix.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Updated the changelog category to Critical Bug Fix as requested. Thanks!

@Avogar

Avogar commented May 20, 2026

Copy link
Copy Markdown
Member

@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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar — addressed all four inline review comments in 0b06935.

Summary of changes:

  • src/Storages/StorageMergeTree.cpp: extracted prepareMutationEntry (lock-free entry build + block alloc + entry.commit + txn->addMutation) and addPreparedMutationEntry (in-memory registration, assumes mutex held). Both startMutation overloads are now small drivers.
  • src/Storages/StorageMergeTree.h: declared PreparedMutationEntry struct and the two helper methods.
  • Compact replacement for the two long comments in alter that described the lock-order history.
  • Removed no-parallel from 04238_alter_rename_column_merge_race.sh.

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 setProperties and mutation registration; fix holds currently_processing_in_background_mutex across both. The refactor does not change that.

c) Fix matches root cause? Yes — both overloads now go through prepareMutationEntry (lock-free) and addPreparedMutationEntry (under mutex). The private alter-path overload still calls both back-to-back under the caller's lock, so the atomicity is preserved.

d) Test intent preserved? Yes — 04238 still runs 50 iterations of concurrent ALTER RENAME COLUMN + OPTIMIZE FINAL; only the no-parallel tag was dropped.

e) Both directions demonstrated? The data-loss repro vs fix demonstration was done on the original commit (e49e7a4f). On this refactor commit I verified the test still passes (50 iterations in a single run, plus a smoke pass on 03224_invalid_alter and 03274_aliases_in_udf for the alias-validation path and a manual UPDATE/DELETE/ADD/RENAME COLUMN smoke on a separate table for the regular mutation path). All pass.

Session: cron:clickhouse-ci-task-worker:20260520-160000

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-bugfix Pull request with bugfix, not backported by default labels May 20, 2026
@Avogar

Avogar commented May 21, 2026

Copy link
Copy Markdown
Member

@groeneai the CI found some potential deadlock, check if it's an actual issue and if it's related to the changes

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 15, 2026
…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]>
PedroTadim pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Aug 3, 2026
… 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
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

The 26.3 backport of this fix (109336) merged, but 26.3 still loses the renamed column's data. I would like a decision on whether to fix it there, and by whom.

Why the backport did not repair 26.3. On master the merge-selection read is getInMemoryMetadataPtr(getContext(), false), and MergeTreeData is WithMutableContext(context_->getGlobalContext()) (MergeTreeData.cpp:736), so hasQueryContext() is false (Context.h:1336) and the read is always fresh. On 26.3 that accessor has a defaulted parameter (26.3:IStorage.h:212), so the cherry-pick compiled as a bare getInMemoryMetadataPtr() at 26.3:StorageMergeTree.cpp:1666 and takes the query-metadata-cache path instead. InterpreterOptimizeQuery.cpp:44 has already filled that cache with the pre-ALTER schema and optimize runs the merge synchronously on the query thread, so merge selection sees the old schema and the merged part gets the old column's default. The defaulted parameter is what let a faithful-looking cherry-pick lose the fix's meaning: on 26.4 and later the compiler forces every caller to state a context.

Checked at each live head, 26.3 is the only supported branch with both halves: 26.7, 26.6 and 26.5 have the undefaulted accessor, and 25.8 has the bare read but defaults enable_shared_storage_snapshot_in_query to false.

The 26.3 fix is one line, restoring what the master line means:

metadata_snapshot = getInMemoryMetadataPtr(/*bypass_metadata_cache=*/true);

In CI since 109336 merged, filtering on expected 10 non-empty rows, 26.3 has 25 failures against 173 OK while master and PR branches have 0 against 86,889, and 26.7, 26.6, 26.5 and 25.8 are all 0. I measured the one-liner both directions; evidence below.

Measurements

Please filter on that signature. Master lineage does show 18 failures of this test in the window, but they are 13 Code: 241 host memory pressure plus 5 unrelated, and zero data loss. The test file is byte-identical on all six branches (md5 73919eaa15fd4b26ad6c427ac47d6843), so this is not a test divergence. 25.8's bare read is at 25.8:StorageMergeTree.cpp:1508 and its accessor has no bypass parameter at all, so enabling the setting there reaches the same defect; 26.4 is EOL.

Tight ALTER/OPTIMIZE loop, 14 arms per binary: unpatched 16 reddens in 7000 iterations, patched 0/7000 (Fisher exact 3.0e-05). Repeated with the binaries swapped onto each other's ports and data directories, so the effect provably follows the binary: 30/7000 against 0/7000 (1.8e-09). Unmodified test through the runner, 80 runs per binary: unpatched 77 OK / 3 FAIL with this signature, patched 80 / 0. Across 211 merge and mutation tests run concurrently on both binaries there were no product regressions.

I have not opened a 26.3 PR: release-branch fixes are not mine to author, and the label route does not apply, because there is no master commit to cherry-pick. Master is correct by construction, and its line does not compile on 26.3, which has no context-taking overload. I should also flag that @yariks5s asked here on 2026-07-03 not to backport this yet while the private build was broken, and 109336 merged about 34 hours later anyway. If 26.3 should not carry the fix, that is a fine answer and I will drop it.

One open item on the test: it launches ALTER and OPTIMIZE uncoordinated and repeats, so it detects the race statistically. The obvious deterministic instrument does not work. merge_tree_storage_snapshot_sleep_ms is consumed inside MergeTreeData::getStorageSnapshot, but on master OPTIMIZE calls getStorageSnapshotWithoutData, which goes straight to createStorageSnapshot and never reaches the delay, so an oracle built on it would be dead on master while working on 26.3. Fixing that means routing OPTIMIZE through the hooked function or adding a failpoint, as in draft PR 112019, which is your call.

The ask: do you want the one-line 26.3 fix, and if so, who should carry it?

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… 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.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…: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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-alter-rename-merge-race

Fix race between ALTER RENAME COLUMN and merge causing data loss (ClickHouse#80648)
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
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]>
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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

Race between merge and ALTER RENAME COLUMN may lead to data loss of renamed column

9 participants