Repository navigation
feat: sql cluster interface - #102405
feat: sql cluster interface#102405ylw510 wants to merge 59 commits into
Conversation
|
Workflow [PR], commit [2c90b1a] Summary: ❌
|
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.
Follow-up refactoring: single source of truth for cluster definitions and connection pool decouplingStatus: 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 motivationThe current PR introduces SQL-managed cluster metadata ( Problems this leaves behind:
2. Target architectureThree separated layers, with the definition layer as the single source of truth:
3. Key design3.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>;
3.2 ClusterConnectionCache (the new home for connection pools)Replaces only what 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:
Implementation notes:
3.3 Ephemeral clustersClusters from the 4. Phased implementation (one standalone PR per phase, each based directly on master)
Critical ordering constraint: pools cannot be removed from 5. Blast radius assessment (based on current branch statistics)
6. Risks and pitfalls
7. Test plan
8. Boundary with the current PRThe current PR is merged as-is (with the materialization task approach). All phases of this plan |
|
It appears complicated that we introduce new commands, CREATE ENDPOINT, CREATE REPLICA, CREATE SHARD, because:
The overall complexity (11k lines of code) is too high. |
|
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. |
…-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]>
…a `shared_ptr` 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]>
|
🕵 Merged
The |
| 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); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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).
| 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), ""); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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_)) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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.
| /// 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(); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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.
| if (auto existing = current->clusters->getCluster(cluster_name); | ||
| existing && existing->getDefinitionSource() == ClusterDefinitionSource::RemoteServersConfig) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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.
|
@alexey-milovidov, the new implementation is here: #116757. We probably don't need to make changes in this branch anymore. |
…-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.
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=102405&sha=4e1d75af37a266a776da879d603e8287b2e8ef1d&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 ClickHouse#102405 Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
| const bool caught_up_to_durable_log = last_ready_entry >= getMaxLogPointer(); | ||
| const String target_digest = caught_up_to_durable_log ? storage->readSnapshotDigest() : ""; |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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; |
There was a problem hiding this comment.
[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.
| if (cluster && cluster->getDefinitionSource() == ClusterDefinitionSource::RemoteServersConfig) | ||
| config_cluster_names.push_back(name); |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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.
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]>
|
🕵 @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:
If #116757 replaces this PR, several of these fixes probably apply there too: the readonly masks, |
|
Closing in favor of #116757 |
Closes: #93137
Changelog category (leave one):
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 withDistributedtables, theclustertable function, andON CLUSTERDDL.Documentation entry for user-facing changes
Docs added under
docs/en:operations/sql-clusters.md— motivation,<cluster_metadata>settings (Keeperpath,replica_group, encryption,imports), privileges,SYNC/ON CLUSTER, coexistence withremote_servers/ cluster discovery, and end-to-end examples.CREATE/ALTERforENDPOINT,SHARD, andCLUSTER;DROP/SHOW CREATEupdates.system.endpoints,system.shards;system.clustersdescription updated for SQL catalog clusters.Example use: