Repository navigation
Fix MaterializedPostgreSQL database/table with ON CLUSTER - #110493
alexey-milovidov wants to merge 88 commits into
Conversation
A `MaterializedPostgreSQL` database or table created via `ON CLUSTER` receives the same ClickHouse UUID on every replica. With `materialized_postgresql_use_unique_replication_consumer_identifier` enabled, the replication slot name was derived from that UUID and the publication name from the PostgreSQL database/table name, so all replicas produced identical slot and publication names and fought over a single PostgreSQL replication slot and publication: only one replica replicated correctly, the others failed with a `pqxx::unique_violation` (duplicate publication) or could not hold the slot. Mix in the persistent per-server `ServerUUID` (hashed together with the ClickHouse UUID into a single UUID via `makeUUIDv4FromHash`, so the result stays within PostgreSQL's identifier length limit) so that both the replication slot and the publication are unique per (ClickHouse object, server). Each replica now gets its own slot and publication and replicates independently. Closes: #58726 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Validated locally on ARM with an ASan binary: the new |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
# Conflicts: # src/Storages/PostgreSQL/PostgreSQLReplicationHandler.cpp
|
Workflow [PR], commit [983e391] Summary: ✅
AI ReviewSummaryReviewed head Final VerdictStatus: ✅ Approve |
Address AI review: salting the unique replication consumer identifier with `ServerUUID` renamed the generated replication slot and publication for existing deployments that already run with `materialized_postgresql_use_unique_replication_consumer_identifier = 1`, so an `ATTACH` after an upgrade would miss the old slot, run an initial sync, reload the snapshot into the already-populated nested tables (duplicating data), and leave the old slot and publication orphaned. On attach, when the salted slot does not exist but the pre-salt one (the bare ClickHouse object UUID) does, adopt the pre-salt slot and publication. The pre-salt slot name embeds this object's own UUID, so its existence is itself proof of ownership; `ON CLUSTER` replicas that shared the UUID before the fix fought over that slot already, so adopting keeps them exactly as broken as they were (never worse), and recreating the object moves them to the fixed per-server identity. Covered by a new integration test that reconstructs the pre-salt PostgreSQL-side state under a stopped server and checks that a restart adopts it: no re-snapshot, streamed changes arrive, and `DROP DATABASE` removes the adopted objects.
…alt publication The pre-salt publication name for the ON CLUSTER fix (`legacy_publication_name`) ignores `materialized_postgresql_use_unique_replication_consumer_identifier` and is always the schema-blind `<postgres_database>[_<postgres_table>]_ch_publication` form (schema is forced empty in its construction). Its mere existence therefore proves nothing about which engine's schema it belongs to, unlike the pre-salt slot name, which embeds this object's own ClickHouse UUID. A database or table replicating a non-default `materialized_postgresql_schema` that loses its own salted publication on attach could adopt a schema-blind pre-salt publication that actually belongs to a different, default-schema engine (or another schema targeting the same bare table): the schema-scoped replica would then filter WAL through the wrong table list and miss its own schema's changes. Require the same ownership proof `adoptLegacyReplicationIdentityIfNeeded()` already requires for the schema-aware rename below: every table the pre-salt publication publishes must belong to this engine's schema (`pg_publication_tables`, normalizing an empty/`"public"` schema to compare against). If ownership cannot be proven, the pre-salt publication is left alone and a fresh salted publication is created instead — the pre-salt slot adoption (self-proving via the embedded ClickHouse UUID) is unaffected. Add `test_unique_identifier_legacy_publication_not_adopted_across_schemas`, which plants a hand-crafted publication under the schema-blind name to stand in for a foreign, default-schema engine, then upgrades a schema-scoped database that lost its own salted objects: the pre-salt slot is adopted, the foreign publication is left untouched, and a fresh salted publication is created for the engine's own schema, so no cross-talk between the two schemas' changes is observed.
The unique-identifier half of `adoptLegacyReplicationIdentityIfNeeded` had two problems when adopting the schema-blind pre-salt publication on attach after an upgrade. 1. The ownership check only consulted `materialized_postgresql_schema`, coercing an empty value to `public`. But `materialized_postgresql_schema_list` and `materialized_postgresql_tables_list_with_schema` also leave that setting empty while legitimately replicating non-default schemas, so such a deployment never recognized its own pre-salt publication, created a fresh salted one, and orphaned the old one. The check now derives the full set of replicated schemas (see `computeReplicatedSchemas`) from the single common schema, the schema list, or the per-table schemas of `tables_list`. 2. When the pre-salt slot was adopted but the pre-salt publication could not be (missing or foreign), the code created a fresh salted publication and streamed through it. That silently loses every change written to WAL before the fresh publication existed: `pgoutput` resolves publication membership from the historic catalog snapshot at each change's LSN, so a not-yet-created publication is skipped (`WARNING: skipped loading publication`) and its rows never reach the replica, which falls permanently behind without any error. Once the pre-salt slot is adopted its pre-salt publication must be reused; if it is missing or belongs to another engine the attach now fails closed (startup keeps retrying and replication resumes once the conflict is resolved), matching the schema-aware branch. The previously added integration test `test_unique_identifier_legacy_publication_not_adopted_across_schemas` asserted the (impossible) fresh-publication sync and hung until timeout on every shard; it is rewritten to assert the fail-closed behavior and recovery. A new `test_unique_identifier_adopts_own_publication_from_schema_list` covers the `schema_list` ownership path. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110493&sha=8084392d37aa5f4419bbd63ca007a366076256a3&name_0=PR PR: #110493 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The new `test_unique_identifier_adopts_own_publication_from_schema_list` used a single-schema `materialized_postgresql_schema_list`, which `fetchPostgreSQLTablesList` intentionally does not schema-qualify: it prefixes table names with the schema only when the list names more than one schema. As a result the nested table was created as the bare `postgresql_replica_0`, and `createPublicationIfNeeded` built `CREATE PUBLICATION ... FOR TABLE ONLY "postgresql_replica_0"`, which PostgreSQL rejected with `relation "postgresql_replica_0" does not exist` because the table lives in a non-default schema. Initial sync therefore failed before the attach-time adoption path under test was ever reached (`test_3.py` failed on every integration shard). Use a multi-schema list (two non-default schemas), matching the existing `test_database_with_multiple_non_default_schemas_2`, so table names are schema-qualified end to end. This still exercises the `schema_list` branch of `computeReplicatedSchemas` and the schema-ownership check that adopts the schema-blind pre-salt publication on upgrade. A single-schema `materialized_postgresql_schema_list` for a non-default schema is a separate, pre-existing limitation unrelated to this fix. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110493&sha=bc2e2f40f9db3e46274b646cbfb8ba5baf7d7cb8&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@groeneai, the |
|
@alexey-milovidov Confirmed: Separate fix PR already open: #110677 (mirrors the sibling |
…ifier Address the AI review blocker: a user-provided `materialized_postgresql_replication_slot` bypasses the per-server-unique replication identity that `materialized_postgresql_use_unique_replication_consumer_identifier` provides for `ON CLUSTER` deployments. `ON CLUSTER` assigns the same settings (and therefore the same user-managed slot name) to every replica, so they all bind to one logical PostgreSQL replication slot and fight over it even though the publication name is made unique per server. Only one replica could ever stream, which is exactly the failure this feature exists to prevent (#58726). The generated publication can be made per-server, but a user-managed slot has a single fixed name and cannot be, so the two settings contradict each other. Reject the combination in the `PostgreSQLReplicationHandler` constructor with a clear `BAD_ARGUMENTS` error instead of silently leaving all but one replica unable to replicate. The check fires only on `CREATE`, not `ATTACH`, so an already-created single-server deployment that happens to set both settings keeps starting up after an upgrade. Add `test_on_cluster_user_managed_slot_rejected`: a `CREATE DATABASE ON CLUSTER` with both settings fails closed on every replica (with the error logged from the replication startup task) and creates no replication slot or publication. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ntifier Note in the `materialized_postgresql_use_unique_replication_consumer_identifier` documentation that it cannot be combined with a user-managed `materialized_postgresql_replication_slot`, and that the combination is rejected on `CREATE`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses the AI review blocker on `PostgreSQLReplicationHandler.cpp`: the attach-time ownership proof for a schema-blind pre-salt publication only checked that every published table belonged to a schema this engine replicates, not that the publication's table set was actually this engine's set of tables. A same-schema publication with the wrong table set (e.g. this engine replicates `foo.a, foo.b` while the publication publishes only `foo.c`) therefore passed the check, `adoptLegacyReplicationIdentityIfNeeded` switched `publication_name` to it, and replication then streamed through the wrong publication — some intended tables would silently stop receiving WAL after upgrade while the extra ones were only skipped, violating the fail-closed contract. The unique-identifier branch now adopts the pre-salt publication only when it publishes EXACTLY this engine's set of replicated tables. The expected `(schema, table)` set is derived from `tables_list` (including the single-table engine's raw remote table name), or, in full-schema mode, from `fetchPostgreSQLTablesList` over the replicated schema(s). A schema mismatch and a table-set mismatch each produce a distinct, actionable reason; when ownership cannot be proven the attach fails closed (never hijacking a foreign publication, never creating a fresh publication that would lose the WAL gap) and keeps retrying, so replication resumes once the operator restores the correct publication. Adds `test_unique_identifier_legacy_publication_not_adopted_with_wrong_table_set`, which plants a same-schema pre-salt publication publishing only one of the engine's two tables, verifies the upgrade fails closed with the new message and makes no progress, and that recovery (restoring the correct publication) adopts it and streams the WAL gap. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses the AI review major on `PostgreSQLReplicationHandler.cpp:405`: the mutual-exclusion check between `materialized_postgresql_replication_slot` and `materialized_postgresql_use_unique_replication_consumer_identifier` only ran when the `PostgreSQLReplicationHandler` was constructed. For the `MaterializedPostgreSQL` database engine that happens in the background `tryStartSynchronization` task, after the metadata has already been written, so `CREATE DATABASE` still succeeded and left a database that retried forever in the background — contradicting the code comment, the source docs, and the `ON CLUSTER` regression test, all of which say the combination is rejected on `CREATE`. The check now also runs in the database factory (`registerDatabaseMaterializedPostgreSQL`), which executes synchronously during `CREATE DATABASE` and before any metadata is persisted (`InterpreterCreateQuery::createDatabase` constructs the database object before writing the metadata file), so the query is rejected outright. It stays gated on `!attach`, matching the handler check and keeping an already-created single-server deployment startable after an upgrade. The single-table storage engine keeps failing synchronously via the handler check, as before. `test_on_cluster_user_managed_slot_rejected` now asserts that `CREATE DATABASE ... ON CLUSTER` fails with the error and that no database, slot, or publication is created on any replica. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…test A plain `count()` also counts the rows that were deleted in PostgreSQL, so the test counts them the same way as the other `MaterializedPostgreSQL` tests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110493&sha=6ba2047f02b&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%2C%20function_prop_fuzzer%29 ( |
|
The fix is my #126210 (open). The stuck worker at Mechanism: #120908 (comment). #126210 changes only the test harness; its CI has finished and it is mergeable, still without a review. |
…alizedPostgreSQL` object `CREATE TABLE ... ON CLUSTER ... AS src` copies the engine settings of `src`, including the stored `materialized_postgresql_unique_replication_consumer_server_uuid`, on the initiator. All replicas then derived the same replication slot and publication names. Now a fresh `CREATE` always writes the UUID of the executing server into the definition, replacing an inherited value, while `ATTACH` keeps the stored one. Add a regression test for `CREATE TABLE ... ON CLUSTER ... AS`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master (
|
|
🕵 The only red check on |
… a new PostgreSQL table A table created in PostgreSQL after `CREATE DATABASE` is not replicated without an explicit `ATTACH TABLE`, so it has no nested table. On attach, the whole-schema database took the list of tables to replicate from the live PostgreSQL schema, failed on the missing nested table of the new one, and retried forever without resuming replication of the other tables. Now on attach only the tables that have nested tables are replicated. A table that is in the publication but was never materialized (for example, its initial snapshot has failed) is named in a warning together with the recovery, `ATTACH TABLE`, which now reuses the existing publication membership instead of failing on a duplicate `ALTER PUBLICATION ... ADD TABLE`. Related: ClickHouse#110493 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_shared_publication` The test added on master relies on two databases with `materialized_postgresql_use_unique_replication_consumer_identifier = 1` sharing one publication. With this PR, newly created databases mix the server UUID into the identifier and get separate publications, so the test would no longer exercise the shared publication. Disable `materialized_postgresql_use_unique_replication_consumer_identifier_mixed_with_server_uuid` there, as for the databases created by older versions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master ( Master also added |
…essage `deleted_tables` and `waiting_list` of `MaterializedPostgreSQLConsumer` are keyed by the ClickHouse table name, which includes the PostgreSQL schema when `materialized_postgresql_schema_list` or `materialized_postgresql_tables_list_with_schema` is used. The `Insert`, `Update` and `Delete` messages already pass that name, but the `Relation` message passed the bare PostgreSQL relation name. So in the multi-schema modes a table removed with `DETACH TABLE ... PERMANENTLY` was not recognized as deleted when its `Relation` message was still in the replication stream: the consumer logged a misleading error that the storage does not exist and put the table into the skip list. Related: ClickHouse#110493 Co-Authored-By: Claude Opus 5.5 <[email protected]>
When `MaterializedPostgreSQLConsumer::consume` threw (for example, `syncTables` failed to flush a buffered table because a materialized view on the nested table throws), `PostgreSQLReplicationHandler::consumerFunc` rescheduled the consumer task immediately, ignoring `materialized_postgresql_backoff_min_ms`. The task then ran back-to-back on the pool threads, re-acquiring its `exec_mutex` right away, and `BackgroundSchedulePoolTaskInfo::deactivate` (used by `DETACH TABLE`, `ATTACH TABLE` and shutdown) could starve on that mutex for minutes. This made `test_postgresql_replica_database_engine/test_3.py::test_detach_table_with_pending_buffer` flaky: `DETACH TABLE ... PERMANENTLY` hung for 364 s under ASan. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110493&sha=ca77771a0dba59ede9b97d7b289482f6e8aad138&name_0=PR&name_1=Integration%20tests%20(amd_asan_ubsan%2C%20flaky) ClickHouse#110493 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… test config Master renamed `allow_experimental_database_materialized_postgresql` to `enable_database_materialized_postgresql` (the old name is kept as an alias) and updated the other `MaterializedPostgreSQL` test configs; do the same here. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master ( |
|
🕵 Merged master ( |
Closes: #58726
A
MaterializedPostgreSQLdatabase or table created withON CLUSTERgets the same ClickHouse UUID on every replica. Withmaterialized_postgresql_use_unique_replication_consumer_identifier = 1the replication slot name was derived from that UUID, and the publication name from the PostgreSQL database/table name, so all replicas used the same slot and publication and only one of them replicated.This adds a new table-level setting,
materialized_postgresql_use_unique_replication_consumer_identifier_mixed_with_server_uuid. When it is enabled together withmaterialized_postgresql_use_unique_replication_consumer_identifier, the names of the replication slot and the publication are derived from the hash of the ClickHouse UUID and the persistentServerUUID, so each replica has its own slot and publication.The setting is
1by default, but an absent setting is treated as0: onCREATEit is written explicitly into the stored definition, and onATTACHa definition without it (created by an older version) keeps the old names. Existing databases and tables continue to work as is, with no migration, and new ones get the behavior suitable for distributed operation by default.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
MaterializedPostgreSQLdatabases and tables created withON CLUSTERandmaterialized_postgresql_use_unique_replication_consumer_identifier = 1: replicas no longer share a single PostgreSQL replication slot and publication. Added a settingmaterialized_postgresql_use_unique_replication_consumer_identifier_mixed_with_server_uuid, enabled by default for newly created databases and tables; the existing ones keep using their replication slot and publication.Documentation entry for user-facing changes
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/110493]