Repository navigation
Fix assertion failure in view dependencies on DROP+CREATE MV - #98779
Conversation
…ew dependencies The BuzzHouse fuzzer found an assertion failure where `view_dependencies.getDependents(table_id).size()` could be greater than 1, violating the `assert(tables_from.size() == 1)` check. Root cause: when a materialized view was dropped via `InterpreterDropQuery`, `removeDependencies` was called with `is_mv=false` (the default), so the view dependency edge (source_table → MV) was never cleaned up. When a new MV with the same name was later created, it accumulated stale + new view dependencies, causing the assertion to fire on subsequent ALTER. Fixes: 1. Always clean up view dependencies in `removeDependencies`, removing the `is_mv` parameter entirely. This prevents stale edges from persisting after DROP TABLE/VIEW. 2. Handle multiple dependents gracefully in `updateDependencies` and `removeDependencies` by iterating all entries instead of asserting there is exactly one. 3. Always add the new view dependency in `updateDependencies`, even when there was no previous one to replace. 4. Fix early return bug in `addDependencies` (first overload) that skipped adding view dependencies when referential and loading dependencies were both empty. https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8f8e0d3934ac11a8887020d917ca88aa0727f3ea&name_0=MasterCI&name_1=BuzzHouse%20%28amd_debug%29 Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Workflow [PR], commit [a1b4cde] Summary: ✅ AI ReviewSummaryThis PR fixes ClickHouse Rules
Final Verdict
|
The previous commit removed the `is_mv` parameter and made view dependency cleanup unconditional in `removeDependencies`. This caused test `03290_alter_mv_dependency_check` to fail because during DROP, the UUID-based node lookup in the view dependency graph could find a wrong node after EXCHANGE (stale UUID from pre-exchange edges), leading to removal of unrelated edges. On master, DROP passes `is_mv=false`, skipping view dep cleanup in `removeDependencies` and relying on `StorageMaterializedView::shutdown` to correctly remove the edge. This commit restores that behavior while keeping the other fixes: replacing `assert` + single-element access with for loops, fixing the `addDependencies` early return bug, and moving `addDependency` outside the "if not empty" block in `updateDependencies`. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…se/ClickHouse into fix-view-dependencies-assertion
Fgrtue
left a comment
There was a problem hiding this comment.
All in all the fix does the job -- the crash does not happen. However, the root cause of the error is slightly different from what is asserted in the description of this PR. According to my investigation, it hides in the updateDependencies implementation, which, along with BACKUP/RESTORE functionality makes us having several edges in the dependency graph.
Fixes in updateDatabaseName and removeDependencies are good continuation of the fix, which cannot hurt.
Fix in addDependencies(...) is valid, but seems unrelated to the roots of the problem.
There was a problem hiding this comment.
The current test did not reproduce the error for me.
Instead, I tried the following:
CREATE DATABASE d0 ENGINE = Memory;
CREATE TABLE d0.src1 (c0 Int) ENGINE = Memory;
CREATE TABLE d0.src2 (c0 Int) ENGINE = Memory;
CREATE TABLE d0.target (c0 Int) ENGINE = Memory;
CREATE MATERIALIZED VIEW d0.mv TO d0.target AS SELECT c0 FROM d0.src1;
BACKUP VIEW d0.mv TO Memory('b.tgz') SYNC; -- BACKUP/RESTORE path would allow us to have two edges
ALTER TABLE d0.mv MODIFY QUERY SELECT c0 FROM d0.src2; -- cleanly replaces: src1→mv becomes src2→mv, allows us to add src1→mv via `addDependencies(...)`
ALTER TABLE d0.mv MODIFY QUERY SELECT 1 c0; -- leaks edge src2→mv due to empty new_view_dependencies, which is checked in `updateDependencies(...)`
TRUNCATE DATABASE d0; -- we drop the mv, but keep the stale edge src2→mv, so that we can restore it after
RESTORE VIEW d0.mv FROM Memory('b.tgz') SYNC; -- adds src1→mv via addDependencies, now {src2, src1}
ALTER TABLE d0.mv MODIFY COMMENT ''; -- triggers updateDependencies, assert(tables_from.size() == 1) failsAnd it caused the crash as in here #98706
There was a problem hiding this comment.
Thanks for the explicit reproducer. The test was rewritten in commit b2933c82 to observe the bug directly via system.tables.dependencies_table: after ALTER TABLE mv MODIFY QUERY SELECT 1 c0, src2 should have an empty dependencies_table, but with the bug it retains a stale ['mv'] entry. The previous version relied on assert(tables_from.size() == 1) firing, which is a no-op in release builds. The trailing BACKUP/RESTORE/ALTER ... MODIFY COMMENT flow following your reproducer is kept to also exercise the assertion path in debug builds.
| @@ -1724,14 +1718,9 @@ void DatabaseCatalog::updateDependencies( | |||
| { | |||
| assert(new_view_dependencies.size() == 1); | |||
| auto tables_from = view_dependencies.getDependents(table_id); | |||
| if (!tables_from.empty()) | |||
| { | |||
| assert(tables_from.size() == 1); | |||
| const auto & the_table_from = *tables_from.begin(); | |||
|
|
|||
| for (const auto & the_table_from : tables_from) | |||
| view_dependencies.removeDependency(the_table_from, table_id, /* remove_isolated_tables= */ true); | |||
There was a problem hiding this comment.
As far as I found during my investigation, the primary issue is due to the fact that we removeDependency only when the new_view_dependencies is non empty. This causes such a mutation ALTER TABLE d0.mv MODIFY QUERY SELECT 1 c0; to leak a stale edge.
However, for other dependencies (referential_dependencies and loading_dependencies) we first remove all dependencies, and then add new ones.
The current fix eliminates the crash, but the dependency is still left in the view_dependencies. This is a minor issue, however, fully correct fix would involve pulling the loop with removeDependency for view_dependencies out of the if (!new_view_dependencies.empty()). I should note, that I could not find where it would cause any seen error -- the protections in other part of the code, such as InsertDependenciesBuilder.cpp::1108 prevented the MV from showing the wrong output while inserting into the dependency.
However, since we are clearing all the asserts, the graph inconsistency is now silently accepted, and if some other code path relies on the previous existent invariant, that could lead to a wrong result.
There was a problem hiding this comment.
Right — this was addressed in the current code: the removeDependency loop has been pulled out of if (!new_view_dependencies.empty()) in updateDependencies (lines 1790–1792 of DatabaseCatalog.cpp), so stale source→view edges are now unconditionally cleared regardless of whether the new MV query references any source table, matching the unconditional removal pattern already used for referential_dependencies and loading_dependencies. The addDependency for the new source remains gated on !new_view_dependencies.empty().
…Dependencies` The root cause of the assertion failure was that `view_dependencies` removal was only performed inside `if (!new_view_dependencies.empty())`, so queries like `ALTER TABLE mv MODIFY QUERY SELECT 1 c0` (with no view dependencies) would leak stale edges. This differs from the pattern used for `referential_dependencies` and `loading_dependencies`, where removal is always unconditional. Now the removal of old view dependencies happens unconditionally (matching the other dependency types), and only the addition is conditional on non-empty `new_view_dependencies`. Also replaced the test with a proper reproduction using BACKUP/RESTORE as suggested by the reviewer, which actually triggers the original assertion failure. Co-Authored-By: Claude Opus 4.6 <[email protected]>
The root cause of the assertion failure was that `view_dependencies` removal was gated by `if (!new_view_dependencies.empty())` in `updateDependencies`. This meant that `ALTER TABLE mv MODIFY QUERY SELECT 1 c0` (producing no view dependencies) would leak stale edges. Combined with BACKUP/RESTORE, this accumulated multiple dependents, violating `assert(tables_from.size() == 1)`. Fix: make view dependency removal unconditional, matching the pattern already used for `referential_dependencies` and `loading_dependencies`. Replace the test with a proper reproduction case from the reviewer that exercises the BACKUP/RESTORE + MODIFY QUERY path. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Take our version: unconditional view dependency removal without extra braces block, and the reviewer-suggested test case. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…derr warnings `TRUNCATE DATABASE d0` removed all tables including `d0.src1` and `d0.target`, so RESTORE produced warnings about missing dependencies. Use `DROP TABLE d0.mv` instead so the dependent tables still exist during restore. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… incorrectly deleted files - Convert test to .sh with unique database and backup names to avoid collisions in the flaky check - Use the reviewer's improved reproduction that uses `TRUNCATE DATABASE` to better demonstrate the stale edge leak - Restore `03843_truncate_database_parallel_cancel` test and `InterpreterDropQuery.cpp` pre-merge-blocker code that were incorrectly removed during a merge conflict resolution Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The test uses BACKUP/RESTORE with Memory engine which is not supported in the fast test environment. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
The flaky check failure is fixed in #102148, let's update the branch. |
…gression test - `04027_mv_view_dependencies_drop_recreate.sh`: pass `--send_logs_level=error` to suppress the expected `BackupMetadataFinder` warnings from the `RESTORE VIEW` step (the view depends on tables that are not in the backup and were truncated). - `04104_mv_view_dependencies_rename.sh`: new regression test for the `addDependencies` early-return bug that silently dropped view dependencies during `RENAME TABLE` and `EXCHANGE TABLES` when referential and loading dependencies were empty; verifies that inserts into the source table still reach the renamed/exchanged materialized view.
`Memory` database does not support `renameTable`, so the test has to use a database engine that supports it (e.g. `Atomic`).
…endencies_drop_recreate` The test's `RESTORE VIEW` runs against a truncated database, so `BackupMetadataFinder` emits two `<Warning>` messages about the view's referenced tables not being in the backup. Even with `--send_logs_level=error`, these two warnings still leak to the client's stderr, and the CI harness fails any test that produces anything on stderr. Capture stderr to a temp file, filter out the expected warning lines, and re-emit the rest so unexpected diagnostics remain visible. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98779&sha=818752b99a35925ef10d6e5b76765119290e6448&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 PR: #98779 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Fgrtue
left a comment
There was a problem hiding this comment.
Everything looks good in my opinion. Also, the test are targeting the problem precisely, which is nice
`InterpreterRenameQuery::executeToTables` cross-swaps the harvested `from_dependent_views` and `to_dependent_views` after the physical rename, which is correct for `EXCHANGE TABLES a, b` (both tables persist, edges follow data). `doCreateOrReplaceTable` routes both `CREATE OR REPLACE TABLE` and `REPLACE TABLE` through the same rename interpreter, but the displaced table is dropped immediately afterwards — so the cross-swap pins the source-view edges to the soon-to-be-dropped table and the new occupant of the name ends up with `system.tables.dependencies_table` empty. `InsertDependenciesBuilder` then visits no MVs on the next insert and rows are silently lost. Tag the synthetic rename built by `doCreateOrReplaceTable` with a new `ASTRenameQuery::is_create_or_replace` flag and, when set, restore each harvested dependent-view list onto the table id it came from instead of swapping them. `EXCHANGE TABLES a, b` keeps its existing semantics. Regression introduced in ClickHouse#98779
`InterpreterRenameQuery::executeToTables` cross-swaps the harvested `from_dependent_views` and `to_dependent_views` after the physical rename, which is correct for `EXCHANGE TABLES a, b` (both tables persist, edges follow data). `doCreateOrReplaceTable` routes both `CREATE OR REPLACE TABLE` and `REPLACE TABLE` through the same rename interpreter, but the displaced table is dropped immediately afterwards — so the cross-swap pins the source-view edges to the soon-to-be-dropped table and the new occupant of the name ends up with `system.tables.dependencies_table` empty. `InsertDependenciesBuilder` then visits no MVs on the next insert and rows are silently lost. Tag the synthetic rename built by `doCreateOrReplaceTable` with a new `ASTRenameQuery::is_create_or_replace` flag and, when set, restore each harvested dependent-view list onto the table id it came from instead of swapping them. `EXCHANGE TABLES a, b` keeps its existing semantics. Regression introduced in ClickHouse#98779
The cross-swap of source-view dependency edges on `EXCHANGE TABLES` introduced by #98779 (commit `6133fbc6416`) is undone by the fix for #105021. The post-`EXCHANGE` sections of this test now produce the option-C output (edges follow the name) that matches the reference from before `6133fbc6416`. The `RENAME TABLE` sections keep #98779's behavior intact. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds `04240_exchange_tables_drops_mv_source_dependencies`. After `EXCHANGE TABLES a, b` where a materialized view reads from `a`, inserts into both `a` and `b` silently stop feeding the `MV` target table. Regression introduced by ClickHouse#98779 (correct on `v26.4.2.10`, broken on master). The reference pins the current buggy behavior: both post-exchange `SELECT count() FROM dst` assertions stay at 1. When the bug is fixed, the reference must be updated. Related: ClickHouse#105021 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`EXCHANGE TABLES a, b` (and the synthetic exchange used by `CREATE OR REPLACE TABLE` / `REPLACE TABLE`) cross-swapped the source-side `view_dependencies` edges along with the data. The `MV`'s stored `select_table_id` is not rewritten by the rename, so cross-swapping orphaned the `MV`: * `INSERT INTO a` after exchange found no dependents — the edge had been moved to `b`. * `INSERT INTO b` was rejected by `InsertDependenciesBuilder::observePath` because the `MV`'s recorded source name `a` no longer matched the parent `b`. Both inserts silently dropped rows. Restore the pre-ClickHouse#98779 semantics for `EXCHANGE`: keep source-view edges keyed by the original name. The `MV` continues to read from whatever now lives at the name it was created against. Plain `RENAME TABLE` keeps the post-ClickHouse#98779 re-keying behavior used by `01155_rename_move_materialized_view`. This also subsumes the special case from ClickHouse#104907 — the synthetic `CREATE OR REPLACE` exchange routes through the same `exchange_tables=true` branch. Tests: * `04240_exchange_tables_drops_mv_source_dependencies` — regression test for ClickHouse#105021. Now passes; `MV` continues to feed `dst` after `EXCHANGE TABLES`. Reference updated to the fixed behavior. * `04235_create_or_replace_source_table_view_dependencies` — cherry from ClickHouse#104907 (originally authored by @serprex). Passes with the unified fix. * `04241_rename_table_mv_source_dependencies` — pins a pre-existing latent bug in plain same-database `RENAME TABLE` (silent data loss, alive-but-orphaned `MV`). Not a ClickHouse#98779 regression; not fixed by this PR. Root cause shared with ClickHouse#76303; out of scope. The chosen behavior here ("option C": edges follow the name) is a regression repair — it matches v26.4. A future redesign to "option A" (identity-bound, atomic `MV.as_select` rewrite, like PostgreSQL) is tracked separately. Closes ClickHouse#105021 Co-Authored-By: Philip Dubé <[email protected]> Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The test was occasionally returning two rows from the per-iteration SELECT against `system.query_log` instead of one, observed as a spurious extra `1` in the diff before the expected `7` for `max_threads = 7` iterations across multiple unrelated PRs (ClickHouse#101143, ClickHouse#105406, ClickHouse#102308, ClickHouse#100752, ClickHouse#104473, ClickHouse#98779, ClickHouse#97302) and on master. The original filter accepted any `type != 'QueryStart'` row matching the iteration's `query_id`. Under randomized CI settings a second `query_log` entry can match the same `query_id` (subquery, distributed sub-fragment, or non-`Insert` follow-up), giving the test two rows. Tighten the filter to require the successful initial INSERT only: `type = 'QueryFinish' AND is_initial_query = 1 AND query_kind = 'Insert'`. This matches the well-known sibling test `02871_peak_threads_usage`, which already filters on `type = 'QueryFinish'`. Verified locally that the new filter correctly suppresses a duplicate log row sharing the same `query_id` while still returning exactly one row for the real INSERT. CI report (one of the recent failures): https://s3.amazonaws.com/clickhouse-test-reports/101143/ Co-Authored-By: Claude Opus 4.8 <[email protected]>
Adds `04240_exchange_tables_drops_mv_source_dependencies`. After `EXCHANGE TABLES a, b` where a materialized view reads from `a`, inserts into both `a` and `b` silently stop feeding the `MV` target table. Regression introduced by ClickHouse#98779 (correct on `v26.4.2.10`, broken on master). The reference pins the current buggy behavior: both post-exchange `SELECT count() FROM dst` assertions stay at 1. When the bug is fixed, the reference must be updated. Related: ClickHouse#105021 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When the definition of a system log changes, `SystemLog::prepareTable` renames the table to `<name>_N` and creates a new one under the old name. Since ClickHouse#98779 a plain `RENAME TABLE` moves the source-side view-dependency edges to the new name, but a materialized view's query still reads the log by name (`select_table_id` is name-only and `InsertDependenciesBuilder` rejects any other source), so the new table had no dependent views and the view silently stopped receiving rows until the next restart rebuilt the graph by name. Add an internal `InterpreterRenameQuery::setKeepSourceViewDependencies` that leaves those edges on the old name, as `EXCHANGE TABLES` already does (ClickHouse#105029), and set it only for the system log rotation. User `RENAME TABLE` keeps re-keying the edges. Closes ClickHouse#124177 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes #98706
Summary
tables_from.size() == 1inDatabaseCatalog::updateDependenciestriggered by BuzzHouse fuzzerupdateDependencies, the removal of oldview_dependenciesedges was insideif (!new_view_dependencies.empty()), so queries likeALTER TABLE mv MODIFY QUERY SELECT 1 c0(with no view dependencies) would leak stale edges; combined with BACKUP/RESTORE this accumulated multiple dependents, violating the assertionupdateDependencies, matching the pattern already used forreferential_dependenciesandloading_dependencies(unconditional removal, conditional addition)assert(tables_from.size() == 1)assertions that assumed a single dependent; iterate over all dependents instead, handling stale edges gracefullyaddDependencies(first overload) that silently dropped view dependencies when referential and loading dependencies were both emptyCI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8f8e0d3934ac11a8887020d917ca88aa0727f3ea&name_0=MasterCI&name_1=BuzzHouse%20%28amd_debug%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix assertion failure in
DatabaseCatalog::updateDependencieswhen dropping and recreating a materialized view with the same name; also fix view dependencies being silently lost duringRENAME TABLEorEXCHANGE TABLESwhen referential dependencies were empty.🤖 Generated with Claude Code
Note
Medium Risk
Touches
DatabaseCatalogdependency-graph maintenance used by DDL operations (ALTER/RENAME/EXCHANGE), so mistakes could impact catalog consistency, but the change is localized and covered by a regression test.Overview
Fixes view-dependency bookkeeping for materialized views to avoid accumulating stale edges:
updateDependenciesnow always removes existingview_dependenciesedges before optionally adding the new one, and code paths that previously assumed a single dependent (viaassert(tables_from.size() == 1)) now iterate over all dependents.Also fixes an early-return bug in
DatabaseCatalog::addDependenciesthat could silently skip adding view dependencies when referential/loading deps were empty (affectingRENAME TABLE/EXCHANGE TABLESflows), and adds a stateless regression test covering DROP/TRUNCATE + BACKUP/RESTORE + MV query modification that previously hit the assertion.Written by Cursor Bugbot for commit cb712fb. This will update automatically on new commits. Configure here.
Version info
26.5.1.462