Repository navigation
Make BACKUP work for MaterializedPostgreSQL databases - #107433
Conversation
BACKUP of a `MaterializedPostgreSQL` database hung forever (and could not be killed) with repeated `Table ... were created or changed its definition during scanning`. Two problems: 1. `DatabaseMaterializedPostgreSQL::getCreateTableQueryImpl` generated a fresh random UUID on every call, so the table definition appeared to change on each pass of `BackupEntriesCollector`'s consistency check, which therefore never converged. Use the table's actual (stable) UUID instead. This also makes `SHOW CREATE TABLE` deterministic. 2. `StorageMaterializedPostgreSQL` did not back up any data (the default `IStorage::backupData` is a no-op), so even a completed backup would have been empty. Delegate `backupData`/`restoreDataFromBackup` to the nested `ReplacingMergeTree`, mirroring `StorageMaterializedView`. A backed-up table can now be restored as a standalone `ReplacingMergeTree`. Closes: #44252 Related: #49045 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [78227cf] Summary: ✅
AI ReviewSummaryThis PR fixes the original Findings❌ Blockers
Tests
Final Verdict |
The new `test_backup_database` integration test failed at RESTORE with:
Code: 608. DB::Exception: The table has a different definition:
CREATE TABLE restored_db.test_backup_tbl (...) ENGINE = ReplacingMergeTree(_version)
ORDER BY tuple(key) SETTINGS index_granularity = 8192
comparing to its definition in the backup:
CREATE TABLE restored_db.test_backup_tbl (...) ENGINE = ReplacingMergeTree(_version)
ORDER BY tuple(key)
(CANNOT_RESTORE_TABLE)
The create query stored in the backup is the synthetic nested-table query produced by
`DatabaseMaterializedPostgreSQL::getCreateTableQueryImpl`, which intentionally omits the
default `index_granularity` setting so that `SHOW CREATE TABLE` stays clean (asserted by
the existing `test_table_override`). When the table is restored as a standalone
`ReplacingMergeTree`, its definition is normalized and gains `SETTINGS index_granularity =
8192`, so `RestorerFromBackup::checkTable` rejects the otherwise-identical definition.
Since the test deliberately restores a `MaterializedPostgreSQL` table's data as a plain
`ReplacingMergeTree`, the definitions are expected to differ; pass
`allow_different_table_def = 1` to skip the check. Only the data has to match, which the
assertions verify.
CI report: #107433
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # tests/integration/test_postgresql_replica_database_engine/test_3.py
Per review feedback on `DatabaseMaterializedPostgreSQL::getCreateTableQueryImpl` (#107433 (comment)): fold the `table_uuid != Nil ? table_uuid : generateV4()` ternary into the preceding `if`. `table_uuid` now defaults to a freshly generated UUID and is overwritten with the table's stable UUID when it exists, so the assignment to the AST is unconditional. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses the AI review "Request changes" verdict on this PR (#107433): the new `StorageMaterializedPostgreSQL::restoreDataFromBackup` delegated to the nested `ReplacingMergeTree`, but a `MaterializedPostgreSQL` table starts replicating from the live PostgreSQL source the moment it is created (its constructor calls `replication_handler->startup`, and the table-engine creator ignores `StorageFactory::Arguments::is_restore_from_backup`). Restoring the backed-up parts on top of that freshly replicated data would mix the backup snapshot with the current remote state, or fail if PostgreSQL is unavailable, breaking the contract that restored data represents the backup. Following the fail-close principle, `restoreDataFromBackup` now throws `NOT_IMPLEMENTED` with a message directing the user to restore the data as a standalone `ReplacingMergeTree` instead. `backupData` is unchanged, so the supported path - `BACKUP DATABASE` of a `MaterializedPostgreSQL` database followed by `RESTORE TABLE ... AS ... SETTINGS allow_different_table_def = 1` (covered by `test_backup_database`) - still works and captures the data. Adds `test_backup_table_engine_restore_rejected`, which backs up a standalone `MaterializedPostgreSQL` table-engine table and asserts that an in-place `RESTORE` is rejected with a clear exception. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lacingMergeTree target The `restoreDataFromBackup` error message recommended `RESTORE TABLE ... AS <new_table> SETTINGS allow_different_table_def = 1`, but for a standalone `MaterializedPostgreSQL` table-engine backup this guidance is incomplete: if `<new_table>` does not already exist, the restore recreates it from the backup definition (again as `MaterializedPostgreSQL`) and hits the same `NOT_IMPLEMENTED` exception, because `allow_different_table_def` only skips the definition comparison against an already existing target. Direct the user to pre-create a compatible `ReplacingMergeTree` target (including the `_sign` and `_version` columns) and restore the data into it. #107433 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ackup `RESTORE DATABASE` of a `MaterializedPostgreSQL` backup recreated the database as `ENGINE = MaterializedPostgreSQL`, which starts replicating from the live PostgreSQL source (its `startupDatabaseAsync` schedules `tryStartSynchronization`) before `RestorerFromBackup` restores the backed-up table data. That mixes the backup snapshot with the current remote state. Refuse such a restore in `RestorerFromBackup::createDatabase` before the database is created, with `CANNOT_RESTORE_DATABASE`, directing the user to restore the data of individual tables into separately created `ReplacingMergeTree` tables (the data is still captured by `StorageMaterializedPostgreSQL::backupData`). This mirrors the existing in-place table-engine restore guard. Covered by extending the `test_backup_database` integration test to assert that `RESTORE DATABASE ... AS restored_mpg_db` is rejected. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`StorageMaterializedPostgreSQL::backupData` previously logged a warning and returned when `tryGetNested` returned null, so a `BACKUP` could silently succeed while capturing only the table metadata and none of the data (the parts live in the nested `ReplacingMergeTree`). A later restore into a `ReplacingMergeTree` target would then produce an empty or incomplete table even though the backup command reported success. Following the fail-close principle, throw `CANNOT_BACKUP_TABLE` instead, so a backup that cannot capture the data fails loudly rather than producing a misleading partial backup. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e table-engine restore path The `RESTORE DATABASE` rejection for a `MaterializedPostgreSQL` database told users to restore into an already-existing `ReplacingMergeTree`. But in a database backup each table's stored definition is already the synthetic nested `ReplacingMergeTree` (not the `MaterializedPostgreSQL` engine), so a table can be restored straight into a new, not-yet-existing target. The example in the message now reflects that; the pre-created-target wording remains only in `StorageMaterializedPostgreSQL::restoreDataFromBackup`, where the stored definition really is `MaterializedPostgreSQL`. Also extend the standalone table-engine test to exercise the supported data path: pre-create a `ReplacingMergeTree` with the nested table's structure (including `_sign` and `_version`) and `RESTORE TABLE ... AS` into it with `allow_different_table_def = 1`, asserting the row count and sum match. This proves `StorageMaterializedPostgreSQL::backupData` captures the data - the previous in-place-rejection test would have passed even if it did not. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # tests/integration/test_postgresql_replica_database_engine/test_3.py
The `MaterializedPostgreSQL` rejection in `RestorerFromBackup::createDatabase` ran after the `create_database = 'must-exist'` early return, so a `RESTORE DATABASE ... SETTINGS create_database = 'must-exist'` into an existing, live `MaterializedPostgreSQL` database bypassed the guard. It would then attach the backed-up nested `ReplacingMergeTree` parts into tables that are actively replicating from PostgreSQL, mixing the backup snapshot with the live remote state - the same failure the guard is meant to prevent. Move the check before the `kMustExist` early return so the whole `RESTORE` fails during the `CREATING_DATABASES` stage, before any table data is inserted. Add a null guard for the backed-up database definition (absent when restoring individual tables into an existing database) and a regression test asserting `RESTORE DATABASE ... SETTINGS create_database = 'must-exist'` into a live `MaterializedPostgreSQL` database is rejected. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A standalone `MaterializedPostgreSQL` table-engine restore was rejected only in `restoreDataFromBackup`, which runs after `RestorerFromBackup` has already created the table. Because the `StorageMaterializedPostgreSQL` constructor calls `replication_handler->startup`, a rejected `RESTORE TABLE` into a not-yet-existing target left a live table replicating from the live PostgreSQL source (the restore is not rolled back on a later failure), so the fail-close did not actually fail closed. Reject the restore in `registerStorageMaterializedPostgreSQL` when `args.is_restore_from_backup` is set, i.e. before the storage is constructed, so no table is created and no replication is started. `restoreDataFromBackup` keeps its `NOT_IMPLEMENTED` throw as the safety net for an in-place restore into an already-existing `MaterializedPostgreSQL` table. This mirrors the database-level rejection in `RestorerFromBackup::createDatabase`, which already fails before creation. The `test_backup_table_engine` integration test now asserts the rejected restore leaves no table behind (`EXISTS TABLE` is `0`). Addresses the AI Review on #107433 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
murphy-4o
left a comment
There was a problem hiding this comment.
The PR description appears to be a Claude-generated summary rather than a meaningful explanation of the actual changes:
Note for reviewers: I could not run BACKUP/RESTORE end-to-end locally (build/submodule constraints in my environment), so this relies on CI for the integration tests
Address review feedback from @murphy-4o on `RestorerFromBackup.cpp`: explain the backup/restore behavior in the documentation. `BACKUP DATABASE` of a `MaterializedPostgreSQL` database works (the data is captured via the nested `ReplacingMergeTree`), while restoring a `MaterializedPostgreSQL` database or table in place is not supported and fails closed. The new "Backup and restore" section documents this and shows how to restore the captured data into plain `ReplacingMergeTree` tables. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`test_backup_table_partitions` partitions the nested `ReplacingMergeTree` via a `TABLE OVERRIDE`, backs up a subset of partitions with `BACKUP TABLE ... PARTITIONS`, restores them into a standalone `ReplacingMergeTree`, and asserts only the selected partitions are present. This exercises the `supportsBackupPartition` delegation that previously rejected partition backups before reaching `backupData`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed
Regression test Note: the test uses the database-engine Built the changed object locally (compiles clean); the integration test relies on CI like the existing backup tests in this PR. CI status — the 3 reds are all pre-existing flakes unrelated to this change:
|
|
CI status on
I did not re-merge Otherwise the PR looks ready: AI Review is ✅ Approve on this commit, @murphy-4o approved, and there are no unresolved review threads. |
|
Follow-up on So all 4 reds are pre-existing master-wide flakes, each with an open tracking issue, and none touch this PR's code paths (
I re-ran the 4 failed jobs (all were attempt 1 on this commit). Did not re-merge The PR is otherwise ready: AI Review ✅ Approve on this commit, @murphy-4o approved, no unresolved review threads. |
|
CI status on
The PR touches only |
Resolve conflict in test_postgresql_replica_database_engine/test_3.py: both this PR (backup tests: test_backup_database, test_backup_table_engine, test_backup_table_partitions) and master's PR #107427 (test_table_schema_changed_while_server_down) added new test functions at the same location. Keep both sets. The three C++ files auto-merged cleanly; their changes occupy disjoint regions. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ynchronized table `BACKUP DATABASE` of a `MaterializedPostgreSQL` database could succeed while silently omitting a table whose nested `ReplacingMergeTree` was never created. The fail-closed guard added earlier in `StorageMaterializedPostgreSQL::backupData` only runs for the standalone table-engine path; the database backup path bypasses it: `BackupEntriesCollector` enumerates tables via `DatabaseWithOwnTablesBase::getTablesForBackup`, which iterates `DatabaseMaterializedPostgreSQL::getTablesIterator`. That iterator runs in the nested context, so it only sees the already-created nested `ReplacingMergeTree` tables and backs them up directly, never touching the `StorageMaterializedPostgreSQL` wrappers. A table that the database is configured to replicate but whose nested table has not been created yet (its initial snapshot from PostgreSQL is still in progress or failed - e.g. the PostgreSQL table has no primary key and no replica identity index, so `createNestedIfNeeded` throws and, in the database engine, that failure is logged and swallowed) is therefore left out of the backup without any error. Override `getTablesForBackup` in `DatabaseMaterializedPostgreSQL` to first walk the configured `materialized_tables` and refuse the whole backup with `CANNOT_BACKUP_TABLE` when any requested table still has no nested table, mirroring the fail-closed check in `backupData`. The filter is honored so that `BACKUP TABLE` of a synchronized table is unaffected by an unrelated unsynchronized one. Addresses the AI Review "Request changes" verdict on #107433 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lose `test_backup_database_fails_closed_on_unsynchronized_table` creates a `MaterializedPostgreSQL` database over two PostgreSQL tables: a normal one and one with no primary key and no replica identity index. The latter deterministically fails to create its nested `ReplacingMergeTree` (its wrapper stays with no nested table) while the former synchronizes. The test asserts that `BACKUP DATABASE` now fails closed with a clear message instead of producing a backup that silently omits the unsynchronized table. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed Verified the finding is real. Fix ( Regression test ( The C++ change compiles clean ( |
…upPartition path The existing `test_backup_table_partitions` backs up a table of a `MaterializedPostgreSQL` *database*, whose `BACKUP TABLE` path enumerates the database through `getTablesIterator` (the nested context). So `BackupEntriesCollector` sees the inner `ReplacingMergeTree` and checks `supportsBackupPartition` on it, never on the `StorageMaterializedPostgreSQL` wrapper - the override added in this PR is not exercised, and a regression to the `IStorage` default would keep that test green. Add `test_backup_table_engine_partitions`, which backs up a standalone `MaterializedPostgreSQL` *table engine* table with `BACKUP TABLE ... PARTITIONS`. That path resolves the storage to the wrapper, so `BackupEntriesCollector` calls the wrapper's `supportsBackupPartition`; a regression to the `IStorage` default rejects the backup with "doesn't support partitions" and fails the test. The standalone engine does not propagate `PARTITION BY`, so the nested `ReplacingMergeTree` has a single partition; its id is read from `system.parts` (nested table `<wrapper_uuid>_nested`, per `getNestedTableName`) and backed up by id, then restored into a standalone `ReplacingMergeTree` to verify the data. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tion has not populated the tables `DatabaseMaterializedPostgreSQL::getTablesForBackup` rejected a database backup when a configured table's nested `ReplacingMergeTree` was missing, but skipped that guard entirely while `materialized_tables` was still empty. `startupDatabaseAsync` only schedules the background synchronization task and `waitDatabaseStarted` returns before `startSynchronization` populates the wrapper map, so right after `CREATE DATABASE` or a server restart - in particular for the whole time the initial `fetchRequiredTables` call to PostgreSQL is in flight - the map is empty and `DatabaseAtomic::getTablesForBackup` would silently produce an empty or partial database backup. Fail the whole backup closed when the map is empty: a database that finished starting up always has at least one table (`startSynchronization` refuses an empty tables list), so an empty map means synchronization has not populated it yet. Add the regression test `test_backup_database_fails_closed_before_synchronization`, which deterministically reproduces the empty-`materialized_tables` window with bad PostgreSQL credentials and asserts `BACKUP DATABASE` is refused. Addresses the AI Review finding on `src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| BackupEntriesCollector & backup_entries_collector, const String & data_path_in_backup, const std::optional<ASTs> & partitions) | ||
| { | ||
| /// The data lives in the nested ReplacingMergeTree table, delegate the backup to it. | ||
| auto nested = tryGetNested(); |
There was a problem hiding this comment.
backupData now treats the standalone table-engine path as safe as soon as the nested table exists, but that is earlier than "initial snapshot is fully loaded". On the ATTACH path, PostgreSQLReplicationHandler::loadFromSnapshot creates the nested ReplacingMergeTree first and only later streams the snapshot rows and calls StorageMaterializedPostgreSQL::set (PostgreSQLReplicationHandler.cpp:503-532). A BACKUP TABLE that lands in that window will therefore delegate to a half-populated nested table and can produce an incomplete backup that later restores without any indication the snapshot was partial.
Please fail closed until the standalone engine's initial synchronization has actually completed, not just until tryGetNested() starts returning non-null. A completion signal tied to replication-handler initialization (or another explicit "snapshot fully loaded" bit) would avoid backing up tables that are still mid-snapshot.
| /// `StorageMaterializedPostgreSQL::backupData`, which the database backup path bypasses because it backs up | ||
| /// the nested tables directly rather than the `StorageMaterializedPostgreSQL` wrappers. | ||
| { | ||
| std::lock_guard lock(tables_mutex); |
There was a problem hiding this comment.
This guard assumes tables_mutex makes materialized_tables stable while we inspect it, but the writers of that same map do not use tables_mutex: startSynchronization populates it under handler_mutex only (DatabaseMaterializedPostgreSQL.cpp:131-153), attachTable writes it without either mutex (DatabaseMaterializedPostgreSQL.cpp:416-420), and stopReplication clears it without tables_mutex (DatabaseMaterializedPostgreSQL.cpp:503-510). The startup window this method is meant to protect (BACKUP DATABASE immediately after CREATE DATABASE / restart) can therefore still race with concurrent std::map inserts or clears, so the new fail-closed check is not actually synchronized and can still observe UB or a partial wrapper set.
Please use one lock consistently for every access to materialized_tables (or reuse the existing writer-side lock here) before relying on this pre-scan as the safety boundary.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 72/90 (80.00%) · Uncovered code |
…om `04338_on_fly_mutation_read_overwritten_lc_source` The stateless test `04338_on_fly_mutation_read_overwritten_lc_source` (table `t_overwrite_before_consume`) chains the async mutations `UPDATE v = toString(id + 100)`, `UPDATE b = isNotNull(materialize(v))` and `MODIFY COLUMN v UInt64` over a column whose on-disk value is the unconvertible String `'x'`. This is an intentionally-broken mutation of exactly the class already documented in the `CANNOT_PARSE_TEXT` allowlist (issue ClickHouse#39174): a `MODIFY COLUMN ... UInt64` on un-parseable String data, just like the already-allowlisted `'Hello'`/`'a'`/`'b'` variants from `00834_kill_mutation` and `01414_mutations_and_errors_zookeeper`. After the upgrade restart the broken mutation is retried and logs `Cannot parse string 'x' as UInt64: syntax error at begin of string` (`CANNOT_PARSE_TEXT`) to `clickhouse-server.upgrade.log`, which fails the `Upgrade check` with `Error message in clickhouse-server.log (see upgrade_error_messages.txt)`. This is not a backward-incompatibility or a regression; it is the expected test-induced error. Add the narrow `'x'` message to the upgrade-check allowlist and document `04338` in the comment block. The failure is not caused by any product change - it surfaces on any pull request that runs the Upgrade check (observed on PR ClickHouse#108011 and the unrelated PR ClickHouse#107433). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The new `test_backup_database` integration test failed at RESTORE with:
Code: 608. DB::Exception: The table has a different definition:
CREATE TABLE restored_db.test_backup_tbl (...) ENGINE = ReplacingMergeTree(_version)
ORDER BY tuple(key) SETTINGS index_granularity = 8192
comparing to its definition in the backup:
CREATE TABLE restored_db.test_backup_tbl (...) ENGINE = ReplacingMergeTree(_version)
ORDER BY tuple(key)
(CANNOT_RESTORE_TABLE)
The create query stored in the backup is the synthetic nested-table query produced by
`DatabaseMaterializedPostgreSQL::getCreateTableQueryImpl`, which intentionally omits the
default `index_granularity` setting so that `SHOW CREATE TABLE` stays clean (asserted by
the existing `test_table_override`). When the table is restored as a standalone
`ReplacingMergeTree`, its definition is normalized and gains `SETTINGS index_granularity =
8192`, so `RestorerFromBackup::checkTable` rejects the otherwise-identical definition.
Since the test deliberately restores a `MaterializedPostgreSQL` table's data as a plain
`ReplacingMergeTree`, the definitions are expected to differ; pass
`allow_different_table_def = 1` to skip the check. Only the data has to match, which the
assertions verify.
CI report: ClickHouse#107433
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Per review feedback on `DatabaseMaterializedPostgreSQL::getCreateTableQueryImpl` (ClickHouse#107433 (comment)): fold the `table_uuid != Nil ? table_uuid : generateV4()` ternary into the preceding `if`. `table_uuid` now defaults to a freshly generated UUID and is overwritten with the table's stable UUID when it exists, so the assignment to the AST is unconditional. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses the AI review "Request changes" verdict on this PR (ClickHouse#107433): the new `StorageMaterializedPostgreSQL::restoreDataFromBackup` delegated to the nested `ReplacingMergeTree`, but a `MaterializedPostgreSQL` table starts replicating from the live PostgreSQL source the moment it is created (its constructor calls `replication_handler->startup`, and the table-engine creator ignores `StorageFactory::Arguments::is_restore_from_backup`). Restoring the backed-up parts on top of that freshly replicated data would mix the backup snapshot with the current remote state, or fail if PostgreSQL is unavailable, breaking the contract that restored data represents the backup. Following the fail-close principle, `restoreDataFromBackup` now throws `NOT_IMPLEMENTED` with a message directing the user to restore the data as a standalone `ReplacingMergeTree` instead. `backupData` is unchanged, so the supported path - `BACKUP DATABASE` of a `MaterializedPostgreSQL` database followed by `RESTORE TABLE ... AS ... SETTINGS allow_different_table_def = 1` (covered by `test_backup_database`) - still works and captures the data. Adds `test_backup_table_engine_restore_rejected`, which backs up a standalone `MaterializedPostgreSQL` table-engine table and asserts that an in-place `RESTORE` is rejected with a clear exception. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lacingMergeTree target The `restoreDataFromBackup` error message recommended `RESTORE TABLE ... AS <new_table> SETTINGS allow_different_table_def = 1`, but for a standalone `MaterializedPostgreSQL` table-engine backup this guidance is incomplete: if `<new_table>` does not already exist, the restore recreates it from the backup definition (again as `MaterializedPostgreSQL`) and hits the same `NOT_IMPLEMENTED` exception, because `allow_different_table_def` only skips the definition comparison against an already existing target. Direct the user to pre-create a compatible `ReplacingMergeTree` target (including the `_sign` and `_version` columns) and restore the data into it. ClickHouse#107433 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A standalone `MaterializedPostgreSQL` table-engine restore was rejected only in `restoreDataFromBackup`, which runs after `RestorerFromBackup` has already created the table. Because the `StorageMaterializedPostgreSQL` constructor calls `replication_handler->startup`, a rejected `RESTORE TABLE` into a not-yet-existing target left a live table replicating from the live PostgreSQL source (the restore is not rolled back on a later failure), so the fail-close did not actually fail closed. Reject the restore in `registerStorageMaterializedPostgreSQL` when `args.is_restore_from_backup` is set, i.e. before the storage is constructed, so no table is created and no replication is started. `restoreDataFromBackup` keeps its `NOT_IMPLEMENTED` throw as the safety net for an in-place restore into an already-existing `MaterializedPostgreSQL` table. This mirrors the database-level rejection in `RestorerFromBackup::createDatabase`, which already fails before creation. The `test_backup_table_engine` integration test now asserts the rejected restore leaves no table behind (`EXISTS TABLE` is `0`). Addresses the AI Review on ClickHouse#107433 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ynchronized table `BACKUP DATABASE` of a `MaterializedPostgreSQL` database could succeed while silently omitting a table whose nested `ReplacingMergeTree` was never created. The fail-closed guard added earlier in `StorageMaterializedPostgreSQL::backupData` only runs for the standalone table-engine path; the database backup path bypasses it: `BackupEntriesCollector` enumerates tables via `DatabaseWithOwnTablesBase::getTablesForBackup`, which iterates `DatabaseMaterializedPostgreSQL::getTablesIterator`. That iterator runs in the nested context, so it only sees the already-created nested `ReplacingMergeTree` tables and backs them up directly, never touching the `StorageMaterializedPostgreSQL` wrappers. A table that the database is configured to replicate but whose nested table has not been created yet (its initial snapshot from PostgreSQL is still in progress or failed - e.g. the PostgreSQL table has no primary key and no replica identity index, so `createNestedIfNeeded` throws and, in the database engine, that failure is logged and swallowed) is therefore left out of the backup without any error. Override `getTablesForBackup` in `DatabaseMaterializedPostgreSQL` to first walk the configured `materialized_tables` and refuse the whole backup with `CANNOT_BACKUP_TABLE` when any requested table still has no nested table, mirroring the fail-closed check in `backupData`. The filter is honored so that `BACKUP TABLE` of a synchronized table is unaffected by an unrelated unsynchronized one. Addresses the AI Review "Request changes" verdict on ClickHouse#107433 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…egate Make BACKUP work for MaterializedPostgreSQL databases
…erializedPostgreSQL table `DatabaseMaterializedPostgreSQL::getCreateTableQueryImpl` rebuilt the definition of every table from the current PostgreSQL catalog when called with a query context, even when the nested `ReplacingMergeTree` exists. BACKUP stores that definition together with the nested table's parts, whose columns and sorting key were fixed when the nested table was created. When the PostgreSQL primary key or replica identity changes after replication started (logical replication carries no DDL and an existing nested table is never re-created), or when the key column order returned by `fetchPostgreSQLTableStructure` changes with an upgrade (ClickHouse#127137), RESTORE created the table with the new key over parts sorted by the old one, and key-filtered reads returned too few rows (81 of 999 in ClickHouse#128271) while `CHECK TABLE` passed. `SHOW CREATE TABLE` reported a key the table does not have. Return the stored definition (`DatabaseAtomic::getCreateTableQueryImpl`, already used without a query context) when the nested table exists. The PostgreSQL-derived definition remains for a name without a nested table, which `ATTACH TABLE <db>.<table>` needs to add a table to replication. The UUID lookup added in ClickHouse#107433 to keep repeated reads stable for BACKUP is dead now (an existing table returns its stored UUID) and is removed. `SHOW CREATE TABLE` now includes `SETTINGS index_granularity = 8192`, so `test_table_override` expects it, and the restore in `test_backup_database` no longer needs `allow_different_table_def` (kept, as in the documented recipe). Closes ClickHouse#128271 Co-Authored-By: Claude Opus 5.5 <[email protected]>
BACKUPof aMaterializedPostgreSQLdatabase hung forever (and could not be killed), repeatedly logging:Two root causes:
Non-deterministic table definition.
DatabaseMaterializedPostgreSQL::getCreateTableQueryImplassigned a freshly generated random UUID (generateV4) on every metadata read.BackupEntriesCollectorreads table metadata several times and requires it to stay identical between passes, so it saw the definition "change" on every read and never converged. This PR uses the table's actual (stable) UUID instead. As a bonus,SHOW CREATE TABLEfor these tables is now deterministic.No data was backed up.
StorageMaterializedPostgreSQLdid not overridebackupData/restoreDataFromBackup, and the defaultIStorageimplementation is a no-op — so even a completed backup would contain no data. This PR overridesbackupDatato delegate to the nestedReplacingMergeTree(mirroringStorageMaterializedView), so the materialized data is captured. The backed-up data can then be restored as a standaloneReplacingMergeTree.Restoring a
MaterializedPostgreSQLtable in place is intentionally not supported: the storage starts replicating from the live PostgreSQL source the moment it is created (its constructor callsreplication_handler->startup), so restoring the backed-up parts on top would mix the backup snapshot with the current remote state. Following the fail-close principle,restoreDataFromBackupthrowsNOT_IMPLEMENTEDwith a message directing the user to restore the data as a standaloneReplacingMergeTreeinstead.The integration test
test_backup_databasecreates aMaterializedPostgreSQLdatabase, runsBACKUP DATABASE(which must now complete instead of hanging), thenRESTOREs a table as a standaloneReplacingMergeTreeand checks the data matches. A second test,test_backup_table_engine_restore_rejected, backs up a standaloneMaterializedPostgreSQLtable-engine table and asserts that an in-placeRESTOREis rejected with a clear exception.The supported backup/restore workflow is described in
docs/en/engines/database-engines/materialized-postgresql.md.Closes: #44252
Related: #49045
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
BACKUPof aMaterializedPostgreSQLdatabase no longer hangs forever with "Table ... were created or changed its definition during scanning", and now actually backs up the table data (delegated to the underlyingReplacingMergeTree), which can be restored as a standaloneReplacingMergeTree.Documentation entry for user-facing changes
Version info
26.7.1.457(included in26.7and later)