Skip to content

Fix UNKNOWN_IDENTIFIER in a multi-command ALTER that changes a column and then mutates it - #130322

Merged
PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-alter-segments-stale-query-metadata-cache
Nov 13, 2026
Merged

PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-alter-segments-stale-query-metadata-cache

Conversation

@groeneai

@groeneai groeneai commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #130110
Related: #92118
Related: #127982
Related: #130528

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 an ALTER TABLE that combines a column change with a mutation or a partition command, such as ALTER TABLE t ADD COLUMN c UInt8, UPDATE c = 1 WHERE c = 0, failing with UNKNOWN_IDENTIFIER (or INCOMPATIBLE_COLUMNS for ATTACH PARTITION ... FROM and MOVE PARTITION ... TO TABLE) when enable_shared_storage_snapshot_in_query is enabled, which is the default. Closes #130110.

Description

On 26.10.2.103 (also 26.6.8.7 and 26.8.18.2, not 26.3.60.2), the repro from #130110 fails with UNKNOWN_IDENTIFIER; it works with enable_shared_storage_snapshot_in_query = 0.

Root cause: runCommandSegments cleared only the metadata cache, and only before the ALTER segment's own reads, which then cache the pre-ALTER metadata again. The later segments analyze against the old columns: MutationsInterpreter::validate, findNonDeterministicVirtualColumn and the partition commands' structure checks.

Change: runCommandSegments calls QueryMetadataCache::clear (added by #130528), which drops both the metadata and the snapshot cache, before the ALTER segment's reads and after it commits. StorageMaterializedView::alter now uses it too instead of its metadata-only clear, with no behaviour change: that path reads no snapshot. The clear is full, since an Alias caches under its target's storage.

Covered: MergeTree, ReplicatedMergeTree, Alias; UPDATE/DELETE after ADD COLUMN or RENAME COLUMN, UPDATE before and after, both partition commands. A Replicated database rejects mixed ALTERs.

Not changed (the same with the setting off): the session_timezone rewrite of DateTime literals uses the columns from before the statement; with alter_sync = 0 ReplicatedMergeTree does not wait before the next command.

Validation: each case of 05616 fails on master (including #130528); with the fix it passes 50 of 50 randomized runs.


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

Version info

  • Merged into: 26.11.1.2209-master (included in 26.11 and later)

groeneai and others added 2 commits November 9, 2026 12:17
`ALTER TABLE t ADD COLUMN c UInt8, UPDATE c = 1 WHERE c = 0` failed with
UNKNOWN_IDENTIFIER `c` when `enable_shared_storage_snapshot_in_query` is
enabled (the default).

`runCommandSegments` runs the segments of one ALTER one after another, but it
cleared only the query-scoped metadata cache, and only before the ALTER
segment's own reads. Those reads re-cache the pre-ALTER metadata, and a mutation
segment that ran earlier leaves its storage snapshot cached.
The following segments then analyze their expressions against the old columns:
`TableNode(storage, context)` in `MutationsInterpreter::validate`,
`findNonDeterministicVirtualColumn` for Replicated tables, and the structure
check of `ATTACH PARTITION ... FROM`.

Drop both caches before the ALTER segment's reads and after it commits. The
clear is full, not per table: an `Alias` table forwards to its target, so the
cache entries are keyed by the target storage. Between segments nothing reads
data through the query's snapshots (mutations execute in background tasks with
their own context, and validation never executes), so the clear does not change
any part set the query reads.

Closes ClickHouse#130110

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the doc comment of dropQueryMetadataCache that restates its body; state the post-ALTER drop as an invariant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings over 2 runs), plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ❌ The session_timezone rewrite of DateTime literals in parseAlterCommandSegments still uses the columns from before the statement, so ADD COLUMN c DateTime, UPDATE c = '...' leaves the literal unwrapped DISAGREE (out of scope: separate PR) The rewrite reads the metadata with the cache bypassed (InterpreterAlterQuery.cpp:242) while the statement is parsed, so it behaves the same with enable_shared_storage_snapshot_in_query = 0; it is not the cache defect this PR fixes. The description says it is not changed.
2 ⚠️ The test does not pin alter_update_mode, so a Stress run with lightweight_force rejects its mixed ALTERs DISAGREE Stress reports only server health, not per-test results (no per-test rows for any Stress check in CIDB over the last 3 days), and the stateless jobs that exercise the fix never randomize alter_update_mode.
3 💡 The post-ALTER snapshot-cache clear has no current reader: the pre-lock clear already drops the snapshot an earlier mutation cached noted, not blocking One helper at both sites keeps the change smallest.
4 💡 MOVE PARTITION ... TO TABLE after ADD COLUMN reads through the cache like ATTACH PARTITION ... FROM and has no dedicated case noted, not blocking Covered by the same full clear.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261109-122300

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's ALTER TABLE t ADD COLUMN c UInt8, UPDATE c = 1 WHERE c = 0 fails on master with UNKNOWN_IDENTIFIER every time; so do the other four cases of the test (UPDATE before and after ADD COLUMN, Alias, ATTACH PARTITION ... FROM, ReplicatedMergeTree).
b Root cause explained? Yes. runCommandSegments cleared only the query metadata cache, and only before the ALTER segment's reads, which cache the pre-ALTER metadata again; an earlier mutation segment leaves its snapshot cached. Later segments analyze against the old columns.
c Fix matches root cause? Yes. Both caches are dropped before the ALTER segment's reads and after it commits; no reader is patched, no setting changed.
d Test intent preserved / new tests added? New SQL test with five cases and one fixture; enable_shared_storage_snapshot_in_query is clamped to 1, checked in system.query_log with a negative control.
e Both directions demonstrated? Yes. Every case fails on master and passes with the fix; each also passes on master with the setting 0, which isolates the cache. 50 of 50 randomized runs pass.
f Fix is general across code paths? Yes. The one clear covers all three later-segment readers (TableNode, findNonDeterministicVirtualColumn, replacePartitionFrom). It is full, not per table, because Alias caches under its target (a per-table variant leaves the Alias case failing).
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers do not apply (cache lifetime). Covered: segment orders, MergeTree / ReplicatedMergeTree / Alias, UPDATE and ATTACH PARTITION FROM.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; behaviour with the setting 0 is unchanged.
i Invariants and contracts preserved? Yes. The two cache mutexes are taken one after the other, never nested. Between segments no data is read through the cache (mutations run in background tasks with their own context, validation never executes), so the one-part-set-per-query promise holds.

Session id: cron:clickhouse-impl-slot-7:20261109-113100

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [33e5c53]

Summary: ✅


AI Review

Summary

The PR clears both query-scoped caches before and after metadata-changing ALTER segments so subsequent mutations and partition commands see the updated schema. It also uses the same cache-clear helper when forwarding column comments through StorageMaterializedView. No actionable findings remain in the current diff after reviewing the surrounding code and all prior discussion. The new 05616_alter_mutation_sees_added_column regression test passed in Fast test at the PR head; tests were not rerun locally.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 9, 2026
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @evillique, could you review this and add the can be tested label so CI runs? In a multi-command ALTER, runCommandSegments cleared the query metadata cache only before the ALTER segment's own reads, which cached the pre-ALTER columns again, so a following UPDATE or partition segment failed with UNKNOWN_IDENTIFIER under the default enable_shared_storage_snapshot_in_query = 1; it now drops both the metadata and the storage-snapshot caches before those reads and after the ALTER commits.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Nov 9, 2026
@PedroTadim PedroTadim self-assigned this Nov 9, 2026
…n one ALTER

Each of these also reads the table through the query-scoped caches after the
preceding ALTER segment committed, and fails on master with
enable_shared_storage_snapshot_in_query = 1:
- RENAME COLUMN v TO w, UPDATE w = ... WHERE w = ...: UNKNOWN_IDENTIFIER w
- ADD COLUMN c, DELETE WHERE c = 0: UNKNOWN_IDENTIFIER c
- ADD COLUMN e, MOVE PARTITION ... TO TABLE: INCOMPATIBLE_COLUMNS

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

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 33e5c53ab with master 1f096f12b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.65, programs/clickhouse-keeper ×0.64 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.9 s 14.5 s +10.7 s (+280%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.5 s +5.3 s (+237%)
Compile time of recompiled translation units

8 translation units recompiled, 32 s compile time in total, 8 of them have a recent master baseline.

Job report

…et's lock

runCommandSegments clears the query-scoped caches after taking the locks of the
table it ALTERs, but for an Alias those are the alias's own locks: the reads that
follow cache the target's metadata, and StorageAlias::alter takes the target's
DDLGuard and alter lock only later. StorageMergeTree::alter then builds the new
metadata from that cached copy, so a concurrent ALTER of the target that committed
in between is overwritten. Measured: 150 ALTER ... ADD COLUMN through the alias
concurrently with 150 directly on the target leave 151 columns instead of 301 with
enable_shared_storage_snapshot_in_query = 1, and 301 with it set to 0.

Clear the caches again once the target's alter lock is held, as
StorageMaterializedView::alter does for its inner table. The clear of both caches
moves into QueryMetadataCache::clear, also used by runCommandSegments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 9, 2026
@PedroTadim

PedroTadim commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

🕵️ @groeneai Reviewed — the fix is correct and well-targeted for its scope, and CI is green. One sibling gap worth folding into this PR:

src/Storages/StorageMaterializedView.cpp:980-984 still uses the old metadata-only clear.

This PR introduces QueryMetadataCache::clear() precisely because clearing only the metadata cache leaves a stale snapshot-cache entry pinned (under the default enable_shared_storage_snapshot_in_query = 1), and applies the full clear in both InterpreterAlterQuery::runCommandSegments and StorageAlias::alter. But StorageMaterializedView::alter, which forwards a column-comment ALTER to the inner table after taking the inner table's alter lock, still does:

if (auto metadata_cache = local_context->getQueryMetadataCache())
{
    auto [cache, cache_lock] = metadata_cache->getStorageMetadataCache();
    cache->clear();
}

Its own comment ("the alter below reads the inner table's metadata through that cache") is the same premise as the StorageAlias fix, so this is the third instance of the pattern you're unifying and is now inconsistent with the other two — and plausibly the same latent concurrent-overwrite bug for an MV whose inner table is altered concurrently.

Suggested fix (same one-liner as the other two sites):

if (auto metadata_cache = local_context->getQueryMetadataCache())
    metadata_cache->clear();

If you believe the inner comment-only alter can't be affected by the snapshot cache (e.g. it never re-resolves through getStorageSnapshotForQuery), it'd be good to state that reasoning so the three sites don't silently diverge.

The column-comment ALTER that a materialized view forwards to its inner table
cleared only the metadata half of the query caches after taking the inner
table's alter lock. Use the same full clear as runCommandSegments and
StorageAlias::alter, so the three sites do not diverge.

No behaviour change: nothing on that path reads through the snapshot cache
(checkAlterIsPossible and the MergeTree alter read only metadata). Measured:
20 COMMENT COLUMN through the view racing 20 ADD COLUMN on the inner table keep
all 21 columns with this change and on master, and keep 1 to 7 when the clear
is removed entirely.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 24738af: StorageMaterializedView::alter now calls metadata_cache->clear() like the other two sites, and the description mentions it.

It changes no behaviour there, because that path reads no snapshot: checkAlterIsPossible and StorageMergeTree::alter / StorageReplicatedMergeTree::alter go through getInMemoryMetadataPtr only, never getStorageSnapshot. Measured with 20 COMMENT COLUMN through the view racing 20 ADD COLUMN directly on the inner table: all 21 columns survive on master and with this change (5 of 5 runs; 151 of 151 with 150 of each), and only 1 to 7 survive when the clear is removed entirely. So the metadata half is the one that matters at this site, and I did not add a test for it, since it cannot fail on master.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
…its target

The commands are prepared again against the target's current metadata, but
`checkAlterIsPossible` and the target's `alter` then read the metadata the
query cached before the target's lock (`enable_shared_storage_snapshot_in_query = 1`).
When a concurrent ALTER of the target dropped enum values in between, the
re-prepared `ADD ENUM VALUES` looked like a type change against that stale copy
and was persisted as a mutation without a type, so the table could no longer be
attached (`MODIFY COLUMN mutation command doesn't specify type`).

`QueryMetadataCache::clear` and the clear in `StorageAlias::alter` are the same
as in ClickHouse#130322.

05618 gains a case where the target's enum is replaced concurrently.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai I am about to merge #130528 it also introduces QueryMetadataCache::clear() can you update this PR after that one gets merged?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes. #130528 is in the merge queue now; once it is in master I will update this PR on top of it and drop the duplicated QueryMetadataCache::clear() and StorageAlias::alter hunks.

groeneai and others added 2 commits November 13, 2026 09:24
…stale-query-metadata-cache

# Conflicts:
#	src/Storages/StorageAlias.cpp
The clear in `StorageAlias::alter` that 05617 tested now comes from ClickHouse#130528,
and its test 05618 fails without that clear as well (19 mutations instead of 0,
5 of 5 runs; 05617 gives 21 columns instead of 41).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Updated: merged master with #130528 in 0cfdb5e, taking its side of the StorageAlias::alter conflict. QueryMetadataCache::clear() and the StorageAlias::alter change now come from master, so this PR only changes runCommandSegments (clear before and after the ALTER segment) and StorageMaterializedView::alter, plus 05616.

I also removed 05617 in 33e5c53: without the StorageAlias::alter clear, 05618 from #130528 fails too (19 mutations instead of 0, 5 of 5 runs).

Every case of 05616 still fails on master with #130528 merged, and passes 50 of 50 randomized runs with this PR. The description is updated.

@PedroTadim
PedroTadim enabled auto-merge November 13, 2026 10:30
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 048029b Nov 13, 2026
204 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 Nov 13, 2026
buggins added a commit to buggins/ClickHouse that referenced this pull request Nov 14, 2026
…napshot

The merged master has ClickHouse#130322, which refreshes the shared snapshot of the
query between the segments of an `ALTER`, so 05483 no longer needs `enable_shared_storage_snapshot_in_query = 0`.

Related: ClickHouse#123959
Related: ClickHouse#130110

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

ALTER TABLE ... ADD COLUMN c ..., UPDATE ... c ... fails with UNKNOWN_IDENTIFIER with the default enable_shared_storage_snapshot_in_query

3 participants