Repository navigation
Validate the database engine of a non-APPEND refreshable materialized view on ATTACH and RESTORE - #111928
Conversation
…ESTORE A non-APPEND refreshable materialized view is only supported in Atomic and Replicated databases. CREATE enforced this in validateMaterializedViewColumnsAndEngine, but the call is gated on mode <= CREATE, so a full-definition ATTACH (mode ATTACH) and a RESTORE that remaps the view into another database (SECONDARY_CREATE with is_restore_from_backup) bypassed the check. In a Memory database the view then got a Nil StorageID UUID, and its refresh (CREATE OR REPLACE of the temp inner table into a Replicated-db target) wrote the Nil into DDLLogEntry.parent_table_uuid, so checkParentTableExists(Nil) -> DatabaseCatalog::tryGetByUUID(Nil) tripped chassert(uuid != Nil && ...) (abort in debug/sanitizer; in release the refresh instead failed permanently with TABLE_IS_DROPPED "Parent table doesn't exist"). Hoist the engine check out of validateMaterializedViewColumnsAndEngine into createTable, gated on is_fresh_definition = mode <= CREATE || (mode == ATTACH && !attach_short_syntax) || is_restore_from_backup, mirroring the existing is_fresh_definition predicate in registerStorageMergeTree.cpp. Stored definitions (short ATTACH, ATTACH DATABASE, restart) and plain Replicated-DDL replay stay exempt; fresh full-definition ATTACH and RESTORE-with-remap are validated like CREATE. Also add a fail-close Nil guard in checkParentTableExists (return false, mirroring the existing guard in getRMVCoordinationInfo) so metadata written by older binaries loads and its refresh fails cleanly instead of aborting. Found by BuzzHouse (arm_asan_ubsan on PR ClickHouse#111370, amd_msan on PR ClickHouse#109454; both unrelated to this code path). Co-Authored-By: Claude Opus 4.8 <[email protected]>
The test proved that a fresh full-definition ATTACH and a RESTORE-with-remap are rejected, but neither of the compatibility promises the fix makes was asserted, so removing either guard left the whole suite green. A cross-engine RENAME reaches the pre-fix state without going through InterpreterCreateQuery: DatabaseOnDisk::renameTable swaps the UUID away when moving from Atomic to Ordinary and installs the definition with the target database's own createTable. That yields a stored, Nil-UUID, non-APPEND refreshable view on a fixed binary, so the test can now assert that such a definition still loads via short ATTACH and that its refresh is refused with TABLE_IS_DROPPED while the server stays up. The Nil UUID itself is asserted too, because the coverage is meaningless if the RENAME ever stops clearing it. The view is created with EMPTY so the only refresh in the test is the explicit SYSTEM REFRESH VIEW after the RENAME, and its target is a plain MergeTree table inside the Replicated database, which is what routes the refresh's CREATE OR REPLACE through the Replicated DDL log and into the parent-table lookup. Verified by patching out each guard in turn: without the attach_short_syntax exemption the stored definition no longer attaches, and without the Nil guard the server aborts on the refresh with the original assertion. Also drop the tables the test leaves behind.
Internal second-model review - adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 findings across 2 rounds), plus 4 findings from my own cold review of the same diff.
Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260725-232000 |
|
cc @tuanpach @al13n321 - could you review this? A non-APPEND refreshable materialized view was only engine-validated on |
|
Workflow [PR], commit [c1508c6] Summary: ✅
AI ReviewSummaryThis PR moves the non- Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit c1508c6.
Changed lines: Changed C/C++ lines covered: 22/24 (91.67%) · Uncovered code |
The fresh-definition gate treated every RESTORE as fresh input, because DatabaseWithOwnTablesBase::createTableRestoredFromBackup unconditionally sets is_restore_from_backup before running the interpreter. A restore therefore could not be told apart from a remap, so a backup of a non-APPEND refreshable materialized view that already lived in a Memory or Ordinary database stopped being restorable into the very database it was taken from: the restore threw INCORRECT_QUERY even though the same metadata still loads on restart and on a short ATTACH, and its refresh already fails closed through the Nil guard in checkParentTableExists. Such a definition carries no UUID in the backup. RESTORE overwrites the create query's uuid with a freshly generated one before the interpreter runs, but it never touches has_uuid, which still reflects what the backup stored. A restore is therefore only a remap when has_uuid is set: the view lived in a database that holds UUIDs, so landing it in one that does not is the case that must be rejected. A UUID-less backup is a definition that already lived without a UUID and stays restorable. The regression test gains a same-database restore of the UUID-less definition it already builds via a cross-engine RENAME. Removing the has_uuid condition loses that line, and the two pre-existing kill-tests still bite: dropping !create.attach_short_syntax loses three lines, and dropping the Nil guard aborts the server with the original assertion. Co-Authored-By: Claude Fable 5 <[email protected]>
The restore renaming map is applied before the interpreter runs and nothing records that a rename happened, so a UUID-less definition restored under another name is indistinguishable from one restored in place. Both are accepted, which is the intent: there is no UUID to lose either way, and the resulting view is harmless because the Nil guard in checkParentTableExists refuses its refresh instead of aborting. Say so explicitly rather than leaving it implied. The predicate is renamed to is_uuid_losing_restore, which is what it actually tests, and the test now restores the UUID-less definition under a second name and asserts both that the restore succeeds and that the copy's refresh is refused cleanly with the server still up. Co-Authored-By: Claude Fable 5 <[email protected]>
The rationale it spelled out belongs in the commit messages and the PR description, not next to the predicate. Keep only what a reader needs at this line: which definitions are validated, and why has_uuid is the right signal. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Confirmed and fixed in 467fc2c.
The predicate now keys on Two rows were added to Removing the |
| /// were already validated, and rejecting them would make existing metadata unloadable. | ||
| /// `has_uuid` is the backup's own metadata, not the UUID this restore generated, so it tells a | ||
| /// view that had a UUID (about to lose it here) from one that never had one. | ||
| const bool is_uuid_losing_restore = is_restore_from_backup && create.has_uuid; |
There was a problem hiding this comment.
create.has_uuid is too weak a proxy for "this restore is just replaying old metadata". A backup taken after moving a valid non-APPEND RMV from Atomic to Ordinary has has_uuid == false, so RESTORE ... AS rep_db.v now skips this gate. But in a Replicated destination assertOrSetUUID regenerates a real UUID (InterpreterCreateQuery.cpp:1572), so this is no longer replaying the old Nil-UUID definition: StorageMaterializedView switches to coordinated refresh, while its CREATE-time guard against a non-replicated target only runs for mode < SECONDARY_CREATE (StorageMaterializedView.cpp:242-246). That lets restore create the exact combination CREATE refuses because each refresh can replace the target on other replicas with empty tables. The compatibility carve-out needs to stay limited to replaying UUID-less metadata into non-UUID databases, or restore needs to rerun the target-engine validation for Replicated destinations.
There was a problem hiding this comment.
The mechanism is real, but it is pre-existing master behavior that this PR cannot influence, so I am not changing the predicate. Checked on the PR-head binary (server buildId() verified against readelf).
The gate only throws when the destination engine is neither Atomic nor Replicated:
if (database && database->getEngineName() != "Atomic" && database->getEngineName() != "Replicated")
throw Exception(ErrorCodes::INCORRECT_QUERY, ...);is_uuid_losing_restore decides whether that block is entered, not what it does. For a Replicated destination the condition is false by construction, so has_uuid cannot change the outcome. Restoring into a Replicated database, same db, both directions of the flag:
| Backup | UUID clause in backup metadata |
has_uuid |
gate entered | RESTORE ... AS rep_db.v |
|---|---|---|---|---|
| cross-engine RENAME (Nil UUID) | absent | false | no | RESTORED |
| plain Atomic view | UUID '3bc56a82-...' |
true | yes | RESTORED |
The second row enters the gate and still succeeds, so has_uuid is not the discriminator the comment assumes. Both restored views get a real UUID in the destination, which matches assertOrSetUUID and is unchanged by this PR.
The two mechanics cited are untouched here:
StorageMaterializedView.cpp:218mode < LoadingStrictnessLevel::SECONDARY_CREATE && !fixed_uuidis byte-identical at the base commit, and this PR does not modifyStorageMaterializedView.cpp.mode = getLoadingStrictnessLevel(..., is_secondary_query || is_restore_from_backup)is also pre-existing, so RESTORE has always beenSECONDARY_CREATEand that target-engine guard has always been skipped on restore. At the base commit the engine check ran only undermode <= CREATE, so it never ran on a restore either.
Restore-into-Replicated therefore behaves exactly as it does on master. Plain CREATE still refuses the combination (Code: 36, "refreshable materialized view, no APPEND, replicated database, non-replicated table"), the server stays up, and no assertion fires.
The residual gap in master is genuine and I reproduced it, but constraining RESTORE for a pre-existing behavior is a backward-incompatible change that needs a maintainer decision and its own changelog entry, and it is a second concern in a single-root-cause PR. I am tracking it separately instead of folding it in here.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 24/26 (92.31%) · Uncovered code |
CI finish ledger - 467fc2cEvery failure below has an owner: a fixing PR (mine or external). Only
None is PR-caused: this PR touches Session id: cron:our-pr-ci-monitor:20260726-103000 |
Re-threads the fix onto master's current shape. `ASTRefreshStrategy::append` became the `RefreshMode` enum, so the non-APPEND test is now `!isAppend()`, i.e. `mode == RefreshMode::Replace`. That selects the same views the old `!append` did: APPEND split into APPEND and APPEND INCREMENTAL, and `isAppend()` reports both. Master has since added `isFreshTableDefinition(level, attach_short_syntax)` in Databases/LoadingStrictnessLevel.h, holding exactly the predicate this branch open-coded, with four call sites already using it. The hoisted check now calls it and keeps only the restore-specific term this fix adds, so the branch no longer carries a second copy of that definition. Both halves of the fix are still needed on master: `checkParentTableExists` still calls `tryGetByUUID` with an unchecked UUID, and the refreshable-view database-engine check still runs only under `mode <= CREATE`. Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units31 translation units recompiled, 239 s compile time in total, 31 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR changes only refreshable materialized view creation/attach/restore validation and a Nil-UUID guard in Replicated-DDL parent-table lookup — none of which runs during a ClickBench SELECT. The single flagged query (ClickBench Q28, -5.2%) already landed as not_sure because the two tests disagreed and the measurements were noisy, and it exercises no code this diff touches, so treat it as run-to-run variance rather than a PR effect. No real performance impact is expected from this change. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a logical error (server abort in debug and sanitizer builds) when a non-APPEND refreshable materialized view was created in a non-Atomic/Replicated database via a full-definition
ATTACH, or via aRESTOREof a view that had a UUID into such a database.CREATEalready rejected this combination;ATTACHandRESTOREbypassed the check and produced a view with a Nil UUID whose refresh tripped aDatabaseCatalog::tryGetByUUIDassertion in the Replicated-DDL parent-table lookup. Backups of views that never had a UUID stay restorable, and their refresh now fails cleanly instead of aborting.Description
A non-APPEND refreshable materialized view is only supported in
AtomicandReplicateddatabases: its refresh swaps the inner table through an atomicEXCHANGE, and it needs a real UUID for parent-table tracking when the target lives in aReplicateddatabase.CREATEenforces this invalidateMaterializedViewColumnsAndEngine, but that call is gated onmode <= LoadingStrictnessLevel::CREATE, so two fresh-definition paths bypassed it:ATTACH MATERIALIZED VIEW ... REFRESH ... TO ...(runs atLoadingStrictnessLevel::ATTACH), andRESTORE ... AS <other_db>.<view>that lands the view in a non-Atomic/Replicated database (runs atSECONDARY_CREATEwithis_restore_from_backup).In a
Memorydatabase the view gets a Nil StorageID UUID. When its refresh fires and issuesCREATE OR REPLACEfor the temp inner table into aReplicated-database target, the Nil UUID is written intoDDLLogEntry.parent_table_uuid, andDatabaseReplicatedDDLWorker::checkParentTableExists(Nil)callsDatabaseCatalog::tryGetByUUID(Nil), hittingchassert(uuid != UUIDHelpers::Nil && ...). In release builds the assertion is compiled out and the refresh instead fails permanently with a misleadingTABLE_IS_DROPPED "Parent table doesn't exist".Fix:
validateMaterializedViewColumnsAndEngineintocreateTable, gated onis_fresh_definition = mode <= CREATE || (mode == ATTACH && !attach_short_syntax) || (is_restore_from_backup && create.has_uuid). This mirrors the existingis_fresh_definitionpredicate inregisterStorageMergeTree.cpp: stored definitions (shortATTACH,ATTACH DATABASE, restart) were validated when introduced and keep loading; plain Replicated-DDL replay stays exempt (its database isReplicatedanyway); fresh full-definitionATTACHis user input and is validated likeCREATE. The exception text is unchanged.checkParentTableExists: a Nil UUID never identifies a table, so return false (mirrors the existing Nil guard ingetRMVCoordinationInfoin the same file). This keeps metadata written by older binaries loadable and makes its refresh fail cleanly instead of aborting debug/sanitizer servers.A
RESTOREis only validated when the backed-up definition carried a UUID (create.has_uuid, which reflects the backup's own metadata:RESTOREoverwritesuuidwith a freshly generated one before the interpreter runs, but neverhas_uuid). A view that had a UUID lived in a database that holds UUIDs, so landing it in one that does not is the UUID-losing case that must be rejected. A backup of a view that never had a UUID (for example one moved to anOrdinarydatabase by an earlierRENAME) is a definition that already lived without one: rejecting it would make such backups unrestorable on newer servers while the same metadata still loads on restart and on a shortATTACH, so it stays restorable under any name and the Nil guard keeps its refresh failing cleanly.Found by BuzzHouse:
Logical error: 'uuid != UUIDHelpers::Nil && getFirstLevelIdx(uuid) < uuid_map.size()', BuzzHouse (arm_asan_ubsan): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111370&sha=3c509b961097528327cfb981dbef8957a5f9237a&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29Both sighting PRs are unrelated to this code path (a datetime-function change and an unrelated change); the failure is a latent engine bug, not caused by either PR.
Workflow [PR]
Sync PR [sync-upstream/pr/111928]
Version info
26.10.1.707-master(included in26.10and later)