Skip to content

feat: sql cluster interface - #102405

Closed
ylw510 wants to merge 59 commits into
ClickHouse:masterfrom
ylw510:feature-sql-cluster-interface
Closed

ylw510 wants to merge 59 commits into
ClickHouse:masterfrom
ylw510:feature-sql-cluster-interface

Conversation

@ylw510

@ylw510 ylw510 commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #93137

Changelog category (leave one):

  • New Feature

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

You can now define ClickHouse clusters with SQL (CREATE ENDPOINT / CREATE SHARD / CREATE CLUSTER) instead of editing <remote_servers> in the server config. Catalog metadata is stored in Keeper, replicated across nodes that share a replica group, and materialized for use with Distributed tables, the cluster table function, and ON CLUSTER DDL.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Docs added under docs/en:

  • Guide: operations/sql-clusters.md — motivation, <cluster_metadata> settings (Keeper path, replica_group, encryption, imports), privileges, SYNC / ON CLUSTER, coexistence with remote_servers / cluster discovery, and end-to-end examples.
  • SQL reference: CREATE / ALTER for ENDPOINT, SHARD, and CLUSTER; DROP / SHOW CREATE updates.
  • System tables: system.endpoints, system.shards; system.clusters description updated for SQL catalog clusters.

Example use:

CREATE ENDPOINT replica_01 PROPERTIES (host = 'ch1.example.com', port = 9000, user = 'default', password = 'secret');
CREATE ENDPOINT replica_02 PROPERTIES (host = 'ch2.example.com', port = 9000);

CREATE SHARD shard_01 REPLICA (replica_01, replica_02)
    PROPERTIES (weight = 1, internal_replication = true);

CREATE CLUSTER analytics (shard_01)
    PROPERTIES (secret = 'interserver-secret', allow_distributed_ddl_queries = true);

SHOW CREATE CLUSTER analytics;
-- Use `analytics` with Distributed / cluster() / ON CLUSTER like a remote_servers cluster

<!-- CI automatic block start :ci_links: -->

---
Workflow [[PR](https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=102405&sha=latest&name_0=PR)]
Sync PR [[sync-upstream/pr/102405](https://github.com/search?q=head%3Async-upstream%2Fpr%2F102405+org%3AClickHouse+type%3Apr&type=pullrequests)]
<!-- CI automatic block end :ci_links: -->

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Apr 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2c90b1a]

Summary: ❌

job_name test_name status info comment
Style check FAIL
cpp FAIL cidb
Code Review DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_binary) DROPPED
Build (amd_release) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Apr 10, 2026
Comment thread src/Common/Clusters/ClusterFactory.cpp Resolved
Comment thread src/Common/Clusters/ClusterFactory.cpp Resolved
Comment thread src/Common/Clusters/ClusterFactory.cpp Resolved
@ylw510

ylw510 commented Apr 14, 2026

Copy link
Copy Markdown
Contributor Author

Comment thread src/Common/Clusters/ClusterFactory.cpp Resolved
Comment thread src/Common/Clusters/ClusterFactory.cpp Resolved
@ylw510

ylw510 commented Apr 15, 2026

Copy link
Copy Markdown
Contributor Author

ylw510 added 3 commits August 5, 2026 15:41
Inline the thin catchUpLocalSnapshot wrapper into processCommittedEntries,
drop the always-set snapshot_reloader null check, and fail closed when the
local digest does not match the durable snapshot instead of reloading.
mutation_preparer and mutation_applier are always provided by
ClusterMetadataManager::initialize, so the defensive empty checks are noise.
Exercise read-only <imports> across replica groups: system.clusters refresh,
local catalog opacity, digest updates, drops, and local name shadowing.
@ylw510

ylw510 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Follow-up refactoring: single source of truth for cluster definitions and connection pool decoupling

Status: planned (this document describes follow-up work to be done after the current SQL cluster catalog PR is merged; it is not part of the current PR).

1. Background and motivation

The current PR introduces SQL-managed cluster metadata (ClusterMetadataManager / ClusterMetadataStorage::Snapshot,
i.e. the endpoints / shards / clusters catalog tables). To avoid touching the Cluster class,
which carries a lot of historical baggage, the PR takes a "tolerating" approach: a materialization
task materializationTask, scheduled every second, materializes the full Snapshot into
ClusterPtr objects and pushes them into the unified ClusterFactory registry
(replaceSQLCatalogClusters).

Problems this leaves behind:

  1. Two representations of the same cluster: the declarative definition (Snapshot) and the
    materialized object (ClusterPtr), reconciled by a periodic task (with three bookkeeping
    variables: materialization_requested / snapshot_version / materialized_snapshot_version).
  2. Visibility lag: there is an asynchronous window between a DDL commit and its visibility in
    system.clusters / getCluster; read-your-writes is not deterministic.
  3. All-or-nothing publishing: if materializing any single cluster definition throws an
    exception, the entire publish fails and is retried every second, spamming the log.
  4. Connection pool churn: any single DDL statement rebuilds the ClusterPtr of all catalog
    clusters (all connection pools are recreated).
  5. Root cause: Cluster couples two responsibilities together:
    • metadata (topology, addresses, weights, secret, allow_distributed_ddl_queries)
    • runtime resources (ShardInfo::pool / per_replica_pools, failover error state, the
      is_local cache)

2. Target architecture

Three separated layers, with the definition layer as the single source of truth:

Write sources                       Single definition layer          Runtime layer
─────────────                       ───────────────────────          ─────────────
SQL DDL (Keeper log)      ──┐
remote_servers XML parser ──┼──▶  ClusterCatalogTypes /      ──▶   ClusterConnectionCache
ClusterDiscovery          ──┘     ClusterSnapshot (immutable)       (name+digest → pools)
remote()/DatabaseReplicated ──▶  owned SnapshotPtr (not in registry) ──┘
  • Definition layer (source of truth): the reference-style catalog shape
    (endpoints / shards / clusters), isomorphic to today's ClusterMetadataStorage::Snapshot.
    The ClusterFactory registry stores only immutable ClusterSnapshotPtr values, tagged with
    their source (config / SQLCatalog / Discovery). Precedence is resolved at read time:
    config > catalog > discovery.
  • Runtime layer: ClusterConnectionCache builds/reuses connection pools keyed by the
    definition digest; is_local is computed when expanding addresses or building pools and never
    enters the source of truth.
  • The Cluster class is replaced: no more Cluster / ShardInfo with embedded pools exposed
    to consumers; read paths get a ClusterSnapshotPtr plus ClusterShardConnections from the cache.
  • The materialization task is deleted: the manager only publishes the definition snapshot
    pointer synchronously (cheap, infallible, no retries);
    materializationTask / replaceSQLCatalogClusters / registerCatalogClustersInto are all removed.

3. Key design

3.1 ClusterSnapshot (immutable definition view)

struct ClusterSnapshot
{
    String name;
    String secret;
    bool allow_distributed_ddl_queries;
    ClusterDefinitionSource source;
    UInt64 version;                    /// transitive-closure digest of the definition, or a monotonic version
    std::vector<ShardSpec> shards;     /// addresses, weight, internal_replication
    SlotToShard slot_to_shard;         /// or computed lazily from weights
};
using ClusterSnapshotPtr = std::shared_ptr<const ClusterSnapshot>;
  • XML clusters require five additional fields on EndpointCatalogDefinition (in-memory fields,
    not exposed via SQL DDL, always persisted as defaults): quota_key, proto_send_chunked,
    proto_recv_chunked, stateless_worker_port, streaming_exchange_port.
  • Subcluster transforms (getClusterWithSingleShard / getClusterWithMultipleShards /
    getClusterWithReplicasAsShards) become pure functions on snapshots, returning a new
    ClusterSnapshotPtr.

3.2 ClusterConnectionCache (the new home for connection pools)

Replaces only what Cluster::addShard does today: shard-level failover assembly plus the local
replica layout. Address-level deduplication of the underlying ConnectionPool objects remains the
job of the existing ConnectionPoolFactory — do not reinvent it.

struct ClusterShardConnections
{
    ConnectionPoolWithFailoverPtr pool;      /// same meaning as today's ShardInfo::pool
    ConnectionPoolPtrs per_replica_pools;    /// local slots are nullptr (contract preserved)
    Cluster::Addresses local_addresses;
};

class ClusterConnectionCache
{
    ClusterShardConnections getShard(const ClusterSnapshot &, size_t shard_index,
                                     const Settings &, UInt16 clickhouse_tcp_port);
    void invalidate(const String & cluster_name);
    void invalidateAll();    /// used by reloadClustersConfig / DNSCacheUpdater
    void shutdown();
};

Cache key: (cluster_identity, definition_digest, shard_index, pool_settings_key).

  • cluster_identity: named cluster = name + source; ephemeral cluster = "ephemeral:" + content digest.
  • definition_digest: transitive-closure digest of the cluster definition (hash of the serialized
    members → shards → endpoints). DDL such as ALTER ENDPOINT changes the digest → natural cache
    miss → only the pools of affected clusters are rebuilt (better than today's full rebuild).
  • pool_settings_key: include only the settings that affect pool construction —
    distributed_connections_pool_size, load_balancing, distributed_replica_error_half_life,
    distributed_replica_error_cap. Do not put the whole Settings object into the key.

Implementation notes:

  1. Double-checked locking: pool construction (including DNS) happens outside the lock; when two
    threads miss simultaneously, the first inserter wins.
  2. Preserve today's local-slot contract: a local replica still gets a pool and participates as a
    failover candidate, while also being recorded in local_addresses; its slot in
    per_replica_pools is nullptr.
  3. Failover error state: while the definition is unchanged, reuse the same failover object
    (preserving error counters, matching today's behavior); once the definition changes, discard the
    old object so error counters are not applied to a new topology.
  4. Cache values are shared_ptr: queries still running after an invalidation keep their pools
    valid until the query finishes.
  5. Invalidation matrix:
    • SQL DDL / snapshot publish → digest miss (optionally invalidate proactively to release old
      objects sooner)
    • applyClustersConfig → invalidate the modified config clusters
    • reloadClustersConfig / DNS change → invalidateAll() (a forced re-materialization entry
      point must be kept
      — this is the semantic DNSCacheUpdater relies on; do not short-circuit
      on definition digests alone)
    • shutdown → clear everything

3.3 Ephemeral clusters

Clusters from the remote() table function and DatabaseReplicated do not enter the global
registry (same as today). The replacement API must accept both "snapshot from the registry" and
"owned SnapshotPtr". StorageDistributed::owned_cluster becomes a ClusterSnapshotPtr.

4. Phased implementation (one standalone PR per phase, each based directly on master)

Phase Content Difficulty Rollback
P0 Extract immutable ClusterSnapshot / ShardSpec; all 6 construction paths (XML / remote() / DatabaseReplicated / Discovery / SQL catalog / Factory reload) produce it first; Cluster temporarily wraps snapshot + pools, behavior unchanged M Full
P1 Subcluster transforms become pure functions on snapshots, then wrapped back into the old Cluster for compatibility M Full
P2 Introduce ClusterConnectionCache; Cluster::addShard internally delegates to the cache while ShardInfo.pool stays externally unchanged (dual-read, revertible) L High
P3 Migrate hot paths: StorageDistributed, DistributedSink, ClusterProxy/{executeQuery, SelectStreamFactory, distributedIndexAnalysis}, ReadFromRemote, getStructureOfRemoteTable, IStorageCluster XL Low, needs several PRs
P4 Migrate cold paths: ON CLUSTER DDL (executeDDLQueryOnCluster), backups, TCP secret verification, system.clusters (status served from the cache) S–M High
P5 Registry stores only SnapshotPtr; delete ShardInfo::{pool, per_replica_pools}, materializationTask, replaceSQLCatalogClusters, registerCatalogClustersInto; XML / Discovery write into the definition layer L Low
P6 Cleanup: mechanical ClusterPtr → ClusterSnapshotPtr replacement, shrink/delete Cluster.h, retype SelectQueryInfo::{cluster, optimized_cluster} M Mechanical

Critical ordering constraint: pools cannot be removed from Cluster in one step (it would
break ~9 hot files simultaneously). Extract the snapshot first (P0), add cache dual-read (P2), and
only after the hot paths are migrated (P3) remove the pools (P5).

5. Blast radius assessment (based on current branch statistics)

Metric Magnitude
#include <Interpreters/Cluster.h> ~40 files
ClusterPtr references ~45 files / ~125 occurrences
getShardsInfo calls ~17 files / ~49 occurrences
Direct use of pool / per_replica_pools ~9 hot files / ~30 occurrences
make_shared<Cluster> construction sites 6
Subcluster transform callers 4 files / 6 call sites

6. Risks and pitfalls

  1. The nullptr-for-local contract of per_replica_pools: local execution paths depend on it;
    the cache must preserve it exactly.
  2. Pool semantics of subcluster transforms: today every transform builds a fresh set of pools
    (fresh failover error state); with snapshot transforms + cache, pools may be reused — the
    semantics must be made explicit and tested (especially the parallel-replicas single-shard path).
  3. DNS reload: the whole point of reloadClustersConfig is to rebuild connections even when
    the config is unchanged (to re-resolve DNS); the cache must provide a forced invalidation entry
    point. Consumers of getClustersVersion (e.g. DistributedAsyncInsertDirectoryQueue) need an
    equivalent version/invalidation signal.
  4. errors_count / slowdowns_count in system.clusters: they come from live pools via
    pool->getStatus(); on a cache miss they would read as 0, or the cache needs pre-warming — the
    behavioral difference must be pinned down in tests.
  5. Reference-style vs expanded-style: the catalog is reference-style (members → shard names →
    endpoint names) while the old Cluster is an expanded address tree. The registry stores the
    reference-style source of truth; the read side expands it into a ClusterSnapshot view via a
    pure function.
  6. XML parsing parity: <node> syntax, macro expansion, per-replica default inheritance,
    weights — compare field by field against the XML constructor of Cluster::Address, and run a
    full regression of the existing remote_servers integration tests.

7. Test plan

  • DDL read-your-writes: CREATE CLUSTER followed immediately (no sleep) by ON CLUSTER /
    querying system.clusters.
  • Same-name precedence: config beats catalog; catalog beats discovery.
  • Pool reuse: after ALTER ENDPOINT, the affected cluster takes effect immediately while the pool
    objects of unrelated clusters stay identical (assert on pointers/state).
  • Broken definitions (only possible from imported groups): the remaining clusters stay usable;
    directly querying the broken cluster throws BAD_CLUSTER_DEFINITION.
  • DNS reload: after invalidateAll, new pools re-resolve DNS; in-flight queries finish normally on
    their old pools.
  • Local layout: with prefer_localhost_replica combinations, the local path never falls back to
    remote.
  • ClusterConnectionCache unit tests: key stability, settings-based key separation, concurrent
    misses, invalidation semantics.
  • XML parity: full regression of existing remote_servers integration tests, plus dedicated tests
    for <node> / macros / weights.

8. Boundary with the current PR

The current PR is merged as-is (with the materialization task approach). All phases of this plan
start only after it lands in master, and each PR is based directly on master (no stacked PRs).
Before starting P0, open a tracking issue with this document as its body, and link each phase's PR
back to it with Related: lines.

@ylw510
ylw510 marked this pull request as ready for review August 11, 2026 15:27
@nikitamikhaylov nikitamikhaylov self-assigned this Aug 21, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

It appears complicated that we introduce new commands, CREATE ENDPOINT, CREATE REPLICA, CREATE SHARD, because:

  • CREATE ENDPOINT can be confused with named collections; it would be more natural to use named collections for them, just like we use them for table engines and table functions;
  • if we don't use named collections for the implementation of CREATE ENDPOINT, it will be confusing to not being able to provide an endpoint as an argument of the table function remote;
  • CREATE REPLICA is confusing relative to adding a replica to a table or a database;

The overall complexity (11k lines of code) is too high.

@abashkeev abashkeev added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Dear @nikitamikhaylov, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

alexey-milovidov and others added 3 commits October 14, 2026 06:36
…-interface

Conflict resolution notes:
- `ErrorCodes`: master took codes 780-785, the PR's cluster catalog codes were renumbered to 786-792.
- `Cluster`: master removed `ShardInfoInsertPathForInternalReplication` and `concatInsertPath`; kept the PR's `appendShardWeight`, `ShardInitSpec` constructor and definition metadata next to master's shard scope identity.
- `Context::getCluster(name, treat_local_port_as_remote)` (new on master) now reads the `remote_servers` config from `ClusterFactory::getClustersConfig` and falls back to `tryGetCluster`.
- `attachSystemTables` and the statement docs are now generated from source on master: the descriptions of `system.shards`, `system.endpoints`, `system.clusters` and the `DROP`/`SHOW CREATE` sections moved into `DOCS_MD` registrations; the generated regions in `drop.mdx`, `show.mdx` and `clusters.mdx` were taken from master.
- `02117_show_create_table_system.reference` taken from master (the test no longer prints the schema).
- Links in the PR's docs pages converted from slugs to file paths, as used on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master already declares 252 access types, and the 9 privileges added for SQL clusters
(`CREATE`/`ALTER`/`DROP` `ENDPOINT`, `SHARD`, `CLUSTER`, `SHOW CREATE SHARD`/`CLUSTER`)
exceed the 256 values representable by `uint8_t`, which broke the build with
`-Wduplicate-enum` errors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts. Changes beyond the mechanical merge:

  • AccessType is now uint16_t and AccessFlags::SIZE is 512. Master already declares 252 access types, so the 9 privileges this PR adds no longer fit in uint8_t, and the build failed with -Wduplicate-enum. This is a core change that reviewers should look at. The alternative is for this PR to declare fewer privileges.
  • Renumbered the PR's error codes to 786-792, because master now uses 780-785.
  • On master, statement docs and system table docs are generated from source. I moved the DROP ENDPOINT/SHARD/CLUSTER and SHOW CREATE SHARD/CLUSTER sections into the documentation in ParserDropQuery and ParserShowTablesQuery, and the descriptions of system.shards, system.endpoints and system.clusters into attachSystemTables. The generated regions of the .mdx files are left as on master. I also changed the links in the PR's docs pages from slugs to file paths.
  • The clickhouse-local overload Context::getCluster(name, treat_local_port_as_remote), which is new on master, now uses the new ClusterFactory::getClustersConfig.
  • Adapted the code to getSchedulePool returning a shared_ptr.

The clickhouse binary builds locally. These stateless tests pass locally: 01271_show_privileges, 01999_grant_with_replace, 02117_show_create_table_system, 03237_avro_union_in_complex_types, 03988_keeper_client_autocomplete, and the system.documentation / system.statements tests. I did not run the integration test test_sql_catalog_replica_ddl locally.

Comment thread src/Parsers/ASTCreateEndpointQuery.h Resolved
Comment thread src/Access/Common/AccessType.h Resolved
const UInt32 max_log_ptr = getMaxLogPointer();
const UInt32 logs_to_keep = readUInt32Node(getZooKeeper(), logs_to_keep_path);

reloadSnapshotAndAdvanceIfTooFarBehind(log_ptr, max_log_ptr, logs_to_keep);

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.

[P1] Bootstrap the snapshot and applied log pointer at the same position

ClusterMetadataManager::initialize already reads the latest durable snapshot, but registerReplica preserves the returning node's old log_ptr. For a lag of at most 1000, this call does not reconcile them. Stop node A with c = [s1], execute ALTER CLUSTER c ADD SHARD s2 on B, then restart A: A loads [s1, s2] and replays the addition against that snapshot. AddClusterMembers throws because s2 is already present; the batch leaves the old pointer unchanged, so later replication and local catalog DDL remain stuck.

Establish a consistent snapshot and matching applied position during bootstrap/reload, synchronized with catalog writes. The same invariant needs recovery when local apply succeeds but the follower's acknowledgment fails: retrying the intent against the advanced snapshot also duplicates the addition. Add a stop/change/restart regression and verify that a subsequent mutation reaches the restarted node.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in 2c90b1a. A new reloadSnapshotConsistentlyUnlocked reads the snapshot between two equal reads of max_log_ptr. That counter is updated in the same transaction as the catalog and only grows, so the snapshot matches it exactly. It then sets the replica digest and log_ptr (and the finished statuses of the skipped entries) in one transaction. initializeReplication calls it under processing_mutex whenever log_ptr < max_log_ptr, and so does every failed incremental apply. That covers the case where the local apply succeeded but the acknowledgment failed, and a failed local apply right after enqueue. I added your stop / ALTER CLUSTER ... ADD SHARD / restart scenario to test_replica_ddl_keeper_backed_catalog, plus a later mutation from each node. It passes locally, and the restarted node logs Reloaded cluster metadata snapshot ... at log_ptr=16 (was 15).

Comment on lines +522 to +527
const auto shard = readShard(shard_name);
zookeeper->createIfNotExists(shardRefsPath(shard_name), "");
for (const auto & endpoint_name : shard.endpoint_names)
{
validateEntityName(endpoint_name, "Endpoint");
zookeeper->createIfNotExists(endpointShardRefPath(endpoint_name, shard_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.

[P1] Serialize reference-index reconstruction with catalog writes

initLayout runs this repair on every joining/reinitializing node without the enqueue lock. Node A can read shard s referencing endpoint e, then node B can atomically drop s and its reference nodes. A subsequently recreates refs/shards/s and refs/endpoints/e/s from its stale copy. These ghost references permanently prevent DROP ENDPOINT e with ZNOTEMPTY and prevent recreating s with ZNODEEXISTS; later repairs only create nodes and cannot remove the ghosts. The cluster-reference loop has the same race.

Serialize reconstruction with catalog DDL, or install references in a version-checked transaction that verifies the source definition still exists and contains the reference.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in 5ea1d70. rebuildReferenceIndex now computes the missing references from a fresh read and creates them only in transactions that start with a check on the version of the snapshot digest node. Every catalog write updates that node in its own transaction, and the node is never recreated, so the check cannot be fooled by drop-and-recreate (ABA). When the check fails, or another node's repair creates the same reference concurrently, the rebuild starts over, up to 10 attempts. Ghost references created by earlier builds are not cleaned up by this change.

SCOPE_EXIT({
try
{
zookeeper->tryRemove(counter_lock_path);

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.

[P2] Stop scope cleanup after the transaction releases the lock

The successful multi already removes counter_lock at line 285, but this unconditional cleanup runs after local apply. While A applies locally, B can acquire the same path; A then removes B's lock on scope exit. B's transaction fails with ZNONODE, or a third writer enters concurrently and causes further transaction conflicts, despite B having acquired the lock successfully.

Disarm cleanup once the transaction has released the lock. Exceptional cleanup must also avoid deleting a successor's lock after session loss or an uncertain transaction result.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in 2c90b1a: cleanup is disarmed once the commit transaction (which removes counter_lock) has succeeded. On the exceptional path the lock is removed only if ephemeralOwner equals our session id, with a version-checked remove. A successor's lock is therefore never deleted after session loss or an uncertain transaction result.

bool encrypted_,
String encryption_key_hex_,
String encryption_algorithm_)
: zookeeper(std::move(zookeeper_))

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.

[P1] Refresh the Keeper session held by catalog storage

This pointer is captured once and never replaced. After session expiration, Context::getZooKeeper creates a new object, and DDLWorker refreshes its own connection, but ClusterMetadataDDLWorker::initKeeperLayout immediately calls storage->initLayout through this expired pointer. Every subsequent worker initialization fails again. Imported groups retain the same expired pointer and continue serving stale topology indefinitely.

Obtain the current session for storage operations, or refresh every local/imported storage instance as part of recovery. Cover a session expiration followed by a catalog mutation and verify that replicas and importers resume receiving changes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in 5ea1d70: ClusterMetadataStorage now takes a getter (Context::getDefaultOrAuxiliaryZooKeeper(keeper_name)) and calls it for every operation instead of caching the session. So after an expiration, both the local group storage used by initKeeperLayout and the importer's group storages use the renewed session.

Comment thread programs/server/Server.cpp Outdated
/// initializes the session with `ServerUUID::get`. SQL catalog clusters (`CREATE CLUSTER` /
/// `CREATE SHARD`) live under the configured `<clusters_catalog_storage.path>` on Keeper.
ClusterFactory::instance().initialize();
ClusterMetadataManager::instance().initialize();

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.

[P1] Initialize the catalog after embedded Keeper starts listening

ClusterMetadataManager::initialize synchronously opens a Keeper connection and calls storage->initLayout. At this point the server's embedded Keeper has not started: its dispatcher is initialized at line 3113 and its TCP listener is created afterward. With keeper_server enabled and the ZooKeeper client pointing to that same server, startup fails while trying to connect to its own unstarted Keeper and never reaches the code that starts it. A cold start of an ensemble made entirely of combined servers has the same dependency cycle.

Keep ServerUUID initialization early, but initialize catalog persistence after the embedded Keeper listeners are running. Add a combined server/Keeper startup case with the catalog enabled.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in 97c8801: only ClusterFactory::initialize (which does not touch Keeper) stays early. ClusterMetadataManager::initialize now runs after startServers(servers_to_start_before_tables) has started the embedded Keeper listeners, and after macros are loaded. It still runs before the system tables are attached and tables are loaded, so Distributed tables can resolve SQL clusters. I did not add a combined server/Keeper integration case, to keep the integration suite small.

if (!current || !current->clusters || current->clusters_config.get() != pinned_config.get())
return;

auto builder = std::make_shared<Clusters>(*current->clusters);

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.

[P1] Refresh the macro snapshot when rebuilding the registry

The Clusters copy constructor retains its pinned macros_, which getCluster uses to expand every cluster name. This reload replaces individual Cluster objects but never refreshes that macro snapshot. Previously, Context::reloadClusterConfig constructed a new Clusters with the current getMacros.

Change a macro target from c1 to c2, reload configuration, and run SYSTEM DROP DNS CACHE: cluster('{target}', ...) still resolves c1. With the catalog enabled, its initial materialization can also pin the empty macro snapshot before Server.cpp:2104 initializes configured macros. Refresh macros when rebuilding/publishing the registry, including when only macros change, and add a lookup regression for a changed macro.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in 97c8801: publishClustersSnapshotLocked refreshes the Clusters macro snapshot from the global context on every publication. applyClustersConfig republishes even when <remote_servers> is unchanged, so a change to macros alone is picked up. The config reload callback now sets macros before setClustersConfig. The catalog's first materialization also happens after macros are initialized now (see the startup-order thread). I did not add an integration regression for the macro change, because it needs a config reload.

Comment thread src/Common/Clusters/ClusterFactory.cpp Outdated
Comment on lines +160 to +161
if (auto existing = current->clusters->getCluster(cluster_name);
existing && existing->getDefinitionSource() == ClusterDefinitionSource::RemoteServersConfig)

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.

[P1] Make catalog/discovery precedence independent of publication order

This guard protects only config-defined clusters. If SQL catalog cluster c already exists and discovery publishes a different cluster named c, ClusterDiscovery::upsertCluster reaches setCluster and overwrites the SQL entry. The catalog materializer does not republish until its snapshot version or request changes, so Distributed queries and ON CLUSTER use the discovery topology indefinitely. Publishing in the opposite order selects the SQL topology instead, allowing otherwise identical nodes to route differently based on watch timing.

Apply the same source precedence in every publisher; minimally prevent discovery from replacing an existing SQL catalog entry. Cover a same-name collision and a subsequent discovery membership update.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in 97c8801: setCluster now applies one precedence order for every source, <remote_servers> > SQL catalog > discovery (lower enum value wins), so discovery can no longer overwrite an existing SQL catalog cluster. replaceSQLCatalogClusters already let SQL replace discovery entries, so both publication orders now give the SQL topology. A discovery removeCluster never evicts a SQL entry because of the source check. Limitation: after the SQL cluster is dropped, the shadowed discovery cluster reappears on its next discovery update.

@ylw510

ylw510 commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov, the new implementation is here: #116757. We probably don't need to make changes in this branch anymore.

alexey-milovidov and others added 4 commits October 21, 2026 15:58
…-interface

Conflict resolution:
- `ErrorCodes.cpp`: master took code 786 for `BAD_FUNCTION_SIGNATURE`; renumbered this PR's codes to 787-793.
- `Context.cpp`: kept master's new stateless worker providers shutdown block; the `ClusterDiscovery` shutdown stays moved earlier as in this PR.
The `DROP`/`SHOW CREATE` sections for the new entities live in the autogenerated
regions of `drop.mdx`/`show.mdx` (source of truth is already updated in the parsers),
so link to the pages without fragments until they are regenerated.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=102405&sha=4e1d75af37a266a776da879d603e8287b2e8ef1d&name_0=PR&name_1=Docs%20check%20%28Mintlify%29
ClickHouse#102405

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…llow_ddl` for catalog DDL

- Override `hasSecretParts` in `ASTCreateEndpointQuery`, `ASTAlterEndpointQuery`,
  `ASTCreateClusterCatalogQuery`, `ASTAlterClusterQuery` and `ASTAlterShardQuery`:
  their `PROPERTIES` are kept outside the AST children, so without it `formatForLogging`
  was skipped and endpoint passwords / cluster secrets reached `system.query_log`.
- Add the mutating catalog privileges to the `readonly` and `allow_ddl` masks in
  `ContextAccess`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 2c90b1a.

Approve preview

Comment on lines +579 to +580
const bool caught_up_to_durable_log = last_ready_entry >= getMaxLogPointer();
const String target_digest = caught_up_to_durable_log ? storage->readSnapshotDigest() : "";

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.

[P1] Compare the batch with a digest from the same log position

These are separate Keeper reads, and followers do not hold counter_lock. A follower applying through entry N can read max_log_ptr = N, then another node commits N+1 before readSnapshotDigest, so the comparison uses the digest of N+1 for the snapshot of N. mutation_applier has already published N locally when the digest check throws, but the acknowledgment and applied pointer remain behind. If N contains AddClusterMembers, the next pass replays the addition and fails with already listed, permanently blocking replication and subsequent local catalog DDL despite healthy Keeper.

Bind the expected digest to the processed log entry, or obtain and validate a consistent log-position/digest pair. Add a focused concurrent-writer/follower case that verifies a later mutation still applies.

void ClusterMetadataDDLWorker::updateReplicaDigest(const String & digest)
{
auto zookeeper = getZooKeeper();
storage->writeSnapshotDigest(digest);

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.

[P1] Keep lag recovery from overwriting the committed catalog digest

updateReplicaDigest is called after a lagging replica reloads its snapshot, outside the enqueue lock. If it reads snapshot N, another writer commits N+1, and recovery then reaches this line, it overwrites the authoritative snapshot_digest for N+1 with the stale digest of N. An importer that already cached digest N now sees no change and can retain the old endpoint/topology indefinitely, even though Keeper contains N+1. This is reachable whenever a node catches up after more than the retained-log threshold.

Recovery should update only replica_digest_path; update the shared snapshot digest exclusively in the transaction that commits catalog metadata. Cover a lag reload overlapping another catalog mutation and verify that an importer receives the final topology.

if (i >= imported_groups.size())
break;
imported_groups[i].snapshot = std::move(new_snapshot);
imported_groups[i].digest = current_digest;

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.

[P1] Verify the imported snapshot matches the digest being cached

current_digest is sampled before the multi-read readSnapshot, but the snapshot is published and labeled with that earlier digest without comparing new_snapshot.digest. A fresh importer can read digest D for an endpoint at host A, read the endpoint after an ALTER ENDPOINT changes it to B, and then have the source change back to A before the next poll. It permanently retains host B labeled as D: subsequent polls see the source digest D and skip refreshing. This can route queries to a host the source catalog no longer references, even without a Keeper failure.

Before publishing, verify that the calculated snapshot digest matches the sampled digest and that the source position is stable; retry an inconsistent read. Cover a source endpoint changing A → B → A during an import.

Comment on lines +355 to +356
if (cluster && cluster->getDefinitionSource() == ClusterDefinitionSource::RemoteServersConfig)
config_cluster_names.push_back(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.

[P1] Refresh SQL cluster locality when invalidating DNS

SYSTEM CLEAR DNS CACHE calls reloadClusterConfig specifically to rebuild cached address/locality information, but this filter rebuilds only XML clusters and retains SQL catalog Cluster objects. For an SQL endpoint whose hostname initially resolves to this server, change DNS to another server and clear the DNS cache: the SQL cluster still has its old is_local and local_addresses. The periodic catalog materializer skips an unchanged snapshot, so this persists until another catalog mutation or restart. SelectStreamFactory and DistributedSink then continue reading/writing local tables instead of the new remote host with prefer_localhost_replica enabled.

Force catalog endpoint rematerialization on this reload path, including imported clusters. Add a local-to-remote DNS transition case for a SQL cluster.

auto cluster = makeCluster(cluster_info);
std::lock_guard lock(mutex);
cluster_impls[cluster_info.name] = cluster;
ClusterFactory::instance().setCluster(cluster_info.name, cluster, ClusterDefinitionSource::Discovery);

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.

[P2] Retain discovered topology while an XML cluster shadows it

Replacing discovery's own map with this winner-only registry loses the shadowed definition. Configure an XML cluster c and a multicluster observer that also discovers c: setCluster rejects the discovery publication because XML wins, but discovery has already cached nodes_info. Remove just the XML definition and reload configuration. mergeConfigClusters erases c, and discovery returns early at lines 487–490 because Keeper membership is unchanged, so c stays missing until membership changes or the server restarts. Previously the independent discovery map remained available when the config lookup stopped matching. This also affects deployments without SQL catalog configuration.

Retain per-source definitions or explicitly republish the affected discovery entry when the config override disappears. Cover override removal without changing Keeper membership.

alexey-milovidov and others added 4 commits October 21, 2026 17:47
Master now rejects unknown top-level config elements (`UNKNOWN_ELEMENT_IN_CONFIG`),
so servers with `<cluster_metadata>` failed to start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fter embedded Keeper

- `ClusterFactory` refreshes the `Clusters` macro snapshot on every publication (and republishes
  when `<remote_servers>` is unchanged), so a changed `<macros>` is used by cluster name
  expansion; macros are now set before the clusters config on config reload.
- `setCluster` applies the same precedence for every source on name collision:
  `<remote_servers>` > SQL catalog > discovery, so discovery can no longer replace a SQL
  catalog cluster depending on publication order.
- `ClusterMetadataManager::initialize` runs after the embedded Keeper listeners are started
  (and macros are loaded), but still before tables are loaded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…reference index repair

- `ClusterMetadataStorage` takes a getter and obtains the current Keeper session for every
  operation instead of holding the session it was created with, so the local and imported
  groups recover after a session expiration.
- `rebuildReferenceIndex` installs missing references only in transactions that check the
  version of the snapshot digest node (updated by every catalog write), and starts over on a
  conflict, so a concurrent `DROP` can no longer be followed by recreation of ghost references.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Add `reloadSnapshotConsistentlyUnlocked`: reads the durable snapshot between two equal reads
  of `max_log_ptr` (which is updated in the same transaction as the catalog) and sets the
  replica's digest and `log_ptr` to that position.
- Use it when a replica (re)initializes, instead of replaying the missed entries against a
  snapshot that may already contain them, and to recover from any failure of an incremental
  apply (including a successful local apply whose acknowledgment failed). No terminal failure
  status is written for committed entries anymore.
- Disarm the enqueue lock cleanup once the commit transaction has removed the lock, and on the
  exceptional path remove it only if it is still owned by our session.
- Add a stop / change / restart regression to `test_sql_catalog_replica_ddl`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

alexey-milovidov commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

🕵 @ylw510, noted that the new implementation is in #116757. Until someone decides whether this PR should be closed in favour of it, I kept this branch merge-clean and addressed the open review threads:

  • Merged master. Resolved the ErrorCodes.cpp conflict (786 is now taken by BAD_FUNCTION_SIGNATURE, so this PR's codes are 787-793) and the Context.cpp shutdown conflict. Also registered cluster_metadata as a known config section, because master now rejects unknown top-level config elements.
  • Fixed the CI failures: the clang-tidy readability-container-contains errors, and the docs check (navigation entries, broken links).
  • Addressed all 10 review threads. Each has a reply describing the change. Changes: secrets masked in logs, readonly / allow_ddl enforcement, consistent snapshot / log_ptr bootstrap and recovery, safe enqueue lock cleanup, version-checked reference index repair, Keeper session refresh in catalog storage, catalog initialization after the embedded Keeper starts, macro refresh, and source precedence.
  • Added the stateless test 05441_sql_cluster_catalog_readonly_and_secrets and a stop / change / restart case in test_sql_catalog_replica_ddl. Three of the four test functions in that module pass locally (test_replica_ddl_keeper_backed_catalog, test_cluster_metadata_importer, test_sql_catalog_ddl_errors). I did not run test_sql_catalog_property_validation_errors.

If #116757 replaces this PR, several of these fixes probably apply there too: the readonly masks, hasSecretParts, macro refresh, and source precedence.

@alexey-milovidov

Copy link
Copy Markdown
Member

Closing in favor of #116757

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQL interface for creating clusters

5 participants