Repository navigation
MaterializedPostgreSQL: coordinated Replicated/Shared nested tables for HA - #110886
alexey-milovidov wants to merge 214 commits into
Conversation
…or HA
Let the nested tables created by the MaterializedPostgreSQL database and table
engines use ReplicatedReplacingMergeTree / SharedReplacingMergeTree instead of
the hardcoded ReplacingMergeTree, gated behind a new Keeper-based
single-active-worker coordination mechanism.
A PostgreSQL logical replication slot allows only one active consumer, so two
ClickHouse replicas consuming the same slot would race on
pg_replication_slot_advance and lose WAL. The new coordination elects exactly
one active worker via an ephemeral node in Keeper (the same pattern as S3Queue,
the Keeper-coordinated Kafka engine and refreshable materialized views).
Standby replicas create the nested tables as replicas of the same replicated
tree and receive data through ClickHouse replication; when the active worker's
Keeper session ends, a standby takes over and resumes consuming the shared
slot from its confirmed LSN (no reload, no duplication).
New settings:
- materialized_postgresql_table_engine: ReplacingMergeTree (default) |
ReplicatedReplacingMergeTree | SharedReplacingMergeTree
- materialized_postgresql_keeper_path: opt-in gate that enables coordination
(supports {uuid}/{shard}/{replica} macros)
- materialized_postgresql_replica_name: default {replica}
The replicated/shared engines require materialized_postgresql_keeper_path, and
coordination is mutually exclusive with
materialized_postgresql_use_unique_replication_consumer_identifier.
Closes #47655
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [d6614f9] Summary: ❌
AI ReviewSummaryThe PR adds Keeper-coordinated, single-active-worker replication for Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Preserve the projection during failed-detach recovery and close the retained correctness gaps. Complete refused-drop recovery for stopped nested storage and cover the failing paths with focused regressions. |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
…ated-replicated-tables
…ecycle Fixes the CI crash and the three review blockers of the coordinated MaterializedPostgreSQL mode (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110886&sha=d513b334a7b5c3566267ad262b1737cb5499e6ba&name_0=PR, #110886): - Set the Keeper request component (Coordination::setCurrentComponent) in every coordination code path. Its absence made the server abort in sanitizer builds with the logical error "Current component is empty" as soon as coordinationFunc issued its first Keeper request, which crashed the server in a loop and failed all tests of test_coordination.py. - Persist a durable snapshot-completion marker (<keeper_path>/snapshot_completed) after the initial snapshot has loaded every table. A new active worker may resume from the slot's confirmed_flush_lsn only when the marker exists; otherwise the previous worker died mid-snapshot and the new one drops the slot and redoes the snapshot, so rows preceding the slot-creation LSN cannot be lost. Re-inserted rows collapse in the ReplacingMergeTree nested tables. - Treat the publication as shared state, like the slot: a second coordinated CREATE (createPublicationIfNeeded, fetchRequiredTables) adopts an existing publication instead of dropping it from under the active worker. - Register every replica under <keeper_path>/replicas; DROP drops the shared slot and publication (and the coordination nodes) only together with the last registered replica, and keeps them while other replicas are alive (fail-close when Keeper is unavailable). - Refuse ATTACH TABLE / DETACH TABLE PERMANENTLY in coordinated mode (NOT_IMPLEMENTED, before any metadata is mutated): they would change the shared publication and the tables list on one replica only, breaking the other replicas and the next failover. - Require materialized_postgresql_keeper_path to be combined with a replicated/shared nested table engine: with a plain ReplacingMergeTree the standbys hold no data and a takeover would lose every previously replicated row. New integration tests: takeover before snapshot completion reloads all rows, a second CREATE adopts the publication, ATTACH/DETACH are rejected, and a drop keeps the shared PostgreSQL objects until the last replica. Co-Authored-By: Claude Fable 5 <[email protected]>
…lizedPostgreSQL `test_attach_detach_table_is_rejected_in_coordinated_mode` failed deterministically: after a *refused* `DETACH TABLE ... PERMANENTLY` the nested `ReplicatedReplacingMergeTree` no longer received new rows. The coordinated-mode rejection lived in `DatabaseMaterializedPostgreSQL::detachTablePermanently`, but `InterpreterDropQuery` calls `table->flushAndShutdown()` (which shuts the nested table down) *before* it calls the database method. So by the time the rejection was thrown, replication of the nested table had already been stopped, and the "rejected" DETACH was not a no-op. Refuse earlier, in `StorageMaterializedPostgreSQL::checkTableCanBeDetached`, which `InterpreterDropQuery` calls before `flushAndShutdown`. The wrapper learns it belongs to a coordinated database through a new `setCoordinated` flag, set both on the cached wrappers and on the per-query wrapper that `DatabaseCatalog` builds (the one the DROP/DETACH interpreter operates on). The existing `detachTablePermanently` guard is kept as defense in depth. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…stration Addresses the three findings from the automated review on PR #110886: - Blocker: a coordinated `CREATE` with an empty `materialized_postgresql_tables_list` adopted the shared publication but still derived its table set from a fresh scan of the live PostgreSQL schema. If the schema drifted after the first replica created the publication, the joining replica built nested tables the publication never feeds, so they stayed empty forever after a failover. `fetchRequiredTables` now derives the table set from `fetchTablesFromPublication` in coordinated mode, falling back to a schema scan only when there is no publication to adopt. - Blocker: coordination could be combined with a user-managed `materialized_postgresql_replication_slot` / `materialized_postgresql_snapshot`, which breaks the mid-snapshot takeover contract - the next leader cannot drop and recreate a slot it does not own to re-export a fresh snapshot. `validateMaterializedPostgreSQLCoordinationSettings` now rejects both combinations up front. Setting description and docs updated. - Major: `registerReplicaInKeeper` ran before `ensureNestedTablesExist`, so a failure creating the local nested table left a ghost `/replicas/<name>` node with no `shutdownFinal` to remove it, which would keep the shared slot and publication alive forever. The two steps are now ordered so the replica is registered only after its local setup succeeds. New integration tests in `test_coordination.py`: `test_coordination_conflicts_with_user_managed_slot`, `test_coordination_conflicts_with_user_provided_snapshot`, `test_second_coordinated_create_adopts_publication_table_set`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… a mismatching tables_list When a second coordinated replica joins an existing shared publication with an explicit `materialized_postgresql_tables_list` that differs from that publication, `fetchRequiredTables` used to return the local setting. In coordinated mode the publication is authoritative shared state and is adopted (not recreated), so honoring the local list would make the replica build nested tables that PostgreSQL never publishes into (or skip tables the publication does publish), silently diverging replicas on which tables actually replicate. Derive the table set from the publication in coordinated mode and log a warning that the setting is overridden, mirroring the empty-`tables_list` adoption path. The non-coordinated behavior (use the setting, keep the publication) is unchanged. Addresses review feedback on PR #110886. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…l table The coordinated-mode guard previously only covered DETACH. `DROP TABLE` on one replica still routed through `checkTableCanBeDropped` and `DatabaseMaterializedPostgreSQL::dropTable`, which flushed, shut down, and removed the local nested `ReplicatedReplacingMergeTree` without updating the shared publication or `materialized_postgresql_tables_list`. The remaining replicas kept consuming a publication that still contained the table, and the dropping replica kept a wrapper for a nested table that no longer existed. Add a `StorageMaterializedPostgreSQL::checkTableCanBeDropped` override that refuses the operation before `InterpreterDropQuery` calls `flushAndShutdown` (so a rejected DROP/TRUNCATE stays a true no-op and does not stop replication), mirroring the existing DETACH guard. Add a database-side defense-in-depth check in `DatabaseMaterializedPostgreSQL::dropTable`, gated on a non-internal query context so DROP DATABASE and internal cleanup (which run with an internal context and operate on the nested tables directly) are unaffected. Addresses review feedback on PR #110886. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Fix the `pg_query` test helper to tolerate statements without a result set (DROP/INSERT/...): it unconditionally called `cursor.fetchall()`, which raises `psycopg2.ProgrammingError: no results to fetch` for a `DROP TABLE`, failing `test_second_coordinated_create_adopts_publication_table_set` deterministically in every integration configuration. Add two tests for the coordinated-mode review fixes: - `test_drop_table_is_rejected_in_coordinated_mode`: `DROP TABLE` of an individual nested table is refused on every replica and replication keeps working afterwards. - `test_coordinated_create_adopts_publication_over_mismatching_tables_list`: a joining replica with a superset `materialized_postgresql_tables_list` adopts the publication's table set instead of building an empty nested table for the extra, unpublished table. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…umn-filtered tables list Addresses the AI review on head c1e5723 (#110886): Blocker (`PostgreSQLReplicationHandler.cpp:1668`): coordinated adoption only made the *table names* authoritative. `expected_tables` strips `table(col1, col2)` down to `table`, but `getTableAllowedColumns` still reads the per-table column projection from each replica's local `materialized_postgresql_tables_list`. All coordinated replicas share one set of nested `ReplicatedReplacingMergeTree`/`SharedReplacingMergeTree` tables on the same Keeper path, so two replicas created with different column filters (or one with a filter and one without) would try to create diverging schemas on the same shared path, breaking the shared-state contract. Fix per the reviewer's endorsed option: reject a column-filtered `materialized_postgresql_tables_list` in coordinated mode (`validateMaterializedPostgreSQLCoordinationSettings`), so every replica builds the identical shared schema. Major (`PostgreSQLReplicationHandler.cpp:264`): `SharedReplacingMergeTree` was treated as a generally supported `materialized_postgresql_table_engine` value even though that storage is a ClickHouse Cloud engine not registered in the open-source build. `CREATE DATABASE` therefore succeeded and only failed later, when `ensureNestedTablesExist` reaches `InterpreterCreateQuery`, leaving the database stuck in a background retry loop. Fix: validate the requested nested engine against the actually-registered storages (`StorageFactory::instance().getAllStorages()`) and reject an unavailable engine at `CREATE` time. Updated the setting descriptions and `docs/en/engines/database-engines/materialized-postgresql.md`, and added integration tests `test_shared_engine_is_rejected_when_unavailable` and `test_coordination_conflicts_with_column_filtered_tables_list`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…redo and require Keeper at CREATE Addresses the AI review of PR #110886 (1 Blocker + 1 Major). Blocker (`PostgreSQLReplicationHandler.cpp`): a mid-snapshot failover left stale rows behind. When the active worker died before the initial snapshot completed, the next leader redid the snapshot but only re-inserted the current PostgreSQL state on top of the *existing* nested tables. A row the dead worker had already copied and that PostgreSQL then `DELETE`d has no counterpart in the new snapshot, so nothing overrode the stale copy (a `ReplacingMergeTree` collapses duplicate keys by `_version` but never turns a now-absent row into a tombstone). The recovery branch now first clears the nested tables via a new `truncateNestedTables` so the redo starts from an empty table and reproduces the exact current state. The nested tables are `ReplicatedReplacingMergeTree` / `SharedReplacingMergeTree`, so the `TRUNCATE` propagates to every replica. Major (`DatabaseMaterializedPostgreSQL.cpp`): a coordinated `CREATE DATABASE` was accepted on a server with no Keeper/ZooKeeper configured. The first failure only happened later inside the background startup task (at `getContext()->getZooKeeper()`), so the statement succeeded and the database sat in a permanent retry loop instead of rejecting the unsupported mode up front. `validateMaterializedPostgreSQLCoordinationSettings` now takes the context and rejects coordination when `hasZooKeeper` is false, at `CREATE` time (covering both the database and single-table engines). Tests: `test_takeover_after_partial_snapshot_drops_stale_deleted_rows` (a snapshot row is deleted in PostgreSQL while no consumer runs, and the from-scratch redo must not leave the stale row behind) and `test_coordination_requires_keeper_configured` (a new instance with no Keeper configured rejects the coordinated `CREATE` synchronously). Docs updated. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@alexey-milovidov Thanks. Fix PR for the 4514-3f61 crash is open: #110930 "Fix crash in -Tuple combinator with RESPECT NULLS producing a state" (ours, mergeable). No separate tracking issue needed, that PR is the owner. Root cause: the One correction on the grouping:
|
|
Correction on STID 4211-3a99 (the #110380 crash): it is not a separate bug and does not need its own PR. It has the same root cause as 4514-3f61 and is fixed by the same PR, #110930. I was wrong that the different crash site ( So #110930 owns both 4211-3a99 and 4514-3f61. No separate PR from me. |
…shot before discarding stopped copies, treat a failed publication removal as committed Three review blockers on `MaterializedPostgreSQL` coordination: - A failed `removeTableFromReplication` in `DETACH TABLE ... PERMANENTLY` may have committed `ALTER PUBLICATION ... DROP TABLE` (it runs in a `pqxx::nontransaction`). Restoring the original membership as is let the table resume from a slot that skipped its changes. The failure is now recovered like a failed nested drop: the reload marker is persisted and the table is reloaded from a new snapshot. The consumer stops tracking the table before the publication change, so a re-armed consumer never acknowledges WAL for it. New failpoint `materialized_postgresql_fail_after_publication_removal` and test `test_failed_publication_removal_reloads_table`. - The leaked-publication cleanup in `fetchRequiredTables` checked the absence of coordination state before the drop without fencing, so a concurrent create could register, win the election and create its live publication in between, and the late drop removed it. The cleanup now holds `/leader` (only its holder creates the publication), repeats the check under it, and fails the attempt for a retry if another replica holds `/leader`. New failpoint `materialized_postgresql_pause_before_leaked_publication_drop` and test `test_leaked_publication_cleanup_is_serialized_with_concurrent_create`. - Recovering a refused drop discards a stopped nested copy. An unchanged tree generation or another registered replica does not prove that another copy holds the data (overlapping recoveries, or replacements that have not fetched yet). The `snapshot_completed` marker is now removed before any stopped copy is discarded, which replaces the tree-generation records. The active worker notices a removed marker while its consumer runs, stops the consumer and redoes the snapshot right away, so replicas do not keep their tables hidden until the next failover. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pass update (head
|
…ish before the snapshot export, retry the temporary leader release - The drop of a leaked publication now runs in one PostgreSQL transaction: it locks the publication with `COMMENT ON PUBLICATION`, requires its object identifier to be the one seen before the coordination state was checked, and, while the lock is held, re-verifies with a fresh Keeper request that the temporary `/leader` is still held by this session and election term and that there is still no coordination state. A late drop after the session expired can no longer remove a publication that another replica recreated. - `addTableToReplication` adds the table to the publication before it exports the snapshot. PostgreSQL decides whether a change is published by the membership at the time of the change, so a delete made while the snapshot was loading was never sent and the row stayed in ClickHouse. This affects both `ATTACH TABLE` and the recovery of a refused `DETACH TABLE ... PERMANENTLY`. - An unconfirmed removal of the temporary `/leader` of the leaked-publication cleanup is handed over to `LeakedLeaderNodeReleaser` with its election identity, like at `shutdown`, so a replica stopped before its next election does not keep its peers on standby. New tests: `test_leaked_publication_cleanup_is_fenced_against_leadership_loss`, `test_unconfirmed_temporary_leader_release_is_retried`, `test_attach_table_keeps_changes_made_while_loading_snapshot` (new failpoints `materialized_postgresql_fail_temporary_leader_release` and `materialized_postgresql_pause_in_load_from_snapshot`). All three fail without the fixes and pass with them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…down completed `StorageMaterializedPostgreSQL::dropInnerTableIfAny` resets the replication handler after it drops the nested table, but `DatabaseAtomic::dropTable` removes the outer table metadata only afterwards. If that fails, the wrapper stays mounted with a null handler, and a retried `DROP TABLE` dereferenced it. A null handler means the inner teardown is complete, so return early. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…after recreating a missing publication Two review findings on coordinated `MaterializedPostgreSQL`: - Removing `snapshot_completed` before discarding a stopped nested copy did not fence the gap until the replacement exists: the active worker could redo the snapshot and publish a new marker in between, the other replica could then be dropped (non-last, because the recovering replica stays registered), and the recovering replica would drop the last data copy and resume from the new marker into an empty table. The recovering replica now records `<keeper_path>/nested_recreations/<replica>` (together with a version bump of the parent) before the marker is removed and the copy is dropped, and removes it only after every nested table exists again. While any record exists, no worker starts a snapshot reload, and `markInitialSnapshotCompleted` checks the parent version in the same multi-request that creates the marker. The record is removed when the replica unregisters and by the last-replica teardown. - A recreated publication cannot be consumed through the old slot: logical decoding resolves the publication in the historic catalog, so changes written while it was absent fail with `publication "..." does not exist` forever. `createPublicationIfNeeded` now removes the snapshot marker (fenced on the leader session) before recreating a missing coordinated publication, so `startSynchronization` reloads every table from a new slot. `test_single_table_publication_recreated_after_external_drop` now deletes a source row while the publication is absent and checks that it is reflected. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pass update (head
|
`pqxx::result` iteration yields `row_ref` by value, so bind it by value. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-replicated-tables Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tration `tryRemoveOwnReplicaRegistration` and the post-data teardown in `unregisterReplicaAndCheckLast` removed `nested_recreations/<replica>` and then the registration separately. If the second removal failed, the replica stayed registered without the fence, so peers could reload and publish a new snapshot, drop their copies, and a retry of this replica would resume into its empty replacement. Both nodes are now removed in one multi-request (`tryRemoveRegistrationWithPendingRecreation`). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pass update (head
|
…eplicated-tables Resolve the conflict in `InterpreterDropQuery.cpp`: keep the PR's `beforeDropDatabase` / `beforeTruncateDatabase` hooks and drop the incremental-refresh source check that master reverted.
… LSN `MaterializedPostgreSQLConsumer::isSyncAllowed` let a table in `waiting_list` fall through to the skip list while `current_lsn` was still below the table's snapshot LSN, and `addNested` clears its skip-list entries, so the change was applied. Since `ATTACH TABLE` now publishes the table before exporting the snapshot, the changes committed in between are both in the snapshot and in the stream. Replaying them is wrong: an update with an unchanged `TOAST` value of a row deleted before the export cannot find the previous row, and the table stops replicating. Reject such changes until the snapshot LSN is reached. Add the `materialized_postgresql_pause_before_snapshot_export` failpoint and a test that changes rows between the publication addition and the snapshot export. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… a tables list A non-coordinated `MaterializedPostgreSQL` database does not necessarily own its publication: with `materialized_postgresql_use_unique_replication_consumer_identifier` several databases have their own slots but share one publication. When a database's `materialized_postgresql_tables_list` differed from the publication, it dropped the publication and recreated it from its own list, removing the tables that other databases replicate through it. Instead, only add the listed tables missing from the publication (with their column lists) and leave the other members in place. Extend `test_explicit_tables_list_backup_with_shared_publication` to reattach the other database and check that the changes of the table attached to the first one still replicate. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `arm_tidy` builds failed with `modernize-use-nodiscard` on it: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110886&sha=c2b6ed5fc9ce561c93633f694567d50b6b5866c1&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #110886 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ts snapshot LSN `MaterializedPostgreSQLConsumer::isSyncAllowed` also gates the `Relation` message. Since a table in `waiting_list` is rejected until its snapshot LSN, the definition that arrived with a change made before the snapshot was dropped. `pgoutput` sends it once per decoding call, so a later change of the same batch had no buffer to decode into (`No data buffer`), and the waiting entry was already erased, so the retry applied the changes made before the snapshot. - A `Relation` message of a table that has a storage but is not allowed to synchronize yet is kept and processed when the first change of the table is allowed. - A `waiting_list` entry is no longer erased when the gate opens. It is erased when the slot is advanced past the snapshot LSN, so a batch that is read again is filtered the same way. - The gate compares the snapshot LSN with the final LSN of the transaction (from the `Begin` message) instead of the LSN of the individual change. The snapshot contains the transactions committed before its consistent point, and a transaction that was still running at that point has changes below it that are not in the snapshot. Add a test that makes changes both before and after the snapshot export while `ATTACH TABLE` is running, so they arrive in one batch. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…r plain `MaterializedPostgreSQL` too Both guards covered only the coordinated setups, but the problems do not depend on the nested engine: - `RENAME DATABASE` renames the nested tables, while the wrappers and the replication handler keep their IDs with the old database name, so reads fail until a restart. It is now rejected for every `MaterializedPostgreSQL` database and for a database that contains a standalone `MaterializedPostgreSQL` table. - `TRUNCATE ALL TABLES` of a database with a standalone table truncates its nested table while the slot and the publication stay at their positions, so the rows that do not change in PostgreSQL never come back. The preflight in `checkDatabaseTablesCanBeTruncated` now applies to the plain standalone table as well. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Pass update (head
|
|
📊 Cloud Performance Report ✅ AI verdict: This PR does not change performance on clickbench or tpch_adapted_1_official. Its changes cover MaterializedPostgreSQL replication and DDL handling, PostgreSQL connection helpers, and DROP/TRUNCATE DATABASE hooks. The only change on a general code path is a table-lookup check that applies only to MaterializedPostgreSQL databases, and the benchmark queries never reach it. Two queries were flagged. Q10 (+23.9%) stays suppressed because it falls inside master's normal range and has a noisy history, which matches the diff. Q28 (-6.0%) is a borderline result with conflicting signals and noisy measurements, so it remains inconclusive. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…H TABLE ... PERMANENTLY` `DatabaseMaterializedPostgreSQL::getFormattedTablesList` rebuilt `materialized_postgresql_tables_list` from the table names only, so a successful permanent detach of one table dropped the column subset (`table(col1, col2)`) of every remaining table. After a restart the full PostgreSQL structure no longer matched the nested table, the consumer left the table out, and its changes were acknowledged without being applied. The rewritten list now carries the column subsets of the original setting. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…rializedPostgreSQL` table `RENAME TABLE` and `EXCHANGE TABLES` across databases move only the wrapper, the `<uuid>_nested` table stays in the original database. This was refused for the coordinated single-table engine only. For the plain one, the nested table left behind was no longer protected by `checkDatabaseTablesCanBeTruncated`: `TRUNCATE ALL TABLES` of the original database did not see the wrapper and erased the snapshot while the replication slot stayed at its position. Co-Authored-By: Claude Fable 5.2 <[email protected]>
| /// table stays published but not materialized, which is a supported state (see `addTableToPublication`). | ||
| { | ||
| pqxx::nontransaction tx(replication_connection.getRef()); | ||
| addTableToPublication(tx, postgres_table_name); |
There was a problem hiding this comment.
[Blocker] Preserve the column subset when restoring a failed detach
The compensating addTableToReplication also runs for a table with a column subset, but this call re-adds it to the publication without that subset. For example, use materialized_postgresql_tables_list = 'a(key,val),b' with an additional source column in a, then refuse DETACH TABLE db.a PERMANENTLY after its publication removal (the existing materialized_postgresql_fail_after_publication_removal failpoint reaches this path).
readd_table_with_reload calls this method with clear_existing_data = true. The snapshot still uses getTableAllowedColumns, so the nested table contains only key,val, while the restored publication now emits all columns. The first subsequent Relation message reaches MaterializedPostgreSQLConsumer.cpp:1039–1043, marks a as skipped, and later commits keep advancing the slot without applying its changes. The recovery marker has already been removed after the re-add succeeded.
Pass getTableAllowedColumns(postgres_table_name) to addTableToPublication here, and cover a failed permanent detach of the projected table itself, including ongoing replication afterwards.
Closes: #47655
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
MaterializedPostgreSQLcan now create its nested tables asReplicatedReplacingMergeTree/SharedReplacingMergeTreefor high availability, using a new Keeper-based single-active-worker coordination of the replication slot. Controlled by the new settingsmaterialized_postgresql_table_engine,materialized_postgresql_keeper_pathandmaterialized_postgresql_replica_name.Documentation entry for user-facing changes
The three new settings and the coordinated-failover mechanism are documented in the embedded
Documentationblocks ofDatabaseMaterializedPostgreSQL.cppandStorageMaterializedPostgreSQL.cpp, from which the published engine pages are generated.Problem
The nested tables that
MaterializedPostgreSQLauto-creates were hardcoded to plainReplacingMergeTree(StorageMaterializedPostgreSQL.cpp), so the engine could not be made highly available (issue #47655). Simply allowingReplicatedReplacingMergeTreeis unsafe on its own: a PostgreSQL logical replication slot permits only one active consuming session, so two ClickHouse replicas consuming the same slot would race onpg_replication_slot_advanceand silently drop WAL.Solution
Allow the nested engine to be
ReplicatedReplacingMergeTree/SharedReplacingMergeTree, gated behind a new Keeper-based coordination that elects exactly one active worker — the same pattern used byS3Queue, the Keeper-coordinatedKafkaengine and refreshable materialized views:/leadernode undermaterialized_postgresql_keeper_pathand is the only replica that consumes the slot./leaderand resumes consuming from the slot'sconfirmed_flush_lsn— no reload, no duplication. PostgreSQL's own single-active-session rule on the slot is the ultimate backstop against double-advance during a handover. A graceful stop of the active worker (DETACH, a non-lastDROP, server shutdown) does not wait for that: it releases/leaderwith a confirmed removal - the node lives under the server's shared Keeper session, which outlives the database, and nothing re-enters the election on that replica after shutdown, so an unconfirmed (lost-response) removal is resolved on the spot with owner- and version-checked re-checks instead of leaving a stale node that would keep every peer on standby for as long as that session lives.snapshot_completedmarker in Keeper records that the initial snapshot loaded every table. A new leader may resume fromconfirmed_flush_lsnonly when the marker exists; otherwise the previous worker died mid-snapshot, and the new one clears the nested tables, drops the slot and redoes the snapshot from scratch, so pre-slot rows cannot be lost. Clearing first is required for correctness: a row the dead worker had copied and that PostgreSQL thenDELETEd has no counterpart in the new snapshot, so without a clear the stale copy would survive (aReplacingMergeTreecollapses duplicate keys by_versionbut never turns a now-absent row into a tombstone). The marker is fenced on the live leadership session: it is written through the Keeper session that backs/leader(in a multi-request with a check on/leader), the snapshot load aborts as soon as that session is lost, and a consumer is never started over a dead leadership session - so a worker deposed mid-snapshot can never mask its successor's replacement snapshot with a stale marker. The redo of the snapshot is fenced the same way: a worker whose leadership session is no longer alive aborts before truncating the nested tables (re-checked per table) and before dropping or recreating the shared slot, so a deposed worker cannot wipe the tables its successor has already reloaded or discard the slot the successor just created. A startup attempt that fails before a consumer got running (most importantly, a coordinated single-table engine whose one snapshot load failed) aborts instead of starting a consumer with nothing to apply - which would advance the shared slot'sconfirmed_flush_lsnwhile applying no rows - and releases the leadership so a healthy peer can take over. That release never leaves a stale leadership claim behind: aremoveof/leaderthat could not be confirmed does not prove the node survived, so the claim is dropped in either case, and a leader node this replica created under the current Keeper session but no longer tracks is recognized (by its stored replica name and its owning session) and removed on its next election attempt - a replica never keeps acting as the active worker, or touches the shared slot and snapshot state, without provably holding/leader.CREATE DATABASEadopts an existing publication instead of dropping it from under the active worker.<keeper_path>/replicas; dropping the database on one replica keeps the shared slot/publication for the others, and only dropping the last replica removes them from PostgreSQL (fail-close when Keeper is unavailable). The last-replica decision is fenced on the sharedreplicasnode so concurrentDROP DATABASEon different replicas cannot both act as last, it removes the replica's registration only atomically with winning that fence - a replica that is not the last one keeps its registration until its local nested tables are actually gone, so even a server killed mid-drop stays visible to every later last-replica check - and it runs even for aDROP DATABASEissued immediately after a restart, before the background startup task has rebuilt the replication handler.DROP DATABASE), the snapshot insert is never silently deduplicated against block hashes surviving from a previous incarnation of the shared table, a publication leaked by an incompletely dropped setup (no surviving coordination state in Keeper) is dropped by a freshCREATEinstead of silently adopted with its stale table set, and a refused (failed) drop never leaves the replica silently dead: every refusable Keeper step of the pre-data teardown runs before the replica's consumer is stopped, and if the drop still fails after that point - the last replica's removal of the shared coordination nodes, or the deletion of this replica's own local nested tables (e.g. Keeper disappearing while a nested replicated table removes its own Keeper metadata) - replication is rebuilt in the background - for the database engine through a new genericIDatabase::onDropDatabaseFailedhook that discards the stopped handler and re-runs the startup task, for the single-table engine by re-arming the handler's retrying startup path - so the replica rejoins the setup once Keeper is reachable again.materialized_postgresql_table_engine,materialized_postgresql_schema,materialized_postgresql_schema_list,materialized_postgresql_tables_list_with_schema) and must replicate the same PostgreSQL source — the same source database and, for the single-table engine, the same source table (so a single-table engine and a database engine can never share one keeper path): these determine how the ClickHouse names of the shared nested tables and the names of the shared slot and publication are derived. The first replica publishes a canonical fingerprint of them at<keeper_path>/naming; a disagreeing replica is rejected — synchronously atCREATEtime when the setup already exists in Keeper, and fail-close at startup before it registers itself — instead of adopting the same publication yet building a disjoint replicated tree that never receives the other replicas' data.<keeper_path>/table_set, and a replica whose derived set differs is refused fail-close (the shared publication - from which joining replicas later derive their set - is only created by the elected active worker, so without this fence two fresh replicas starting concurrently could silently build diverging nested tables on one keeper path). The refusal converges by itself once the publication exists, because joining replicas then derive their set from the publication, which was created from the fenced set.<keeper_path>/teardown, which is removed only after the shared PostgreSQL slot/publication have actually been dropped. While the token exists, a fresh coordinatedCREATEon the same keeper path is rejected (synchronously by validation and fail-close at startup), so the pending by-name drops can never delete a new setup's freshly created slot/publication. A replica recovering its own refused drop reclaims its own token, and a retried drop resumes its earlier teardown instead of leaking the slot.NOT_IMPLEMENTED) in coordinated mode:ATTACH TABLE/DETACH TABLE PERMANENTLY/DROP TABLE/RENAME TABLE/EXCHANGE TABLES, and a database-wideTRUNCATE DATABASE/TRUNCATE ALL TABLES FROM. Each would only change the local replica (or wipe its copy of the shared replicated data) while the shared publication, tables list, slot/snapshot marker and peer replicas keep the old state, silently diverging the replicas. Recreate the database with an updatedmaterialized_postgresql_tables_listinstead.New settings (both the database engine and the single-table engine):
materialized_postgresql_table_engineReplacingMergeTreeReplacingMergeTree/ReplicatedReplacingMergeTree/SharedReplacingMergeTreematerialized_postgresql_keeper_path{shard}macro; a per-replica/per-server macro ({replica}/{server_uuid}, including reached through a config macro) is rejected atCREATEtime, and so is{uuid}unless the DDL carries the UUID (ON CLUSTER, a table inside aReplicateddatabase, or an explicitUUID '...'clause) so that it is provably identical on every replica, and so is a misspelled/unsupported macro (in this path or inmaterialized_postgresql_replica_name) — both settings are macro-expanded during validation exactly as the handler expands them latermaterialized_postgresql_replica_name{replica}/replicas/<name>registration node stores the owning replica's identity, and a name already registered by another replica is rejected (synchronously atCREATEtime when the registration is already visible); it must also resolve to a single Keeper node name (empty or containing/is rejected, since a nested path under/replicaswould break the last-replica bookkeeping); together withmaterialized_postgresql_keeper_pathit forms the coordination identity of the replica, which is treated as immutable once the setup exists: a configuration-only change of a macro these settings expand through is refused at startup, while aDROPtears down the identity persisted in the nested tables; a name change made in the one window where the registration already exists while no nested table does yet is recovered from the registration itself, which stores an owner identity no macro feeds into, so the stale registration is removed (on startup and on drop) instead of keeping<keeper_path>/replicasnon-empty forever and stopping every future drop from becoming the last-replica dropThe replicated/shared engines require
materialized_postgresql_keeper_pathand vice versa (coordination with a plainReplacingMergeTreewould leave the standbys without data), and coordination is mutually exclusive withmaterialized_postgresql_use_unique_replication_consumer_identifier(which gives each replica its own slot). Coordination also requires Keeper/ZooKeeper to be configured on the server: a coordinatedCREATE DATABASEon a server with no Keeper is rejected synchronously atCREATEtime rather than being accepted and left retrying in the background. All of this validation also applies to a userATTACH DATABASE/ATTACH TABLEthat spells out the full definition - it is fresh user input, exactly like aCREATE; only replaying an already-persisted definition (server startup, and the shortATTACHsyntax, which re-reads the stored definition) is exempt. Behaviour is unchanged when coordination is not configured.Testing
test_postgresql_replica_database_engine/test_coordination.py: convergence + single leader, leader failover with no data loss/duplication, rejoin, takeover before snapshot completion redoes the snapshot without losing pre-slot rows, a mid-snapshot takeover after a row is deleted in PostgreSQL drops the stale copy (test_takeover_after_partial_snapshot_drops_stale_deleted_rows), a secondCREATEadopts the publication,ATTACH/DETACH/DROP/RENAME/EXCHANGE/TRUNCATErejection, shared slot/publication kept until the last replica is dropped, aDROP DATABASEimmediately after restart still unregisters the replica (test_drop_immediately_after_restart_unregisters_replica), concurrentDROP DATABASEon both replicas tears down the shared state exactly once (test_concurrent_drop_on_both_replicas_removes_shared_state), a per-server keeper path macro is rejected (test_keeper_path_rejects_per_server_macro), a plain coordinatedCREATEwith{uuid}in the keeper path is rejected while an explicitUUID '...'clause makes it acceptable (test_keeper_path_rejects_uuid_macro_for_a_plain_create), a leaked publication is replaced instead of adopted (test_leaked_publication_is_not_adopted_by_fresh_coordinated_create), a refused drop in the restart window keeps the startup alive (test_refused_drop_in_restart_window_does_not_disable_startup), a drop refused (via a failpoint) after the replication handler was already stopped recovers without a server restart for both the database and the single-table engine (test_refused_drop_after_handler_shutdown_recovers_database,test_refused_drop_after_handler_shutdown_recovers_single_table_engine), a drop refused because the local nested-table deletion itself fails likewise recovers for both engines (test_refused_drop_when_nested_table_drop_fails_recovers_database,test_refused_drop_when_nested_table_drop_fails_recovers_single_table_engine), coordinatedCREATErejected without Keeper configured (test_coordination_requires_keeper_configured), a joining replica with different naming-affecting settings is rejected atCREATEwhile identical settings converge (test_join_with_different_naming_settings_is_rejected), a coordinated single-table engine cannot join a database engine's keeper path because the fenced identity includes the PostgreSQL source (test_single_table_engine_cannot_join_database_engine_keeper_path), a bad macro in the keeper path or the replica name fails theCREATEsynchronously (test_bad_macro_in_coordination_settings_is_rejected_at_create), a replica name that is not a single Keeper path component (empty, or containing/) is rejected while a plain name on the same keeper path is accepted (test_replica_name_must_be_a_single_keeper_component), a duplicatematerialized_postgresql_replica_nameis rejected without disturbing the registered replica (test_duplicate_replica_name_is_rejected), a joining replica whose derived table set differs from the fenced one is refused before building any nested table (test_join_with_different_table_set_is_rejected), a freshCREATEon a keeper path whose teardown is still pending is rejected and succeeds once the teardown token is released (test_create_is_rejected_while_teardown_token_is_held), the three coordination settings rejected byALTER DATABASE ... MODIFY SETTINGwith an actionable CREATE-time-only message (test_coordination_settings_cannot_be_altered), public DDL on a plain database in the startup window (before the background task has built the replication handler) does not touch a null handler and aDROP DATABASEin that window still removes the PostgreSQL publication and replication slot (test_plain_database_ddl_and_drop_in_startup_window), a plainDROP DATABASEquiesces the retrying background startup task so a retry waking mid-drop cannot recreate the publication/slot while the drop is in flight (test_plain_drop_database_quiesces_retrying_startup_task), a refused plain drop re-arms the startup task instead of leaving the database mounted but dead (test_plain_refused_drop_rearms_startup_task), anALTERof a mutable setting on a coordinated standby is accepted before its consumer exists and survives a failover (test_alter_mutable_setting_on_standby_survives_failover), the sameALTERis accepted on a former leader demoted back to standby and applied on its next takeover (test_alter_mutable_setting_on_demoted_leader), a registration racing the very start of a last-replica teardown is refused by the atomic teardown-token fence (test_registration_is_fenced_against_concurrent_teardown_token), a joiner that adopted the shared publication's table set over its own mismatchingmaterialized_postgresql_tables_listrecreates a missing publication from the adopted set rather than its stale local list (test_adopted_table_set_survives_publication_recreation), that adopted set also survives a restart of the joiner, so a replica restarted while the publication is missing recreates it from the table set fenced in Keeper instead of its stale local list (test_adopted_table_set_survives_restart_and_publication_recreation), a coordination identity changed by a configuration-only macro change is refused at startup - with nothing registered under the new identity - and the setup resumes once the configuration is restored (test_coordination_identity_must_stay_stable_across_restart), aDROPafter such a change (with the macro's value changed, or the macro removed entirely) tears down the original coordination identity persisted in the nested tables for both engines (test_drop_after_coordination_identity_change_tears_down_original_identity,test_single_table_drop_after_coordination_identity_change_tears_down_original_identity), a worker whose Keeper session expires while it is loading the initial snapshot aborts without publishing thesnapshot_completedmarker or starting a consumer while its successor redoes the snapshot (test_lost_leadership_during_snapshot_does_not_publish_stale_marker), a worker deposed right after entering the redo-the-snapshot recovery branch aborts at the leadership fence without truncating the tables its successor reloaded or dropping the successor's slot (test_deposed_worker_aborts_redo_snapshot_before_touching_shared_state), a coordinated single-table engine recreates an externally dropped publication idempotently - with the correctly quoted table name - and resumes replicating (test_single_table_publication_recreated_after_external_drop), a coordinated worker whose snapshot load keeps failing aborts each attempt before a consumer exists and releases the leadership, so a healthy peer completes the full snapshot and no WAL is discarded, for both the single-table and the database engine (test_failed_single_table_snapshot_releases_leadership,test_failed_database_snapshot_releases_leadership), a coordinatedDETACH TABLE ... PERMANENTLY/DROP TABLEissued in the attach/restart window (before the background startup has published the table wrappers) is refused as a true no-op that leaves the nested table consuming (test_coordinated_detach_in_startup_window_is_a_no_op_rejection), a read in the recovery window of a refusedDROP DATABASEstill hides PostgreSQL-deleted row versions instead of falling back to the raw nested tables (test_refused_drop_recovery_window_keeps_wrapped_reads), a stale registration left behind by a replica whose coordination name changed before it owned any nested table is purged so the last-replica teardown still removes the shared slot and publication (test_stale_registration_of_a_renamed_replica_is_purged), a server hard-killed in the middle of a non-lastDROP DATABASEstays registered in Keeper (the last-replica decision is one atomic operation), so a peer's drop keeps the shared state around the killed replica's surviving data and the restarted replica resumes replicating before a retried drop tears everything down (test_hard_stop_during_non_last_teardown_keeps_replica_registered), a graceful stop of the active worker whose fenced/leaderremoval fails (via a failpoint) still frees/leaderthrough the confirmed-release re-check, so the peer takes over promptly while the stopped replica's server and Keeper session keep running (test_graceful_stop_releases_leader_even_when_removal_fails), a userATTACH DATABASE/ATTACH TABLEwith a full definition goes through the coordination validator like aCREATE(test_full_attach_database_definition_is_validated,test_full_attach_table_definition_is_validated) and needs the experimental opt-in like aCREATE(test_full_attach_database_definition_requires_experimental_setting,test_full_attach_table_definition_requires_experimental_setting), and the other negative validation cases.test_plain_single_table_engine_refused_drop_recoverstotest_postgresql_replica_database_engine/test_3.py: the plain (non-coordinated) single-table engine now drops its local nested table before the authoritative PostgreSQL teardown, so a refused (thrown) nested-table drop keeps the replication slot/publication and re-arms the handler to resume from the existing slot, instead of leaving the table mounted but dead with the PostgreSQL objects already removed.test_rename_and_exchange_table_are_rejected,test_database_wide_truncate_is_rejectedandtest_drop_of_individual_table_is_rejectedtotest_postgresql_replica_database_engine/test_1.py:RENAME TABLE/EXCHANGE TABLES, a database-wideTRUNCATE, and aDROP/TRUNCATEof an individual table are now also rejected for a plain (non-coordinated)MaterializedPostgreSQLdatabase, which previously fell through to the genericAtomicDDL and silently diverged the local tables from the replication state (a dropped table stayed inmaterialized_postgresql_tables_listand in the publication, so the consumer marked it skipped while the slot kept advancing);DETACH TABLE ... PERMANENTLYremains the supported removal path.test_count_does_not_include_deleted_rowstotest_postgresql_replica_database_engine/test_1.py:SELECT count()reads the cheapest column of the nested table - the one-byte_signcolumn itself - and the wrapped read used to skip its_sign = 1filter whenever the sign column was among the requested columns, so a count included the durable tombstones a PostgreSQLDELETEleaves in the nestedReplacingMergeTreetable and disagreed withSELECT *. The filter is now applied unconditionally (an explicit read of_signis filtered the same way).test_failed_attach_rolls_back_setting_and_tabletotest_postgresql_replica_database_engine/test_2.py: a failedATTACH TABLEnow rolls back the already persistedmaterialized_postgresql_tables_listextension and the published table wrapper together with the nested table, so the database does not keep claiming a table is attached that never joined the publication; a retry starts from a clean state.test_failed_attach_with_failed_cleanup_keeps_table_attachedtotest_postgresql_replica_database_engine/test_2.py: when the cleanup of a failedATTACH TABLEcannot drop the nested table it created either, the attach deliberately stays visible instead of leaving an invisible leftover that every retry would collide with, andDETACH TABLE ... PERMANENTLYfollowed by a retriedATTACH TABLErecovers it.test_attached_table_can_be_detached_permanentlytotest_postgresql_replica_database_engine/test_2.py: a table added byATTACH TABLEgets a freshly built wrapper that never went through the database's replication startup, so it has to be marked as belonging to an already started database - otherwise the startup-window guard refuses every laterDETACH TABLE ... PERMANENTLYof it and the supported attach/detach round trip is broken.test_failed_detach_rolls_back_and_table_keeps_replicatingtotest_postgresql_replica_database_engine/test_1.py: aDETACH TABLE ... PERMANENTLYwhose local nested-table drop throws is now rolled back completely - the table is re-added to replication through a fresh snapshot and the persistedmaterialized_postgresql_tables_listis restored - so the table keeps replicating and theDETACHcan simply be retried, instead of stranding a live nested table outside the logical database.test_detach_database_and_reattachtotest_postgresql_replica_database_engine/test_1.py:DETACH DATABASEused to fail half-way (the generic detach path had already stopped replication when the per-table walk hit the unconditionalDETACH TABLE not allowedguard), leaving the database mounted but no longer replicating. The internal walk is now let through, soDETACH DATABASEunmounts the database cleanly andATTACH DATABASEresumes replication, catching up on changes made while it was detached.test_detach_permanently_of_last_table_is_rejectedtotest_postgresql_replica_database_engine/test_1.py: detaching the last replicated table would persist an emptymaterialized_postgresql_tables_list, and an empty list does not mean "replicate no tables" - the table set would be re-derived from the current PostgreSQL schema on the next startup, so the detach would not stick. It is now refused up front, leaving the table replicating.test_plain_refused_drop_does_not_resurrect_deleted_rowstotest_postgresql_replica_database_engine/test_coordination.py: a refused plainDROP DATABASEthat had already removed one of the nested tables recovers as a create-style startup, and that startup now clears the nested tables that survived the partial drop before reloading the snapshot. Otherwise the reloaded snapshot was appended to the survivor's pre-drop contents, so rows deleted in PostgreSQL during the replication outage stayed visible forever (they produce no_sign = -1tombstone, and aReplacingMergeTreehas nothing to override a key that is absent from the new snapshot). The test deletes the upper half of both tables in PostgreSQL inside the outage and asserts both tables converge to the exact current PostgreSQL state; without the fix the surviving table keeps 50 rows instead of 25.test_plain_refused_drop_with_user_managed_slot_refuses_to_resumetotest_postgresql_replica_database_engine/test_coordination.py: the create-style recovery of a partially completed refusedDROP DATABASEis impossible for a user-managedmaterialized_postgresql_replication_slot- ClickHouse must not drop and recreate that slot, so no fresh snapshot can be exported, and thematerialized_postgresql_snapshottoken of the original slot creation is only valid while the exporting PostgreSQL transaction is open. The recovery now fails close there instead: the table that survived the partial drop is left untouched and replication is not resumed (resuming would silently skip the removed table while the slot advances past its changes), with an actionable message telling the operator to recreate the database with a freshly created slot and the snapshot exported with it.test_plain_refused_drop_recovery_survives_a_restarttotest_postgresql_replica_database_engine/test_coordination.py: the recovery mode chosen after a refusedDROP DATABASEthat had already removed some nested tables (create-style resnapshot, or fail-close for a user-managed replication slot) used to live in the database object only, so a server restart before the re-armed startup finished rebuilt the database from its metadata as an ordinary attach and the steady-state startup then looked for the removed nested table and retried forever. The decision is now recorded as a.partial_drop_recoverymarker in the database metadata directory and re-applied on every startup until one completes. The test restarts the server inside the recovery window and asserts both tables converge to the current PostgreSQL state; ignoring the marker on startup makes it fail withTabletest_database.first_tablewas not created within 120 seconds.test_coordinated_schema_drift_aborts_startup_instead_of_skippingtotest_postgresql_replica_database_engine/test_coordination.py: a table whose PostgreSQL structure drifted while the replicas were down used to be skipped from replication in coordinated mode too, so the consumer ran with a part of the table set while still confirming the shared replication slot - the changes of the skipped table were acknowledged in PostgreSQL and lost, and the usualDETACH/ATTACHrepair is rejected in coordinated mode. Starting replication is now aborted as a whole and the replication leadership released, so a peer can try. The test adds a column to one of two replicated tables with both replicas stopped, asserts the leadership is released and that no table is marked as skipped, and that both tables converge again after the schema is reconciled; without the fix the leadership is never released.clickhouse-servernodes +clickhouse-keeper+ PostgreSQL (wal_level=logical): coordinatedCREATE DATABASEbuilds theReplicatedReplacingMergeTreenested tables with correctly macro-expanded per-table Keeper paths; snapshot + ongoing INSERT/UPDATE are consumed by the single leader; a standby serves the same data via ClickHouse replication; killing the leader triggers takeover (~8s) that resumes consumption with matching row/key counts (no loss, no duplication); and a restarted node rejoins as a standby without stealing leadership.Note:
SharedReplacingMergeTreeis only available in ClickHouse Cloud; open-source runs are covered withReplicatedReplacingMergeTree.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/110886]