Skip to content

MaterializedPostgreSQL: coordinated Replicated/Shared nested tables for HA - #110886

Open
alexey-milovidov wants to merge 214 commits into
masterfrom
matpg-coordinated-replicated-tables
Open

alexey-milovidov wants to merge 214 commits into
masterfrom
matpg-coordinated-replicated-tables

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

Closes: #47655

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

MaterializedPostgreSQL can now create its nested tables as ReplicatedReplacingMergeTree/SharedReplacingMergeTree for high availability, using a new Keeper-based single-active-worker coordination of the replication slot. Controlled by the new settings materialized_postgresql_table_engine, materialized_postgresql_keeper_path and materialized_postgresql_replica_name.

Documentation entry for user-facing changes

The three new settings and the coordinated-failover mechanism are documented in the embedded Documentation blocks of DatabaseMaterializedPostgreSQL.cpp and StorageMaterializedPostgreSQL.cpp, from which the published engine pages are generated.


Problem

The nested tables that MaterializedPostgreSQL auto-creates were hardcoded to plain ReplacingMergeTree (StorageMaterializedPostgreSQL.cpp), so the engine could not be made highly available (issue #47655). Simply allowing ReplicatedReplacingMergeTree is 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 on pg_replication_slot_advance and 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 by S3Queue, the Keeper-coordinated Kafka engine and refreshable materialized views:

  • The active worker holds an ephemeral /leader node under materialized_postgresql_keeper_path and is the only replica that consumes the slot.
  • Standby replicas create the nested tables as replicas of the same replicated tree and receive data (including the initial snapshot) through ClickHouse replication, without touching the slot.
  • When the active worker's Keeper session ends, a standby wins /leader and resumes consuming from the slot's confirmed_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-last DROP, server shutdown) does not wait for that: it releases /leader with 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.
  • The slot and the publication are shared state, and the whole lifecycle honors that:
    • A durable snapshot_completed marker in Keeper records that the initial snapshot loaded every table. A new leader may resume from confirmed_flush_lsn only 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 then DELETEd has no counterpart in the new snapshot, so without a clear the stale copy would survive (a ReplacingMergeTree collapses duplicate keys by _version but 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's confirmed_flush_lsn while applying no rows - and releases the leadership so a healthy peer can take over. That release never leaves a stale leadership claim behind: a remove of /leader that 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.
    • A second coordinated CREATE DATABASE adopts an existing publication instead of dropping it from under the active worker.
    • Every replica registers itself under <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 shared replicas node so concurrent DROP DATABASE on 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 a DROP DATABASE issued immediately after a restart, before the background startup task has rebuilt the replication handler.
    • Recreating a coordinated database right after dropping it is safe: the nested tables are dropped without the delayed-drop window (so their shared Keeper subtrees do not outlive the 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 fresh CREATE instead 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 generic IDatabase::onDropDatabaseFailed hook 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.
    • All replicas of one coordinated setup must agree on the naming-affecting settings (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 at CREATE time 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.
    • The shared table set is fenced the same way, before any nested table is built: the first replica publishes its derived set at <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.
    • The last-replica teardown is generation-safe: winning the last-replica fence atomically (in one Keeper multi-request) creates an ownership token at <keeper_path>/teardown, which is removed only after the shared PostgreSQL slot/publication have actually been dropped. While the token exists, a fresh coordinated CREATE on 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.
    • Per-table and database-wide destructive changes are refused (NOT_IMPLEMENTED) in coordinated mode: ATTACH TABLE / DETACH TABLE PERMANENTLY / DROP TABLE / RENAME TABLE / EXCHANGE TABLES, and a database-wide TRUNCATE 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 updated materialized_postgresql_tables_list instead.

New settings (both the database engine and the single-table engine):

Setting Default Purpose
materialized_postgresql_table_engine ReplacingMergeTree ReplacingMergeTree / ReplicatedReplacingMergeTree / SharedReplacingMergeTree
materialized_postgresql_keeper_path (empty) opt-in gate that enables coordination; supports the {shard} macro; a per-replica/per-server macro ({replica}/{server_uuid}, including reached through a config macro) is rejected at CREATE time, and so is {uuid} unless the DDL carries the UUID (ON CLUSTER, a table inside a Replicated database, or an explicit UUID '...' clause) so that it is provably identical on every replica, and so is a misspelled/unsupported macro (in this path or in materialized_postgresql_replica_name) — both settings are macro-expanded during validation exactly as the handler expands them later
materialized_postgresql_replica_name {replica} replica identity for coordination and the nested replicated engine; must resolve to a distinct value on every replica, which is enforced: the /replicas/<name> registration node stores the owning replica's identity, and a name already registered by another replica is rejected (synchronously at CREATE time 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 /replicas would break the last-replica bookkeeping); together with materialized_postgresql_keeper_path it 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 a DROP tears 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>/replicas non-empty forever and stopping every future drop from becoming the last-replica drop

The replicated/shared engines require materialized_postgresql_keeper_path and vice versa (coordination with a plain ReplacingMergeTree would leave the standbys without data), and coordination is mutually exclusive with materialized_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 coordinated CREATE DATABASE on a server with no Keeper is rejected synchronously at CREATE time rather than being accepted and left retrying in the background. All of this validation also applies to a user ATTACH DATABASE / ATTACH TABLE that spells out the full definition - it is fresh user input, exactly like a CREATE; only replaying an already-persisted definition (server startup, and the short ATTACH syntax, which re-reads the stored definition) is exempt. Behaviour is unchanged when coordination is not configured.

Testing

  • Added integration test 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 second CREATE adopts the publication, ATTACH/DETACH/DROP/RENAME/EXCHANGE/TRUNCATE rejection, shared slot/publication kept until the last replica is dropped, a DROP DATABASE immediately after restart still unregisters the replica (test_drop_immediately_after_restart_unregisters_replica), concurrent DROP DATABASE on 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 coordinated CREATE with {uuid} in the keeper path is rejected while an explicit UUID '...' 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), coordinated CREATE rejected without Keeper configured (test_coordination_requires_keeper_configured), a joining replica with different naming-affecting settings is rejected at CREATE while 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 the CREATE synchronously (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 duplicate materialized_postgresql_replica_name is 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 fresh CREATE on 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 by ALTER DATABASE ... MODIFY SETTING with 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 a DROP DATABASE in that window still removes the PostgreSQL publication and replication slot (test_plain_database_ddl_and_drop_in_startup_window), a plain DROP DATABASE quiesces 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), an ALTER of 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 same ALTER is 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 mismatching materialized_postgresql_tables_list recreates 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), a DROP after 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 the snapshot_completed marker 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 coordinated DETACH TABLE ... PERMANENTLY / DROP TABLE issued 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 refused DROP DATABASE still 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-last DROP DATABASE stays 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 /leader removal fails (via a failpoint) still frees /leader through 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 user ATTACH DATABASE / ATTACH TABLE with a full definition goes through the coordination validator like a CREATE (test_full_attach_database_definition_is_validated, test_full_attach_table_definition_is_validated) and needs the experimental opt-in like a CREATE (test_full_attach_database_definition_requires_experimental_setting, test_full_attach_table_definition_requires_experimental_setting), and the other negative validation cases.
  • Added test_plain_single_table_engine_refused_drop_recovers to test_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.
  • Added test_rename_and_exchange_table_are_rejected, test_database_wide_truncate_is_rejected and test_drop_of_individual_table_is_rejected to test_postgresql_replica_database_engine/test_1.py: RENAME TABLE / EXCHANGE TABLES, a database-wide TRUNCATE, and a DROP / TRUNCATE of an individual table are now also rejected for a plain (non-coordinated) MaterializedPostgreSQL database, which previously fell through to the generic Atomic DDL and silently diverged the local tables from the replication state (a dropped table stayed in materialized_postgresql_tables_list and in the publication, so the consumer marked it skipped while the slot kept advancing); DETACH TABLE ... PERMANENTLY remains the supported removal path.
  • Added test_count_does_not_include_deleted_rows to test_postgresql_replica_database_engine/test_1.py: SELECT count() reads the cheapest column of the nested table - the one-byte _sign column itself - and the wrapped read used to skip its _sign = 1 filter whenever the sign column was among the requested columns, so a count included the durable tombstones a PostgreSQL DELETE leaves in the nested ReplacingMergeTree table and disagreed with SELECT *. The filter is now applied unconditionally (an explicit read of _sign is filtered the same way).
  • Added test_failed_attach_rolls_back_setting_and_table to test_postgresql_replica_database_engine/test_2.py: a failed ATTACH TABLE now rolls back the already persisted materialized_postgresql_tables_list extension 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.
  • Added test_failed_attach_with_failed_cleanup_keeps_table_attached to test_postgresql_replica_database_engine/test_2.py: when the cleanup of a failed ATTACH TABLE cannot drop the nested table it created either, the attach deliberately stays visible instead of leaving an invisible leftover that every retry would collide with, and DETACH TABLE ... PERMANENTLY followed by a retried ATTACH TABLE recovers it.
  • Added test_attached_table_can_be_detached_permanently to test_postgresql_replica_database_engine/test_2.py: a table added by ATTACH TABLE gets 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 later DETACH TABLE ... PERMANENTLY of it and the supported attach/detach round trip is broken.
  • Added test_failed_detach_rolls_back_and_table_keeps_replicating to test_postgresql_replica_database_engine/test_1.py: a DETACH TABLE ... PERMANENTLY whose local nested-table drop throws is now rolled back completely - the table is re-added to replication through a fresh snapshot and the persisted materialized_postgresql_tables_list is restored - so the table keeps replicating and the DETACH can simply be retried, instead of stranding a live nested table outside the logical database.
  • Added test_detach_database_and_reattach to test_postgresql_replica_database_engine/test_1.py: DETACH DATABASE used to fail half-way (the generic detach path had already stopped replication when the per-table walk hit the unconditional DETACH TABLE not allowed guard), leaving the database mounted but no longer replicating. The internal walk is now let through, so DETACH DATABASE unmounts the database cleanly and ATTACH DATABASE resumes replication, catching up on changes made while it was detached.
  • Added test_detach_permanently_of_last_table_is_rejected to test_postgresql_replica_database_engine/test_1.py: detaching the last replicated table would persist an empty materialized_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.
  • Added test_plain_refused_drop_does_not_resurrect_deleted_rows to test_postgresql_replica_database_engine/test_coordination.py: a refused plain DROP DATABASE that 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 = -1 tombstone, and a ReplacingMergeTree has 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.
  • Added test_plain_refused_drop_with_user_managed_slot_refuses_to_resume to test_postgresql_replica_database_engine/test_coordination.py: the create-style recovery of a partially completed refused DROP DATABASE is impossible for a user-managed materialized_postgresql_replication_slot - ClickHouse must not drop and recreate that slot, so no fresh snapshot can be exported, and the materialized_postgresql_snapshot token 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.
  • Added test_plain_refused_drop_recovery_survives_a_restart to test_postgresql_replica_database_engine/test_coordination.py: the recovery mode chosen after a refused DROP DATABASE that 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_recovery marker 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 with Table test_database.first_table was not created within 120 seconds.
  • Added test_coordinated_schema_drift_aborts_startup_instead_of_skipping to test_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 usual DETACH/ATTACH repair 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.
  • Verified end-to-end against a locally built binary with two real clickhouse-server nodes + clickhouse-keeper + PostgreSQL (wal_level=logical): coordinated CREATE DATABASE builds the ReplicatedReplacingMergeTree nested 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: SharedReplacingMergeTree is only available in ClickHouse Cloud; open-source runs are covered with ReplicatedReplacingMergeTree.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/110886]

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

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d6614f9]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR adds Keeper-coordinated, single-active-worker replication for MaterializedPostgreSQL with replicated/shared nested tables, plus extensive lifecycle recovery. The current head still has correctness gaps: one new failed-detach regression and six previously discussed, deliberately deferred findings. Block pending the correctness fixes below; the deferred findings are retained here without repeating their inline discussions.

Findings

❌ Blockers

  • src/Storages/PostgreSQL/PostgreSQLReplicationHandler.cpp:5318 — Failed-detach recovery loses the detached table's column projection. With source a(key,val,extra) and materialized_postgresql_tables_list = 'a(key,val),b', a permanent detach refused after publication removal invokes the compensating reload. This call republishes all columns, while its snapshot and nested schema still contain only key,val. The next Relation makes the consumer skip a, yet it continues acknowledging WAL. Pass getTableAllowedColumns(postgres_table_name) to addTableToPublication and test subsequent replication after the refused detach.

  • src/Storages/PostgreSQL/PostgreSQLReplicationHandler.cpp:2397 — Takeover can permanently corrupt unchanged TOAST values. A promoted replica starts consuming before fetching its predecessor's acknowledged writes. An update retaining a TOAST value can copy an older local value into a newer _version; fetching the correct older-version part later cannot repair it. Establish the required data dependency before replay, or remove the consumer's dependence on stale local rows. [dismissed by author -- https://github.com/MaterializedPostgreSQL: coordinated Replicated/Shared nested tables for HA #110886#discussion_r4264875694] The availability tradeoff remains a permanent wrong-result case.

  • src/Storages/PostgreSQL/PostgreSQLReplicationHandler.cpp:1857 — In-flight inserts are not fenced on leadership. A snapshot pipeline can resume after its session expires and insert an old row after the successor has truncated and loaded a snapshot without that deleted row, resurrecting it permanently. A liveness check before the pipeline and rejection of its later completion marker cannot undo these writes. Fence part commits or establish successor-side quiescence before rebuilding. [dismissed by author -- https://github.com/MaterializedPostgreSQL: coordinated Replicated/Shared nested tables for HA #110886#discussion_r4271642342] The required infrastructure is still absent; in-flight WAL inserts have the same missing commit fence.

  • src/Storages/PostgreSQL/PostgreSQLReplicationHandler.cpp:252 — ZooKeeper cleanup can delete another election's leader. Without CHECK_STAT, a queued release still reads the old node and later removes by version alone. Another server can tear down and recreate the setup between those operations; the new node also has version zero. Removing it permits concurrent active workers. Require an atomic election-term fence or refuse this coordination mode on unsupported servers. [dismissed by author -- https://github.com/MaterializedPostgreSQL: coordinated Replicated/Shared nested tables for HA #110886#discussion_r4297823304] The Keeper fix explicitly leaves this supported ZooKeeper path unsafe.

  • src/Storages/PostgreSQL/PostgreSQLReplicationHandler.cpp:2195 — Standby reads can expose an incomplete replacement snapshot. The standby hides tables only on its coordination poll, after it may already have applied the replicated truncation. Reads and backups in that interval accept empty or partial data. The marker-generation check repairs missed generations but does not fence visibility when the truncation executes. Enforce readiness at that boundary or before exposing the table. [dismissed by author -- https://github.com/MaterializedPostgreSQL: coordinated Replicated/Shared nested tables for HA #110886#discussion_r4230458968] The acknowledged interval still violates snapshot availability.

⚠️ Majors

  • src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp:666 — Some refused drops resume into permanently stopped plain nested storage. If the nested drop fails after shutdown, attach-style recovery reuses an object whose merges, moves and cleanup were permanently stopped. Writes accumulate parts until replication fails. Failed database drops and permanent-detach compensation retain related stopped survivors. Reconstruct or reattach them while preserving data and slot position. [dismissed by author -- https://github.com/MaterializedPostgreSQL: coordinated Replicated/Shared nested tables for HA #110886#discussion_r4306704180] Moving the earlier shutdown fixes only failures before the nested drop starts.

  • src/Interpreters/InterpreterDropQuery.cpp:715 — A refused enclosing database drop can strand a standalone nested replica. All tables are prepared for shutdown before individual drops. If another table refuses its drop before the wrapper is reached, the nested replica stays stopped and the wrapper's recovery never runs; the enclosing Atomic database has no compensating recovery. Preflight this path or recover prepared survivors. [dismissed by author -- https://github.com/MaterializedPostgreSQL: coordinated Replicated/Shared nested tables for HA #110886#discussion_r4329311855] Recovery currently covers only failures that reach the wrapper.

Tests
  • ⚠️ Add the projected-table variant of test_failed_publication_removal_reloads_table, verifying changes after compensation; the existing test uses all columns and misses the new regression.
  • ⚠️ The deferred findings still need focused evidence for lagged-TOAST takeover, an insert remaining in flight across takeover, election replacement without CHECK_STAT, standby visibility during resnapshot, and resumed background work after refused drops.
  • No local builds or tests were run in this CI review job. The published Praktika report reports no failed tests; that does not establish the missing cases above.
Final Verdict

Status: ❌ 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.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 17, 2026
@mintlify

mintlify Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 24, 2026, 10:43 AM

alexey-milovidov and others added 2 commits July 17, 2026 20:56
…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]>
alexey-milovidov and others added 3 commits July 18, 2026 03:39
…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]>
Comment thread src/Interpreters/DatabaseCatalog.cpp Resolved
alexey-milovidov and others added 4 commits July 18, 2026 08:00
… 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]>
alexey-milovidov and others added 2 commits July 18, 2026 15:10
…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

Copy link
Copy Markdown
Member Author

CI status for 9c567c81aca — the three red checks are all unrelated to this MaterializedPostgreSQL change (which only touches PostgreSQL replication/database code):

@groeneai

Copy link
Copy Markdown
Collaborator

@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 -Tuple combinator (new in 26.7) named its combined -State after the pre-NullsAction base name (any) instead of the resolved nested function (any_respect_nulls). RESPECT NULLS picks the window variant, whose state layout differs from the aggregation variant, so on a type-name round-trip (the two-level memory-efficient merge that runs in MergingAggregatedBucketTransform::transform) the state is reconstructed with the wrong implementation and read at incompatible offsets, giving the garbage string_view cell that segfaults in AggregateFunctionDistinctSingleGenericData<false>::merge. Reproduced deterministically on debug and confirmed fixed both directions; #110930's 04607_... test covers this shape.

One correction on the grouping: MergingAggregatedBucketTransform::transform:394 is the generic two-level-merge driver, so it collects more than one bug. Of the PRs you listed, only two are actual segfaults there:

@groeneai

Copy link
Copy Markdown
Collaborator

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 (-ArgMin/setIfSmaller vs -Tuple/SerializationTuple) meant a different bug. The -Tuple combinator drops the NullsAction from its serialized state name; when -ArgMin wraps -Tuple, that wrong name is inherited, so the -State round-trip reconstructs the wrong variant and setIfSmaller reads a bad SingleValueDataString. Verified both directions on debug: the 4211-3a99 crash reproduces on baseline and is gone with #110930 applied. Details + minimal repro on #110930.

So #110930 owns both 4211-3a99 and 4514-3f61. No separate PR from me.

alexey-milovidov and others added 2 commits November 10, 2026 00:39
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pass update (head aaff37f92c57):

  • CI on 35f5bc256965: only the review-threads gate in Finish Workflow failed (9 unresolved threads), so the full suite did not run.
  • Merged master (no conflicts). The PR's file list did not change.
  • Review: addressed the three new clickhouse-gh blockers in aaff37f. Details are in the replies on each thread:
    • a failed publication removal in DETACH TABLE ... PERMANENTLY is now treated as potentially committed, and the table is reloaded;
    • the leaked-publication cleanup holds /leader and repeats its check under it;
    • recovering a refused drop now always invalidates snapshot_completed before it discards a stopped copy, and the active worker redoes the snapshot when the marker disappears.
  • Added two failpoints and two integration tests.
  • The changed translation units compile without warnings. I did not run the integration tests locally (no linked binary after the master merge).
  • The six older open threads still need a design decision, as stated in the earlier replies.

…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]>
alexey-milovidov and others added 2 commits November 12, 2026 15:28
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pass update (head 28a7d0df2b5f):

  • CI on 254942623b95: all checks passed.
  • Review: I addressed the three open clickhouse-gh threads. A retried DROP TABLE with a null handler no longer dereferences it. Stopped-copy recovery now has a durable fence in Keeper (nested_recreations) that lasts until the replacement exists. A missing coordinated publication is now recreated only after the snapshot marker is invalidated, so all tables reload from a new slot. I replied on each thread.
  • Verification: both changed C++ files compile locally. I did not run the integration tests locally, because a full binary rebuild was not feasible on this shared machine, so CI is the first run of the extended test_single_table_publication_recreated_after_external_drop.

alexey-milovidov and others added 3 commits November 14, 2026 04:08
`pqxx::result` iteration yields `row_ref` by value, so bind it by value.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pass update (head 552808ade37d):

  • CI on 28a7d0df2b5f: Build (arm_tidy, 4/4) failed on clang-diagnostic-range-loop-bind-reference for for (const auto & row : result) over pqxx::result in PostgreSQLReplicationHandler.cpp. Fixed: the loop now binds row by value (b817246). master already had the same fix for the other such loop.
  • Merged master. There were two conflicts. In InterpreterDropQuery.cpp I kept both the PR's beforeDropDatabase/beforeTruncateDatabase vetoes and master's checkDatabaseHasNoIncrementalRefreshSources, all before stopReplication. In PostgreSQLReplicationHandler.cpp it was the same by-value loop fix. The PR's file list did not change.
  • Review: addressed the new clickhouse-gh comment about removing the recreation fence before the registration on a failed startup. Both are now removed in one multi-request (552808a). Details are in the thread.
  • Still open for a human decision (unchanged): the standby visibility window, the takeover consistency for unchanged TOAST values, fencing of in-flight snapshot inserts, and the rebuild of stopped plain or Atomic survivors.

alexey-milovidov and others added 3 commits November 18, 2026 07:34
…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]>
alexey-milovidov and others added 4 commits November 21, 2026 08:42
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pass update (head 918fb9f39e9e):

  • CI on c2b6ed5fc9ce: all four Build (arm_tidy) shards failed on modernize-use-nodiscard for postgres::Connection::getGeneration. Fixed in 8e51fd8. Finish Workflow failed only on the unresolved-review-threads gate.
  • Merged master (no conflicts). The file list of the PR did not change.
  • Review: addressed the three new clickhouse-gh threads; details are in the replies.
    • 95075ef: the consumer keeps the Relation definition of a table that waits for its snapshot LSN, keeps the gate until the slot is past that LSN, and compares it with the commit position of the transaction.
    • 918fb9f: RENAME DATABASE and TRUNCATE ALL TABLES are now rejected for plain MaterializedPostgreSQL engines too. The rename rejection changes behavior for existing plain setups.
  • Verification: built the binary and ran four integration tests locally, all passed: the two new ones, test_attach_table_skips_changes_made_before_snapshot_export, and test_rename_database_and_truncate_all_tables_are_rejected_in_coordinated_mode. The rest of the suite is left to CI.
  • Still open for a human decision (unchanged, six threads): the standby visibility window, takeover consistency for unchanged TOAST values, fencing of in-flight snapshot inserts, and the rebuild of stopped plain or Atomic survivors.

@stresshouse

stresshouse Bot commented Nov 21, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 10 not_sure 92 114 +23.9% <0.0001 aggregation: The +23.9% slowdown sits inside master's normal range (83-115 ms), and this query's history is noisy. The PR does not touch GROUP BY or COUNT(DISTINCT), so keeping the row suppressed is correct.
⚠️ 28 not_sure 1070 1006 -6.0% 0.0004 cpu: The -6.0% gain is borderline: the two tests disagree and both builds' measurements were noisy. The PR does not touch REGEXP_REPLACE or the aggregation path, so it stays inconclusive.

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
  • StressHouse run: bff57d5d-fa48-4de2-b771-de10c2c6f3fd
  • MIRAI run: 6038d414-6ea9-4807-bea6-97d37ada9b5f
  • PR check IDs:
    • clickbench_642688_1795259915
    • clickbench_642694_1795259914
    • tpch_adapted_1_official_642710_1795259915
    • tpch_adapted_1_official_642751_1795259915

alexey-milovidov and others added 3 commits November 24, 2026 09:31
…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);

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.

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

This branch was successfully deployed

1 active deployment
staging - docs — d6614f90 Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-postgresql PostgreSQL-specific integration (table engine/function, logical replication bridge). pr-experimental Experimental Feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Materialized Postgresql DB engine: improvements for underlying tables created by the engine

4 participants