Repository navigation
Conversation
…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]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-7:20260611-023300 |
|
cc @CheSema @al13n321 — could you review this? It refreshes the inferred column metadata of a |
|
Workflow [PR], commit [2f79c81] Summary: ❌
|
|
|
||
| auto table_id = getStorageID(); | ||
| DatabaseCatalog::instance().getDatabase(table_id.database_name) | ||
| ->alterTable(query_context, table_id, new_metadata, /*validate_new_create_query=*/true); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
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.
|
Thanks for the review, all four points are real (I reproduced #3 and #4 locally). #2 (DEFINER context), #1 (alter lock), the 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
Two ways to persist it:
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 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()) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 61/71 (85.92%) | Lost baseline coverage: none · Uncovered code |
|
I think we should close this and not implement this feature at all: #106919 (comment) |
|
Agreed, closing. I checked the three points against master before conceding, and they hold:
I am not proposing a narrower version. Leaving #106919 open for you or @ PedroTadim to close or relabel as intended behaviour. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
DESCRIBEandSHOW CREATE TABLEreporting stale column types for a materialized view created withTO targetafter the source or target table columns were changed withALTER TABLE ... MODIFY COLUMN. Previously the view kept the types inferred at creation time, which also madeSELECTfrom the view fail (for example withUNKNOWN_ELEMENT_OF_ENUM) when the new types were incompatible. The view's inferred columns are now refreshed on the upstreamALTER; explicit-column views keep their declared types.Description
After an
ALTERthat changes a table's columns, the column metadata of dependentTO-target materialized views is refreshed when their stored columns are still in sync with the view'sSELECToutput (recomputed against the pre-ALTERschema). The refresh re-runs the sameSELECT-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 theSELECToutput (e.g.SELECT 1 AS v2over a wider target column) are left untouched. Existing tests02931,01069,01182keep their current behavior; new test:04327_mv_to_target_columns_refresh_on_alter.