Skip to content

Refresh TO-target materialized view columns when upstream tables are altered - #107149

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-mv-to-target-stale-columns-on-alter-106919
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-mv-to-target-stale-columns-on-alter-106919

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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 DESCRIBE and SHOW CREATE TABLE reporting stale column types for a materialized view created with TO target after the source or target table columns were changed with ALTER TABLE ... MODIFY COLUMN. Previously the view kept the types inferred at creation time, which also made SELECT from the view fail (for example with UNKNOWN_ELEMENT_OF_ENUM) when the new types were incompatible. The view's inferred columns are now refreshed on the upstream ALTER; explicit-column views keep their declared types.

Description

After an ALTER that changes a table's columns, the column metadata of dependent TO-target materialized views is refreshed when their stored columns are still in sync with the view's SELECT output (recomputed against the pre-ALTER schema). The refresh re-runs the same SELECT-output inference used at create time, so inferred-column views track the new upstream types while explicit-column views (TO t (x String) ...) and views whose columns intentionally diverge from the SELECT output (e.g. SELECT 1 AS v2 over a wider target column) are left untouched. Existing tests 02931, 01069, 01182 keep their current behavior; new test: 04327_mv_to_target_columns_refresh_on_alter.

…altered

A materialized view created as `CREATE MATERIALIZED VIEW mv TO target AS SELECT ...`
infers its column list from the SELECT output at creation time and freezes it. When the
source or target table columns later change via `ALTER TABLE ... MODIFY COLUMN`, the view's
stored columns are not refreshed, so:

- `DESCRIBE mv` and `SHOW CREATE TABLE mv` report stale types;
- `SELECT * FROM mv` can fail (e.g. `UNKNOWN_ELEMENT_OF_ENUM`) because the read path casts
  the target's current data down to the view's frozen column types.

After an ALTER that changes a table's columns, refresh the column metadata of dependent
TO-target materialized views whose stored columns are still in sync with their SELECT output
(recomputed against the pre-ALTER schema). The refresh re-runs the same SELECT-output
inference used at create time, so inferred-column views track the new upstream types while
explicit-column views (`TO t (x String) ...`) and views whose columns intentionally diverge
from the SELECT output (e.g. `SELECT 1 AS v2` over a wider target column) are left untouched.

The inference reads upstream tables with `enable_shared_storage_snapshot_in_query=false` so
it sees the post-ALTER schema rather than the per-query metadata snapshot cached by the
triggering ALTER.

Closes ClickHouse#106919

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE MATERIALIZED VIEW mv TO target AS SELECT id, status, count() AS cnt FROM source GROUP BY id, status; then ALTER TABLE source MODIFY COLUMN status Enum8('A'=0,'B'=1,'C'=2); + same on target. On master DESCRIBE mv returns the stale Enum8('A'=0,'B'=1) and SELECT * FROM mv after inserting 'C' throws Code 691 UNKNOWN_ELEMENT_OF_ENUM every time.
b Root cause explained? A TO-target MV infers its column list from the SELECT output at create time and freezes it (InterpreterCreateQuery, columns_inferred_from_select_query). Nothing refreshes those stored columns when an upstream ALTER changes the source/target types. DESCRIBE/SHOW CREATE then read the frozen list, and StorageMaterializedView::readImpl casts the target's current data down to the frozen column types, which fails when the new enum value has no slot in the old type.
c Fix matches root cause? Yes. The fix refreshes the frozen stored columns at the moment the cause occurs (the upstream ALTER), recomputing the SELECT-output schema against the new upstream types. It does not widen/loosen the read-path cast or suppress the error.
d Test intent preserved / new tests added? Yes. New stateless test 04327_mv_to_target_columns_refresh_on_alter covers the fix plus the three contracts it must not break (02931 MODIFY QUERY divergence, 01069 target ADD COLUMN not exposed, 01182 explicit columns kept). Existing 02931/01069/01182 were run and keep their references.
e Both directions demonstrated? Yes. On the unfixed master binary the new test diffs (stale enum + Code 691). On the patched binary it passes. Verified by running the same .sql against both a baseline (snapshot) server and the patched server on separate ports.
f Fix is general, not a narrow patch? Yes. It refreshes every dependent inferred TO-target MV found via getDependentViews, on the general column-changing ALTER path (not just enums), and is gated so explicit-column and intentionally-divergent views are never rewritten. It targets the root (stale frozen metadata) rather than guarding the crash site. Known limitation, documented: views created before this change keep their already-baked stale block until a subsequent upstream ALTER re-syncs them; plain VIEWs are not covered in this PR.

Session id: cron:clickhouse-worker-slot-7:20260611-023300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @al13n321 — could you review this? It refreshes the inferred column metadata of a TO-target materialized view when an upstream ALTER ... MODIFY COLUMN changes the source/target types, so DESCRIBE/SHOW CREATE stop reporting stale types and SELECT from the view no longer fails (e.g. UNKNOWN_ELEMENT_OF_ENUM). The refresh is gated to in-sync inferred-column views, so explicit-column and intentionally-divergent views are left untouched (closes #106919).

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2f79c81]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
Build ClickHouse FAIL
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026

auto table_id = getStorageID();
DatabaseCatalog::instance().getDatabase(table_id.database_name)
->alterTable(query_context, table_id, new_metadata, /*validate_new_create_query=*/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.

IDatabase::alterTable is documented to be called under the corresponding table's alter_lock, but this path updates the materialized view metadata without taking the view's lockForAlter. A concurrent ALTER MATERIALIZED VIEW ... MODIFY QUERY or column alter can race with this refresh: both paths clone metadata, call alterTable, and then setInMemoryMetadata, so the last writer can silently drop the other metadata change.

Please acquire the view's alter lock around the re-read, eligibility check, metadata write, and setInMemoryMetadata, and re-check that the view is still eligible while holding that lock before calling alterTable.

return {};

/// Resolve unqualified table references in the view's own database, mirroring CREATE/MODIFY QUERY.
ContextMutablePtr select_context = Context::createCopy(query_context);

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.

Materialized view execution builds its SELECT context through getSQLSecurityOverriddenContext, but this inference uses the altering user's context. For a SQL SECURITY DEFINER view, a user may have ALTER on the source table without direct SELECT on every table referenced by the view; getSampleBlock then throws ACCESS_DENIED, this method catches it, and the view remains stale even though normal MV execution would use the definer.

Please build select_context from the view metadata's SQL-security context, then set the MV database and enable_shared_storage_snapshot_in_query override, and add a regression with a definer MV altered by a user lacking direct SELECT.

/// the new types are incompatible with the frozen ones. Capture the views that are in sync
/// with their SELECT output *before* the change, then re-infer their columns afterwards.
std::vector<StoragePtr> dependent_views;
if (!alter_commands->isSettingsAlter() && !alter_commands->isCommentAlter())

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.

This also runs for ADD COLUMN. For CREATE MATERIALIZED VIEW mv TO dst AS SELECT * FROM src, ALTER TABLE src ADD COLUMN b UInt8 collects the view before the alter, then post-alter inference returns (a, b) and refreshes mv, while dst still only has a. Inserts through the MV then fail in StorageInMemoryMetadata::check with NO_SUCH_COLUMN_IN_TABLE for b, and SELECT b FROM mv asks the target for a column it does not have.

The current test covers target-side ADD COLUMN, not source-side ADD COLUMN. Please either restrict the refresh to the MODIFY COLUMN/type-change case this PR fixes, or validate the new inferred header against the target table before storing it and add a source ADD COLUMN regression.

continue;

auto inferred = mv->tryInferColumnsFromSelectQuery(context);
if (inferred && mv->getInMemoryMetadataPtr(context, false)->columns == *inferred)

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.

Using equality with the current inferred header as the only "inferred-column" test also matches explicit-column views whose declared list happens to equal the old SELECT output. For example, CREATE MATERIALIZED VIEW mv TO dst (n UInt64) AS SELECT n FROM src; then ALTER TABLE src MODIFY COLUMN n Int64. Before the alter, the stored columns equal the inferred UInt64 header, so this view is collected; after the alter, refreshColumnsFromSelectQueryIfInferred rewrites the explicit n UInt64 to n Int64. That violates the PR contract that explicit-column views keep their declared types and changes DESCRIBE / SHOW CREATE for explicit schemas.

Please persist or otherwise derive the actual "columns inferred from SELECT" state instead of using header equality, or skip explicit column-list views, and add the same-type explicit-column regression.

…ped re-inference

Two fixes for CI failures on this PR:

1. Fast test 02697_alter_dependencies: the previous gate triggered the
   dependent-view column re-inference on every alter that was not a pure
   settings or comment alter, including MODIFY TTL. Re-inference analyzes the
   view's SELECT, which executed the functions in 02697's MV (sleepEachRow,
   numbers) and broke its assertion that ALTER ... MODIFY TTL executes no MV
   functions. Add AlterCommands::changesColumns() and gate the re-inference on
   it so only ADD/DROP/MODIFY/RENAME COLUMN alters pay the analysis cost.

2. Style check (catch_all): the catch(...) in tryInferColumnsFromSelectQuery
   silently swallowed the exception. Log it at debug level before returning
   nullopt.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
/// Read the upstream tables' current schema, not the per-query metadata snapshot cached by the
/// triggering ALTER (MergeTreeData::getInMemoryMetadataPtr caches metadata per query when this
/// setting is on, which would otherwise return the pre-ALTER columns here).
select_context->setSetting("enable_shared_storage_snapshot_in_query", Field(false));

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.

This override can be undone by the stored view query itself. Both select analyzers apply SELECT ... SETTINGS while building the sample block; if the MV was created as ... AS SELECT ... SETTINGS enable_shared_storage_snapshot_in_query = 1, that setting is applied after this line and the internal sample can read the per-query cached pre-ALTER metadata again. In that case the post-ALTER inference returns the old header and the refresh silently leaves the MV stale, which is exactly what this override is meant to prevent.

Please force enable_shared_storage_snapshot_in_query = 0 after applying the stored SELECT settings, or strip/ignore just this setting for the internal inference context, and add a regression with this query setting on the MV SELECT.

std::vector<StoragePtr> collectInferredDependentMaterializedViews(const StorageID & source_table_id, const ContextPtr & context)
{
std::vector<StoragePtr> result;
for (const auto & view_id : DatabaseCatalog::instance().getDependentViews(source_table_id))

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 PR promises that changing either the source or the TO target refreshes the MV schema, but this walks only DatabaseCatalog::getDependentViews(source_table_id), i.e. the source-side MV dependency. The TO table is registered as a referential dependency, not as a dependent view, so ALTER TABLE target MODIFY COLUMN status Enum8('A' = 0, 'B' = 1, 'C' = 2) does not collect mv.

That leaves a target-only type evolution on the old failure path: if target then contains the new enum value (for example through a direct insert), SELECT * FROM mv still reads the target and converts it down to the frozen MV enum, so UNKNOWN_ELEMENT_OF_ENUM can still be thrown. Please either narrow the contract/changelog to source-SELECT output changes, or implement and test the target-side case explicitly while preserving the existing intentional-divergence cases.

@@ -0,0 +1,70 @@
-- Tags: no-parallel

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.

This no-parallel tag does not look justified: the test uses ordinary DDL in the current test database and checks only its own tables, so parallel stateless execution should not make DESCRIBE output unstable. no-* tags serialize CI work and should be used only when a test touches a shared external resource or has a concrete cross-test interference mode.

Please remove the tag, or document the specific shared state that makes parallel execution unsafe.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the review, all four points are real (I reproduced #3 and #4 locally). #2 (DEFINER context), #1 (alter lock), the 02697_alter_dependencies failure (the eager re-inference runs the view's SELECT during ALTER, executing a table function the test forbids) and the #3 narrowing (restrict to column type changes, validate against the target) I can fix directly. But #3 and #4 expose one design question I want to confirm with you before reworking.

There is no persisted "columns were inferred" signal. An inferred-column view and an explicit view with the same types store byte-identical metadata:

CREATE MATERIALIZED VIEW mv_inf TO tgt AS SELECT id, n FROM src;
CREATE MATERIALIZED VIEW mv_exp TO tgt (id UInt64, n UInt64) AS SELECT id, n FROM src;
-- identical SHOW CREATE / system.tables.create_table_query

columns_inferred_from_select_query lives only in InterpreterCreateQuery::TableProperties and is never persisted; table metadata is stored as the CREATE-query text, so the signal has to live in the AST. So the header-equality gate (#4) cannot skip explicit views, and after reload nothing tells them apart. A pure read-path fix is not enough either: an explicit mv TO dst (n String) over dst (n UInt8) must keep returning String, so the read path cannot just adopt the target's types. The gate is unavoidable and must be persisted.

Two ways to persist it:

  • A. Persist an inferred marker in the stored AST and gate the refresh on it.
  • B. Don't store the inferred column block (your reporter's idea, absence == inferred). Also fixes SHOW CREATE + reload, but changes SHOW CREATE for every inferred view and needs the has_structure/ALTER path taught about block-less TO views (today one throws in applyMetadataChangesToCreateQuery).

You expected this to be easy, so you may have a lighter mechanism in mind. Which direction do you prefer? I will fold in #1 and #2 and the #3 narrowing regardless, with regressions for the DEFINER, explicit-same-type, and source ADD COLUMN cases.

@PedroTadim

cron:clickhouse-worker-slot-3:20260611-101600

The MV-to-target column refresh added in this PR runs after the triggering
ALTER inside InterpreterAlterQuery::runCommandSegments. On a Replicated
database, that ALTER executes inside a single-table ZooKeeperMetadataTransaction
which is already committed by table->alter() by the time the refresh runs.

refreshColumnsFromSelectQueryIfInferred then issued a second persisted
database->alterTable() for the view, which DatabaseReplicated::commitAlterTable
turns into txn->addOp() on the now-executed transaction. That raises the
LOGICAL_ERROR "Cannot add ZooKeeper operation because query is executed" and
aborts the server (seen as a TSAN stress "Server died").

Refresh the view's columns in memory only when an active metadata transaction
is present: each replica replays the same upstream ALTER and re-infers the same
columns, so DESCRIBE / system.columns stay consistent, while the persisted
statement and the database metadata digest are left untouched (no digest drift
or recovery). The non-replicated path keeps persisting the refresh as before.

Adds 04328_mv_to_target_refresh_on_alter_replicated_db, which reproduces the
crash deterministically by running the ALTER scenario on a Replicated database.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
/// The triggering ALTER's metadata transaction (Replicated database) is already committed here, so a second
/// persisted alterTable would add an op to an executed transaction. Refresh in memory only; each replica
/// replays the upstream ALTER and re-infers identical columns, leaving the persisted statement and digest intact.
if (query_context->getZooKeeperMetadataTransaction())

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.

This branch makes the refresh non-durable for Replicated databases. The source and target ALTERs are persisted, but the materialized view's stored CREATE statement in ZooKeeper/local metadata still contains the old column list; after a server restart, recovery, or a new replica loading metadata, mv comes back with stale columns and SELECT can hit the same UNKNOWN_ELEMENT_OF_ENUM path again. The new test only observes the live in-memory metadata before reload.

Please make the refreshed view metadata durable as well, e.g. by adding it to a still-open replicated metadata update or by scheduling a separate replicated metadata update after the source ALTER; then add a restart/reload or second-replica regression.

…rentDatabase()

The new regression test queried system.columns filtered by
database = {CLICKHOUSE_DATABASE_1:String}, which the style check
(ci/jobs/scripts/check_style/various_checks.sh) does not accept: it only
recognizes database = currentDatabase(), database = $CLICKHOUSE_DATABASE,
or a quoted literal.

USE the test's self-created Replicated database before the system.columns
query so currentDatabase() resolves to it, then USE the default test database
back before dropping it. Output is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
return false;
return c.type == AlterCommand::ADD_COLUMN
|| c.type == AlterCommand::DROP_COLUMN
|| c.type == AlterCommand::MODIFY_COLUMN

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.

MODIFY_COLUMN also covers metadata-only column changes such as MODIFY COLUMN x DEFAULT ..., CODEC, or column TTL. Those do not change the names or types produced by a dependent materialized view, but this gate still re-runs the view's SELECT before and after the ALTER.

That reintroduces the same class of side effect fixed for table-level MODIFY TTL: an unrelated column metadata ALTER can execute scalar subqueries/table functions from the MV analysis path, making the ALTER slow or externally observable even though the MV schema cannot change. For example, the 02697_alter_dependencies pattern with a column TTL alter would still execute the sleepEachRow/numbers analysis path here.

Please gate this on an actual schema-output change, e.g. compare the prepared old/new column names and types, or restrict MODIFY_COLUMN to commands whose data type really changes.

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.20% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 61/71 (85.92%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@al13n321

Copy link
Copy Markdown
Contributor

I think we should close this and not implement this feature at all: #106919 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, closing.

I checked the three points against master before conceding, and they hold:

  • columns_inferred_from_select_query (InterpreterCreateQuery.cpp) never leaves the CREATE interpreter, and explicit column lists with TO are accepted. So this PR had to guess whether a list was inferred by re-inferring and comparing, which silently rewrites any explicit list that happens to match the SELECT output.
  • Not refreshable-specific: the inference is not gated on refresh_strategy, and a plain non-refreshable TO-target MV goes stale the same way.
  • The Replicated part already went wrong here, so "presumed incorrect" is not hypothetical: the post-ALTER refresh issued a second persisted alterTable inside the ALTER's already-committed metadata transaction and aborted the server ("Cannot add ZooKeeper operation because query is executed"). I fell back to an in-memory-only refresh, which leaves the stored CREATE stale after a restart or on a new replica, so the original bug comes back.

I am not proposing a narrower version. Leaving #106919 open for you or @ PedroTadim to close or relabel as intended behaviour.

@groeneai groeneai closed this Aug 20, 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 groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants