Skip to content

Make BACKUP work for MaterializedPostgreSQL databases - #107433

Merged
alexey-milovidov merged 23 commits into
masterfrom
matpg-backup-delegate
Jul 2, 2026
Merged

alexey-milovidov merged 23 commits into
masterfrom
matpg-backup-delegate

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

BACKUP of a MaterializedPostgreSQL database hung forever (and could not be killed), repeatedly logging:

BackupEntriesCollector: DB::Exception: Table ... were created or changed its definition during scanning

Two root causes:

  1. Non-deterministic table definition. DatabaseMaterializedPostgreSQL::getCreateTableQueryImpl assigned a freshly generated random UUID (generateV4) on every metadata read. BackupEntriesCollector reads 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 TABLE for these tables is now deterministic.

  2. No data was backed up. StorageMaterializedPostgreSQL did not override backupData/restoreDataFromBackup, and the default IStorage implementation is a no-op — so even a completed backup would contain no data. This PR overrides backupData to delegate to the nested ReplacingMergeTree (mirroring StorageMaterializedView), so the materialized data is captured. The backed-up data can then be restored as a standalone ReplacingMergeTree.

    Restoring a MaterializedPostgreSQL table in place is intentionally not supported: the storage starts replicating from the live PostgreSQL source the moment it is created (its constructor calls replication_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, restoreDataFromBackup throws NOT_IMPLEMENTED with a message directing the user to restore the data as a standalone ReplacingMergeTree instead.

The integration test test_backup_database creates a MaterializedPostgreSQL database, runs BACKUP DATABASE (which must now complete instead of hanging), then RESTOREs a table as a standalone ReplacingMergeTree and checks the data matches. A second test, test_backup_table_engine_restore_rejected, backs up a standalone MaterializedPostgreSQL table-engine table and asserts that an in-place RESTORE is 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):

  • 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):

BACKUP of a MaterializedPostgreSQL database 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 underlying ReplacingMergeTree), which can be restored as a standalone ReplacingMergeTree.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.457 (included in 26.7 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78227cf]

Summary: ✅


AI Review

Summary

This PR fixes the original MaterializedPostgreSQL backup hang and closes several earlier restore/partial-backup holes, but two correctness risks remain in the new backup paths. One can still produce an incomplete standalone table backup during background attach/initialization, and the new database-level fail-closed guard relies on a mutex that does not actually synchronize the wrapper map with its writers.

Findings

❌ Blockers

  • [src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp:313] backupData for the standalone table engine only checks whether the nested ReplacingMergeTree exists. On the ATTACH path, PostgreSQLReplicationHandler::loadFromSnapshot creates that nested table before it streams snapshot rows and before initialization completes, so BACKUP TABLE can succeed against a half-loaded nested table and produce an incomplete backup. Suggested fix: fail closed until the standalone engine's initial synchronization has completed, using an explicit completion signal rather than tryGetNested() alone.
  • [src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp:551] getTablesForBackup tries to make the empty-map / missing-nested pre-scan safe with tables_mutex, but materialized_tables is mutated elsewhere without that mutex (startSynchronization, attachTable, stopReplication, detachTablePermanently). The exact startup window this code is intended to cover can therefore still race with concurrent std::map mutation, so the new fail-closed guard is not actually synchronized. Suggested fix: protect every materialized_tables access with one consistent lock, or use the existing writer-side lock here before treating the pre-scan as a safety boundary.
Tests
  • ⚠️ Add a standalone table-engine ATTACH / restart regression where BACKUP TABLE is attempted while loadFromSnapshot is still running, and assert the backup is rejected until initialization finishes.
  • ⚠️ Add a startup-concurrency regression once materialized_tables locking is unified; the current bad-credentials test avoids the writer race because fetchRequiredTables fails before the map is populated.
Final Verdict

⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 14, 2026
alexey-milovidov and others added 2 commits June 14, 2026 17:18
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]>
alexey-milovidov and others added 3 commits June 16, 2026 11:07
# 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]>
alexey-milovidov and others added 2 commits June 18, 2026 00:36
…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]>
Comment thread src/Backups/RestorerFromBackup.cpp Resolved
…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]>
Comment thread src/Backups/RestorerFromBackup.cpp Resolved
alexey-milovidov and others added 3 commits June 24, 2026 03:00
# 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 murphy-4o self-assigned this Jun 26, 2026

@murphy-4o murphy-4o left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/Backups/RestorerFromBackup.cpp Resolved
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed e4d03c656bd..5ace7c8d06d addressing the AI Review ⚠️ Request changes verdict.

supportsBackupPartition delegation (e226ad2b2c8)
StorageMaterializedPostgreSQL::backupData already forwarded the selected partitions to the nested ReplacingMergeTree, but the storage still inherited IStorage::supportsBackupPartition (which returns false), so BackupEntriesCollector rejected BACKUP TABLE ... PARTITIONS with "doesn't support partitions" before the delegation could run. Now supportsBackupPartition delegates to the nested table, mirroring StorageMaterializedView. Same gate is shared by standalone table-engine tables and per-table backups inside a MaterializedPostgreSQL database.

Regression test test_backup_table_partitions (5ace7c8d06d)
Partitions the nested ReplacingMergeTree via a TABLE OVERRIDE (... PARTITION BY key), backs up a subset of partitions with BACKUP TABLE ... PARTITIONS '1', '3', restores them into a standalone ReplacingMergeTree, and asserts only the selected partitions are present.

Note: the test uses the database-engine TABLE OVERRIDE path rather than a standalone table-engine table, because the standalone engine does not propagate PARTITION BY to its nested table (it would have a single partition, so partition selectivity would not be observable). The supportsBackupPartition override under test is identical for both paths.

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:

  • Integration tests (amd_tsan, 3/6) → test_keeper_zookeeper_converter::test_multi_and_failed_requests[True]: ZooKeeper container failed to start (zkServer.sh start returns 1) — pure test-infra; fails on many unrelated PRs over the last 30 days (108583, 107884, 107566, 107442). Zero MaterializedPostgreSQL involvement.
  • Stress test (amd_tsan) / Stress test (arm_tsan) → Hung check: tracked by open Hung check failed, possible deadlock found #107941; AST-fuzzer/TCPHandler stacks, no PR frames.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI status on 5ace7c8d — the fresh run finished its build/test phases (only Stress test (amd_tsan) is still in flight); all current reds are pre-existing master-wide flakes unrelated to this PR's MaterializedPostgreSQL backup change, each with an open tracking issue. The PR touches only RestorerFromBackup.cpp, DatabaseMaterializedPostgreSQL.cpp, StorageMaterializedPostgreSQL.{cpp,h}, docs, and the integration test — none of the failing code paths.

I did not re-merge master (branch is behind but MERGEABLE with no conflicts, merge-base is <1 day old, and the reds reproduce on master so a re-merge would not clear them). The three failed jobs could not be re-run yet because the workflow is still running (Stress test (amd_tsan)); they should be re-run once it completes.

Otherwise the PR looks ready: AI Review is ✅ Approve on this commit, @murphy-4o approved, and there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Follow-up on 5ace7c8d: the workflow has finished. Stress test (amd_tsan) — which was still in flight in my previous comment — completed as the chronic Hung check flake (open #107941): the job hit its 10800s timeout (exit -15) with the server unresponsive to SYSTEM STOP DISTRIBUTED SENDS during shutdown (SOCKET_TIMEOUT, 300000 ms), no MaterializedPostgreSQL/backup frames.

So all 4 reds are pre-existing master-wide flakes, each with an open tracking issue, and none touch this PR's code paths (RestorerFromBackup.cpp, DatabaseMaterializedPostgreSQL.cpp, StorageMaterializedPostgreSQL.{cpp,h}, docs, integration test):

I re-ran the 4 failed jobs (all were attempt 1 on this commit). Did not re-merge master: the branch is behind but MERGEABLE with no conflicts, the merge-base is <1 day old, and the reds reproduce on master so a re-merge would not clear them.

The PR is otherwise ready: AI Review ✅ Approve on this commit, @murphy-4o approved, no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI status on 5ace7c8d — no code change needed; both remaining reds are pre-existing flakes unrelated to this PR's MaterializedPostgreSQL backup change, and both have been re-run.

  • Stress test (amd_tsan) — the chronic Hung check flake (open Hung check failed, possible deadlock found #107941): the job hit its 10800s timeout with the server unresponsive at shutdown; the log tail has no MaterializedPostgreSQL/backup frames. Re-ran the failed job.

  • CH Inc sync — tests failed — the private sync PR (clickhouse-private#60886) merged and built cleanly; only two Cloud-only integration tests failed, each an isolated single-test failure (1 failed, N passed) in suites this PR does not touch:

    • test_distributed_cache/test.py::test_idle_client_ttl (distributed-cache TTL/timing test)
    • test_refreshable_mv_no_multi_read/test.py::test_refreshable_mv_attach_without_multi_read (refreshable-MV Cloud feature)

    Re-ran the failed private jobs.

The PR touches only RestorerFromBackup.cpp, DatabaseMaterializedPostgreSQL.cpp, StorageMaterializedPostgreSQL.{cpp,h}, docs, and the test_postgresql_replica_database_engine integration test — none of the failing code paths. AI Review is ✅ Approve, all review threads are resolved, and the PR is approved.

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]>
alexey-milovidov and others added 2 commits July 2, 2026 04:05
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed ae07de7360a..9aa70b75ee9 addressing the AI Review ⚠️ Request changes verdict (database-level BACKUP DATABASE could produce a partial snapshot).

Verified the finding is real. BackupEntriesCollector enumerates a database's tables via DatabaseWithOwnTablesBase::getTablesForBackup, which iterates DatabaseMaterializedPostgreSQL::getTablesIterator. That iterator runs in the nested context (makeNestedTableContext), so it only sees the already-created nested ReplacingMergeTree tables and backs them up directly — the StorageMaterializedPostgreSQL wrappers (and hence the fail-closed guard in backupData) are never reached for the database path. A table the database is configured to replicate but whose nested table was never created is therefore silently omitted from the backup. In the database engine this state is reachable and swallowed: if createNestedIfNeeded throws for a table (e.g. a PostgreSQL table with no primary key and no replica identity index → "has no primary key and no replica identity index"), the per-table failure in PostgreSQLReplicationHandler's initial_sync is logged but not rethrown (throw_on_error && !is_materialized_postgresql_database), leaving that table's wrapper with hasNested() == false.

Fix (23d26c7a941) — override getTablesForBackup in DatabaseMaterializedPostgreSQL to first walk 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 StorageMaterializedPostgreSQL::backupData. The filter is honored, so BACKUP TABLE of a synchronized table is unaffected by an unrelated unsynchronized one. The standalone table-engine path is unchanged (it still hits the wrapper's backupData guard).

Regression test (9aa70b75ee9) — test_backup_database_fails_closed_on_unsynchronized_table builds a MaterializedPostgreSQL database over a normal table plus a no-primary-key/no-replica-identity table (which deterministically ends up with no nested table), and asserts BACKUP DATABASE fails closed instead of producing a partial backup.

The C++ change compiles clean (-fsyntax-only against current headers); the integration test relies on CI like the other backup tests in this PR.

…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();

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.

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);

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 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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 72/90 (80.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit b63e285 into master Jul 2, 2026
173 of 174 checks passed
@alexey-milovidov
alexey-milovidov deleted the matpg-backup-delegate branch July 2, 2026 20:28
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 2, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…egate

Make BACKUP work for MaterializedPostgreSQL databases
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Nov 16, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BACKUP doesn't work with database engine MaterializedPostgreSQL

4 participants