Skip to content

Fix race between ALTER and RENAME/EXCHANGE TABLES - #103044

Merged
evillique merged 33 commits into
ClickHouse:masterfrom
evillique:ddl-guard-for-alter
Sep 14, 2026
Merged

evillique merged 33 commits into
ClickHouse:masterfrom
evillique:ddl-guard-for-alter

Conversation

@evillique

@evillique evillique commented Apr 17, 2026 •

Copy link
Copy Markdown
Member

Fix a race between ALTER and RENAME/EXCHANGE TABLES. A concurrent EXCHANGE could slip in between getStorageID and IDatabase::alterTable inside IStorage::alter, so ALTER would throw UNKNOWN_TABLE or CANNOT_ASSIGN_ALTER. In the COMMENT and SETTING fast paths it could also leave the in-memory metadata out of sync with the .sql file until the next restart. ALTER now holds a DDLGuard on the storage (with a rename-safe retry on acquisition), and every path that applies a local setting or comment change reverts it if saving the metadata fails.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix the race between ALTER and RENAME/EXCHANGE TABLES.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

  • Merged into: 26.9.1.1481 (included in 26.9 and later)

@clickhouse-gh

clickhouse-gh Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e0dce13]

Summary: ✅


AI Review

Summary

This PR adds DDLGuard tracking across ALTER, retries storage-guard acquisition across concurrent renames, and rolls back several metadata fast paths when the durable save fails. The main race it set out to fix is much better covered now, but there are still correctness gaps in the alias path and in the MergeTree setting-derived metadata updates, so this is not ready to merge yet.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterAlterQuery.cpp:365-374] [dismissed by author -- https://github.com/Fix race between ALTER and RENAME/EXCHANGE TABLES #103044#discussion_r3874886761] ALTER TABLE alias ... still reads metadata, runs prepare, and calls checkAlterIsPossible before the target table's DDLGuard is acquired. StorageAlias::alter resolves the target again later, so EXCHANGE TABLES t1 AND t2 can still validate on one target and execute on another. The current 04324 test only exercises the pure comment fast path, so schema-changing alias alters are still exposed.

⚠️ Majors

  • [src/Storages/StorageMergeTree.cpp:512-518] [dismissed by author -- https://github.com/Fix race between ALTER and RENAME/EXCHANGE TABLES #103044#discussion_r3890798841] The pure isSettingsAlter() path still writes the stale new_metadata snapshot back after changeSettings(...) when statistics_changed is true. ALTER TABLE ... MODIFY SETTING auto_statistics_types = 'tdigest', escape_index_filenames = 0 therefore records the new setting in SHOW CREATE, but runtime metadata reverts to the old skip-index filename policy until restart.
  • [src/Storages/StorageMergeTree.cpp:637-695] The non-replicated mixed metadata path has the same stale-snapshot bug the replicated mixed branch was fixed for. changeSettings(...) updates the live escape_index_filenames state, then setProperties(new_metadata, ...) republishes the pre-changeSettings escape_index_filenames / secondary_indices[*].escape_filenames values from commands.apply(...), so a successful mixed ALTER can still leave runtime metadata behind the durable .sql file until restart.
  • [src/Storages/StorageReplicatedMergeTree.cpp:7016-7022] [dismissed by author -- https://github.com/Fix race between ALTER and RENAME/EXCHANGE TABLES #103044#discussion_r3890798844] The replicated pure-settings path still has the same escape_index_filenames clobber as the local MergeTree branch. When auto_statistics_types changes together with escape_index_filenames, setInMemoryMetadata(future_metadata) overwrites the value that changeSettings(...) just committed.
  • [src/Storages/StorageReplicatedMergeTree.cpp:7207-7228] [dismissed by author -- https://github.com/Fix race between ALTER and RENAME/EXCHANGE TABLES #103044#discussion_r3980594808] The lower replicated metadata branch still applies changeSettings(metadata_copy.settings_changes, ...) and then, for mixed setting+comment alters, publishes the older metadata_copy snapshot with stale escape_index_filenames flags. The durable metadata and SHOW CREATE move forward, but this replica keeps the old runtime filename policy until another metadata reload.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Measured on commit e0dce13.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 245/282 (86.88%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 17, 2026
Comment thread src/Storages/StorageAlias.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 8c98baf2-8d9b-4b6a-8541-ad0e63023517
  • MIRAI run: bd552f8f-61a3-43c0-aa97-7451c233c27e
  • PR check IDs:
    • clickbench_154501_1789393969
    • clickbench_154507_1789393968
    • clickbench_154513_1789393968
    • tpch_adapted_1_official_154524_1789393969
    • tpch_adapted_1_official_154540_1789393969
    • tpch_adapted_1_official_154571_1789393969

Comment thread src/Interpreters/DatabaseCatalog.cpp Resolved
Comment thread src/Storages/StorageAlias.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.30% 92.40% +0.10%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 168/193 (87.05%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 16 line(s) · Uncovered code

Full report · Diff report

@SmitaRKulkarni SmitaRKulkarni self-assigned this Jun 23, 2026
Comment thread src/Interpreters/DatabaseCatalog.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Dear @SmitaRKulkarni, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

Comment thread src/Storages/StorageAlias.cpp Resolved
@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

Two behavioral regressions surfaced while reviewing this PR. Both were reproduced on the PR-head CI binary (26.9.1.1, f1c338e) with a pre-PR 26.9.1.1 master build as control.

1. DDL on the table hangs unboundedly (and unkillably) behind a barrier ALTER that is waiting for a pending mutation.

StorageMergeTree::alter releases the DDL guard before the post-commit wait (StorageMergeTree.cpp:816, with a comment explaining why), but the pre-commit barrier waits at StorageMergeTree.cpp:578 and :600 (waitForMutation for the previous mutation) run with the guard held — and those waits are unbounded (until the mutation finishes or is killed). Every other DDL that needs the table's DDLGuard — RENAME TABLE, EXCHANGE TABLES, DROP, DETACH, TRUNCATE, CREATE TABLE of the same name — then blocks inside the untimed table-mutex acquire in the DDLGuard constructor (DatabaseCatalog.cpp:2379), where no lock_acquire_timeout applies and KILL QUERY cannot reach it.

Repro at pure defaults on plain MergeTree:

CREATE TABLE t1 (k UInt64, v UInt64, w UInt64) ENGINE = MergeTree ORDER BY k;
INSERT INTO t1 SELECT number, number, number FROM numbers(1000);
SYSTEM STOP MERGES t1;                    -- stands in for a long-running mutation
ALTER TABLE t1 UPDATE v = v + 1 WHERE 1;  -- pending mutation
ALTER TABLE t1 RENAME COLUMN w TO w2;     -- barrier ALTER: blocks in waitForMutation holding the guard
-- second connection:
RENAME TABLE t1 TO t1_renamed;            -- PR head: hangs; control: completes instantly

On the PR head the RENAME TABLE hung until an external 15 s timeout killed the client (the server-side query stayed blocked); on the control build it completed in under a second while the barrier ALTER kept waiting. The control's instant RENAME is of course the very race this PR fixes, and pre-PR DROP failed loudly with TIMEOUT_EXCEEDED after lock_acquire_timeout on the exclusive table lock — a bounded, retryable error. Post-PR all of these block for the full duration of the mutation, which can be hours, and pile up client threads that cannot be killed. KILL MUTATION remains an escape hatch: in the rig it aborted the waiting ALTER and the queued RENAME then proceeded.

Holding the guard across the wait is load-bearing — releasing it would reopen the fixed corruption for the table_id captured at StorageMergeTree.cpp:479 — so the fix likely needs a timed or periodically re-acquiring wait (fail with a retryable error after lock_acquire_timeout, like the pre-PR DROP did) rather than a release.

2. lock_acquire_timeout = 0 now fails every metadata ALTER, even on an idle table.

tryGetDDLGuardForStorage computes the remaining budget and returns nullptr when it is not positive before making a single acquisition attempt (DatabaseCatalog.cpp:1233), so getDDLGuardForStorage throws. Pre-PR, a zero lock_acquire_timeout was a valid fail-fast configuration: lockForShare and lockForAlter with a zero timeout succeed when uncontended.

Repro: ALTER TABLE t0 MODIFY COMMENT 'hello' SETTINGS lock_acquire_timeout = 0 on an idle table. PR head: Code: 159. DB::Exception: Cannot acquire the DDL guard for default.t0 (...) within 0 ms: a concurrent DDL query is running. (TIMEOUT_EXCEEDED) — note the message is also wrong, no concurrent DDL was running. Control: succeeds. The sharper variant is the MergeTree setting lock_acquire_timeout_for_background_operations = 0: executeMetadataAlter then returns false forever (StorageReplicatedMergeTree.cpp:6775), permanently wedging the replication queue at the ALTER_METADATA barrier with only INFO-level logs. Fix shape: make one zero-wait try_lock attempt when the budget is zero.

For completeness, the rest of the mechanism audited clean on my side: the guard is taken on every metadata-commit path I could find (including the replica queue's executeMetadataAlter, DatabaseReplicated DDL-log replay, and ON CLUSTER), the per-storage wiring is sound (StorageAlias deliberately swaps guards to avoid a deadlock with EXCHANGE, and re-checks under the target guard), and the one constructible lock cycle (alias chain plus EXCHANGE) is bounded by lock_acquire_timeout on one of its edges, so it self-resolves.

@abashkeev abashkeev added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 2026
…e, document the bounded `DDLGuard` re-acquire inversion and name the timeout in its error
{
DatabaseCatalog::instance().getDatabase(table_id.database_name)->alterTable(query_context, table_id, metadata_copy, /*validate_new_create_query=*/true);
}
catch (...)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

changeSettings is still the only code here that writes the setting-derived escape_index_filenames / secondary_indices[*].escape_filenames fields, but this branch writes an older metadata snapshot back afterwards.

Concrete case: ALTER TABLE ... ADD COLUMN y UInt8, COMMENT COLUMN x 'c', MODIFY SETTING escape_index_filenames = 0.

changeSettings(metadata_copy.settings_changes, ...) publishes the new filename policy, then setInMemoryMetadata(metadata_copy) above restores the old escape_index_filenames value from current_metadata, so this replica keeps using the old index filename policy until the ALTER_METADATA entry is replayed locally.

Please refresh metadata_copy.escape_index_filenames and every index.escape_filenames from the post-changeSettings metadata before publishing metadata_copy, the same way the areNonReplicatedAlterCommands() branch already does.

catch (...)
{
/// Revert in-memory so system.* doesn't diverge from SHOW CREATE TABLE.
changeSettings(old_metadata.settings_changes, table_lock_holder);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The pure isSettingsAlter() path now rolls back correctly on save failure, but the same escape_index_filenames clobber is still present lower in StorageMergeTree::alter in the mixed metadata path around 637/695.

Concrete case: ALTER TABLE ... COMMENT COLUMN x 'c', MODIFY SETTING escape_index_filenames = 0.

There, changeSettings(...) installs the new filename policy in the live metadata, then the later setProperties(new_metadata, ...) republishes the pre-changeSettings escape_index_filenames / secondary_indices[*].escape_filenames values that came from commands.apply(...). After a successful ALTER, SHOW CREATE contains the new setting, but runtime code keeps using the old policy until restart.

Please refresh those derived fields from the post-changeSettings metadata before checkMetadataProperties(...), alterTable(...), and setProperties(...), the same way the replicated mixed branch already does.

@qoega

qoega commented Sep 14, 2026

Copy link
Copy Markdown
Member

@evillique green and approved. Let's merge?

@evillique
evillique added this pull request to the merge queue Sep 14, 2026
Merged via the queue into ClickHouse:master with commit 6b982ca Sep 14, 2026
175 checks passed
@evillique
evillique deleted the ddl-guard-for-alter branch September 14, 2026 17:33
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants