Skip to content

Fix flaky test_replicated_table_structure_alter - #111029

Merged
tavplubix merged 11 commits into
ClickHouse:masterfrom
tiandiwonder:fix-alter-comment-metadata-snapshot-cache
Jul 24, 2026
Merged

tavplubix merged 11 commits into
ClickHouse:masterfrom
tiandiwonder:fix-alter-comment-metadata-snapshot-cache

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #110036
Regression of : #107491
PRs fixes the same failure: #110145, #110030

Original pr of metadata pin: #79471

Problem

A comment-only or settings-only ALTER on a ReplicatedMergeTree can silently drop a column added by a concurrent ALTER ... ADD COLUMN. This surfaced as the flaky integration test test_replicated_database::test_replicated_table_structure_alter, which regressed on 2026-07-10.

Root cause — by example

Two ALTERs race on the same replica of a Replicated database table rmt (n, v):

  • on replica1: ALTER TABLE rmt ADD COLUMN m Int32 — structural, replicated as an ALTER_METADATA log entry and applied on every replica by executeMetadataAlter (under lockForAlter);
  • on replica2: ALTER TABLE rmt COMMENT COLUMN v 'x' — comment-only, executed locally on each replica via the early-return branch in StorageReplicatedMergeTree::alter (holds only the alter lock, commits with setInMemoryMetadata).

The commit base in alter was read as getInMemoryMetadataPtr(query_context, /*bypass=*/false) — the query-scoped snapshot cache (enable_shared_storage_snapshot_in_query, default on). That cache pins the first bypass=false read of the query and returns it for the rest of the query, regardless of any lock taken later.

The pinning read moved before the alter lock in #107491: it added isRowExistsLightweightDeleteMarker → getInMemoryMetadataPtr(context, /*bypass=*/false) into InterpreterAlterQuery::getRequiredAccess, i.e. into the access check, which runs before lockForAlter. Timeline on replica2:

 t0  getRequiredAccess (access check, no lock)
       └─ isRowExistsLightweightDeleteMarker → getInMemoryMetadataPtr(ctx, false)   [ADDED BY #107491]
          → pins the query metadata cache to (n, v)          ← pre-lock snapshot
 t1  lockForAlter acquired
 t2                                     executeMetadataAlter applies ADD COLUMN m
                                        under lockForAlter → structure = (n, v, m)
 t3  alter(): getInMemoryMetadataPtr(ctx, false)
       └─ cache hit → (n, v)            ← STALE (pinned at t0, before the lock)
 t4  setInMemoryMetadata((n, v) + comment)   → overwrites (n, v, m), column m lost

replica_path/metadata_version stays equal to the ZooKeeper /metadata version throughout, so SYSTEM SYNC REPLICA cannot detect or repair the divergence.

Before #107491 there was no bypass=false read earlier in the query, so alter's own read at t3 was the first one — it happened after lockForAlter and therefore returned the current, under-lock structure. bypass=false was effectively equivalent to a fresh read, and the bug did not occur. #107491 did not change alter; it only moved the cache-pinning point ahead of the lock, which exposed the latent dependency of a commit path on the query cache.

Solution

Clear the query-scoped metadata cache (enable_shared_storage_snapshot_in_query) right after acquiring lockForAlter in InterpreterAlterQuery::runCommandSegments. The next getInMemoryMetadataPtr(context, /*bypass_metadata_cache=*/false) repopulates it from the metadata committed as of holding the lock, so validate, prepare, checkAlterIsPossible and the storage's alter all read one fresh under-lock snapshot. Committed metadata cannot change while lockForAlter is held, so a snapshot pinned before the lock can no longer become the commit base and drop a concurrently added column. The storage-side reads are left unchanged.

Why not bypass the cache at the reads instead. The first attempt read the commit base with bypass=true in the storage alter methods. That fixed the apply side but left InterpreterAlterQuery validating the commands against the still-pinned (stale) snapshot; under a concurrent DROP COLUMN, a command validated against the old structure was then applied to a fresh one missing the column, aborting with LOGICAL_ERROR: Cannot find column ... in ColumnsDescription. It also left the pin itself in place.

Why clear() and why the runCommandSegments read flips to bypass=false. The essential fix is the single clear(): once the pre-lock pin is discarded, every bypass=false reader below — validate (AlterCommands::validate reads bypass=false), checkAlterIsPossible, and the storage alter's commit-base read — repopulates from the current under-lock metadata. The metadata_snapshot read at the top of the AlterCommands branch is also switched from bypass=true to bypass=false so that prepare uses that same repopulated cache entry instead of a separate (content-identical, since metadata is frozen under the lock) fresh read; clear() alone would already prevent the column drop, but this keeps all consumers on one snapshot object. The storage alter reads themselves need no change.

Resulting behavior. For the #110036 race (comment/settings ALTER vs a concurrent ADD COLUMN) no error is raised and the added column is preserved. For a genuinely conflicting command — e.g. the target column was removed by a concurrent DROP COLUMN — validate and the apply now read the same fresh snapshot, so validate rejects it up front with a normal user error (NOT_FOUND_COLUMN_IN_BLOCK, "Wrong column. Cannot find column X to modify") rather than the internal LOGICAL_ERROR the first attempt produced. No hot-path impact — this is the DDL path.

A regression test test_alter_comment_races_replicated_alter_metadata (wide table + SYSTEM STOP/START REPLICATION QUEUES to overlap the two ALTERs) fails without the fix (lost column) and passes with it. A second test test_mixed_alter_races_replicated_alter_metadata covers the full-ALTER path the same way.

Changelog category (leave one):

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

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

Fixed a rare race where a comment-only or settings-only ALTER of a ReplicatedMergeTree table could silently drop a column added by a concurrent ALTER ... ADD COLUMN, leaving a replica on an outdated table structure.

Version info

  • Merged into: 26.8.1.79 (included in 26.8 and later)

A comment-only or settings-only `ALTER` on a `ReplicatedMergeTree` could
silently drop a column added by a concurrent `ALTER ... ADD COLUMN`.

`StorageReplicatedMergeTree::alter` (and `StorageMergeTree::alter`) built the
committed metadata from `getInMemoryMetadataPtr(context, /*bypass=*/false)`,
which returns the query-scoped shared snapshot
(`enable_shared_storage_snapshot_in_query`). That snapshot can be pinned
earlier in the same query - e.g. by the access check in
`InterpreterAlterQuery::getRequiredAccess`, which runs before `lockForAlter` -
to the pre-`ALTER` structure. The comment/settings branches then commit that
stale snapshot via `setInMemoryMetadata` while holding only the alter lock,
overwriting an `ALTER_METADATA` that `executeMetadataAlter` applied
concurrently (also under `lockForAlter`) and dropping the newly added column,
while `replica_path/metadata_version` stays equal to the ZooKeeper
`/metadata` version.

Read the commit base fresh (`bypass_metadata_cache=true`) under the held
alter lock, matching what `InterpreterAlterQuery` already does for validation
and what the mutation path does, so the alter lock's serialization against
`executeMetadataAlter` is effective.

Surfaced as the flaky integration test
`test_replicated_database::test_replicated_table_structure_alter`.

Closes: ClickHouse#110036

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4336567]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Changed settings are not reflected in the settings changes history (see changed_settings.txt) FAIL cidb
New settings are not reflected in settings changes history (see new_settings.txt) FAIL cidb
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR moves the stale-metadata fix into InterpreterAlterQuery: after lockForAlter it clears the query-scoped metadata cache so validation, preparation, and alter all repopulate from one fresh under-lock snapshot, and the new integration helpers now fail if the synchronized ALTER returns an exception. That addresses the #110036 race, but one previously raised correctness bug in the same replicated structural-ALTER path is still present, so the review remains a request for changes.

Findings

⚠️ Majors

  • [src/Storages/StorageReplicatedMergeTree.cpp:6990-7014, src/Storages/MergeTree/MergeTreeData.cpp:5852-5865] [dismissed by author -- https://github.com/Fix flaky test_replicated_table_structure_alter #111029#discussion_r3612891589] A replicated structural ALTER that mixes MODIFY SETTING escape_index_filenames = ... with a local comment/settings commit still restores stale setting-derived metadata after changeSettings succeeds. changeSettings updates storage_settings and publishes a fresh metadata snapshot with the new escape_index_filenames and per-index escape_filenames, but this branch then clones *current_metadata, mutates only settings_changes and comment, and setInMemoryMetadata(metadata_copy) writes the old escape flags back. The table therefore keeps using the old index-filename policy until restart even though the persisted metadata already records the new setting.
    Suggested fix: mirror the refresh already used in commands.areNonReplicatedAlterCommands() by re-reading the committed metadata after changeSettings and copying the setting-derived fields into metadata_copy before any setInMemoryMetadata or alterTable call, or build metadata_copy from the freshly committed snapshot instead of *current_metadata.
Tests
  • ⚠️ Add a focused regression for a plain ReplicatedMergeTree in an Atomic database that runs ALTER TABLE ... ADD COLUMN x UInt8, MODIFY SETTING escape_index_filenames = 0, MODIFY COMMENT 'c' and asserts the live metadata used for index file naming switches immediately, not only after restart.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Jul 20, 2026
@tiandiwonder tiandiwonder changed the title Do not commit a stale query-cached metadata snapshot in ALTER Fix flaky test_replicated_table_structure_alter #111029 Jul 20, 2026
@tiandiwonder tiandiwonder changed the title Fix flaky test_replicated_table_structure_alter #111029 Fix flaky test_replicated_table_structure_alter Jul 20, 2026
The previous commit fixed the comment/settings early-return branches, but
`StorageReplicatedMergeTree::alter`'s full (structural) ALTER path reads
`current_metadata` the same stale way inside its ZooKeeper retry loop, and
still commits bundled comment/settings changes from it locally via
`setInMemoryMetadata`/`alterTable` before the versioned `/metadata` write.

When that snapshot is pinned before `lockForAlter` (by the access check), a
mixed `ALTER` (e.g. `ADD COLUMN x, MODIFY COMMENT '...'`) racing a
concurrently applied `ALTER_METADATA` silently drops the concurrently added
column locally and fails the query with `CANNOT_ASSIGN_ALTER`; the persisted
`metadata_version` stays equal to the ZooKeeper version, hiding the
divergence. Reachable on a plain `ReplicatedMergeTree` in an Atomic database
(`Replicated` databases reject mixed replicated/non-replicated ALTERs).

Read `current_metadata` fresh (`bypass_metadata_cache=true`) here too.

Adds regression test `test_mixed_alter_races_replicated_alter_metadata`
covering this full-ALTER path (fails without this commit, passes with it).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
/// the access check) to a pre-ALTER structure. Here it also backs the bundled comment/settings local
/// commit below (setInMemoryMetadata/alterTable) and the versioned zookeeper_path/metadata write, so a
/// stale base would drop a concurrently applied column and write an outdated metadata_version.
auto current_metadata = getInMemoryMetadataPtr(query_context, true);

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.

current_metadata is fresh now, but the bundled local settings/comment commit below still overwrites setting-derived in-memory metadata. In the structural path, metadata_copy starts from *current_metadata, changeSettings(metadata_copy.settings_changes, ...) publishes the new escape_index_filenames value, and then setInMemoryMetadata(metadata_copy) at 6997 writes the old flag back because metadata_copy only copied settings_changes and the comment. A query like ALTER TABLE ... ADD COLUMN x UInt8, MODIFY SETTING escape_index_filenames = 0, MODIFY COMMENT 'c' on a plain ReplicatedMergeTree in an Atomic database will therefore keep using the old index filename policy until restart, even though the metadata file records the new setting. This branch needs the same refresh-from-committed-metadata handling as the areNonReplicatedAlterCommands() path above.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed real, but pre-existing and orthogonal to this stale-snapshot fix (the bypass=true change is neutral to it): the bundled setInMemoryMetadata(metadata_copy) reverts the escape_index_filenames metadata field (and per-index escape_filenames) that changeSettings set. Tracking as a separate follow-up to verify and fix across the settings-only and on-disk sub-cases, rather than widening this PR.

Trim the explanatory comments to the load-bearing point (the query cache can
be pinned before lockForAlter, so the commit base must be read fresh under
the lock). No behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Outdated
/// (e.g. by the access check that runs before lockForAlter) to a pre-ALTER structure. The
/// comment- and settings-only branches below commit this snapshot via setInMemoryMetadata under
/// the alter lock; a stale base would overwrite a concurrently applied ALTER and drop columns.
auto metadata_snapshot = getInMemoryMetadataPtr(local_context, true);

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.

Suggested change
auto metadata_snapshot = getInMemoryMetadataPtr(local_context, true);
auto metadata_snapshot = getInMemoryMetadataPtr(local_context, /*bypass_metadata_cache*/ true);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done — removed all three duplicated comments and inlined the argument as /*bypass_metadata_cache*/ true at every call site; the rationale now lives in the commit message and PR body. (commit 4623581)

@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.30% -0.10%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code

Full report · Diff report

@tavplubix
tavplubix enabled auto-merge July 24, 2026 11:10
@tavplubix
tavplubix added this pull request to the merge queue Jul 24, 2026
Merged via the queue into ClickHouse:master with commit 78515f4 Jul 24, 2026
176 of 178 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 24, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Jul 26, 2026
…ta-snapshot-cache

Fix flaky test_replicated_table_structure_alter

(cherry picked from commit 78515f4)
clickhouse-gh Bot added a commit that referenced this pull request Jul 26, 2026
Backport #111029 to 26.7: Fix flaky test_replicated_table_structure_alter
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 3, 2026
Picks up the fixing PRs for the three trunk-flaky integration reds on the
previous head: ClickHouse#111029 (test_replicated_table_structure_alter, merged 07-24)
and ClickHouse#111353 (test_check_all_tables, merged 07-22). Base was 6193 commits
behind, so CI was also stale.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The AI review noted both regression tests would still pass if the
synchronized `ALTER` under overlap returned an exception instead of
succeeding: the comment-only helper ignored `race_out` errors and the
mixed helper recorded `alter_error` without failing on it. Now a cycle
that reached `SYNC_FOUND=1` raises on any `DB::Exception` / `Code:`
output, so the tests also prove the "no error under overlap" behavior
promised by the fix, closing the false-pass mode where the race would
regress from silent clobber to always-throw.

ClickHouse#111029
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ent-metadata-snapshot-cache

Fix flaky test_replicated_table_structure_alter
@PedroTadim

Copy link
Copy Markdown
Member

backporting to fix CI

@robot-ch-test-poll2 robot-ch-test-poll2 added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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 v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: test_replicated_database/test.py::test_replicated_table_structure_alter (regression since 2026-07-10)

7 participants