Skip to content

Implement applySettingsChanges for DatabaseReplicated - #117544

Open
kirillshokhin wants to merge 17 commits into
masterfrom
alter-database-replicate-settings
Open

kirillshokhin wants to merge 17 commits into
masterfrom
alter-database-replicate-settings

Conversation

@kirillshokhin

@kirillshokhin kirillshokhin commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

This commit allows updating DatabaseReplicated settings via ALTER DATABASE ... MODIFY SETTING ... query.

  1. Split settings into mutable and immutable: a. default_replica_path, default_replica_shard_name and default_replica_name are immutable because they're consulted only on the database creation. b. internal_replication is immutable since changing it in realtime may result in inconsistent query results.
  2. logs_to_keep is an immutable setting. It's a cluster-wide setting and modifying it is not safe without additional coordination. Specifically increasing logs_to_keep may result in the following scenario: 1. While replica B is offline, replica A trims the log to the old, smaller logs_to_keep value. 2. logs_to_keep is updated to a greater value. 3. Replica B starts, loads new, greater logs_to_keep value and skips recovery, thus skipping the trimmed entries.
  3. db_settings is stored in the MultiVersion container to synchronize concurrent readers and a writer.
  4. metadata_mutex is used to synchronize writers.
  5. If the collection_name setting changed, the cached cluster objects are invalidated and rebuilt on the next request. mutex is used to synchronize access to the cluster objects.
  6. logs_to_keep column added to the system.database_replicas table, sourced from the Keeper node to provide the real value of the setting.
  7. Old settings values are not compared to the new ones - any new value is considered a change. This allows setting the already used named collection's name to reload the collection's contents and update cluster credentials.

Closes: #74915

Changelog category (leave one):

  • New Feature

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

You can now change the settings of a Replicated database with ALTER DATABASE ... MODIFY SETTING.
Only replica-local settings are mutable, and the change applies only to the replica the query runs on.
Settings that only describe how the database was created (default_replica_path, default_replica_shard_name and default_replica_name), internal_replication, which must match on every replica, and logs_to_keep, which all replicas share through ClickHouse Keeper, are rejected.
Changing collection_name requires the NAMED COLLECTION grant on the new collection, and a collection with a cluster_secure_connection value different from the current one is rejected.
The new logs_to_keep column in system.database_replicas reports the value actually in effect,
which SHOW CREATE DATABASE cannot always show.


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

This commit allows updating `DatabaseReplicated` settings via `ALTER
DATABASE ... MODIFY SETTING ...` query.

1. Split settings into mutable and immutable:
    a. `default_replica_path`, `default_replica_shard_name` and
    `default_replica_name` are immutable because they're consulted only on
    the database creation.
    b. `internal_replication` is immutable since changing it in realtime
    may result in inconsistent query results.
2. `logs_to_keep` is updated in Keeper. May be updated even if the
   metadata on disk update fails. The Keeper is the source of truth for
   this setting and there's no obvious way to guarantee atomicity of
   publishing the settings, so if the metadata on disk update fails, the
   corresponding message is attached to the root cause exception. A new
   failpoint is added to verify behavior in this exact case.
3. Worker fetches `logs_to_keep` on every entry cleanup request along
   with the `max_log_ptr` so the number of requests to Keeper does not
   change.
4. `db_settings` is stored in the `MultiVersion` container to
   synchronize concurrent readers and a writer.
5. `metadata_mutex` is used to synchronize writers.
6. If the `collection_name` setting changed, the cached cluster objects
   are invalidated and rebuilt on the next request. `mutex` is used to
   synchronize access to the cluster objects.
7. `logs_to_keep` column added to the `system.database_replicas` table,
   sourced from the Keeper node to provide the real value of the
   setting.
8. Old settings values are not compared to the new ones - any new value
   is considered a change. This allows setting the already used named
   collection's name to reload the collection's contents and update
   cluster credentials.
@mintlify

mintlify Bot commented Sep 1, 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 9, 2026, 10:09 AM

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [24d4b3f]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb

AI Review

Summary

Reviewed #117544 at 24d4b3f2b3cadb60fce08cc19abf80f30e332a63, including all prior discussion. The PR adds live replica-local settings changes for Replicated databases and exposes effective logs_to_keep. One existing Major remains: credential reload does not reach existing Distributed background-insert queues.

Findings

⚠️ Majors

  • src/Databases/DatabaseReplicated.cpp:3032: Credential changes leave background-insert pools stale. Clearing the database's two cached clusters does not invalidate the queues and connection pools cached by StorageDistributed::getDirectoryQueue at src/Storages/StorageDistributed.cpp:2079. Their refresh requires an increased Context::getClustersVersion and changed addresses; this ALTER never advances that version. SYSTEM FLUSH DISTRIBUTED also uses the existing queues directly. Consequently, correcting or rotating credentials can make fresh cluster queries succeed while pending and subsequent asynchronous inserts continue failing authentication with the old credentials. Propagate credential invalidation to existing queues, including pending work. Include cluster_secret in the invalidation identity: Cluster::Address::tuple omits it, so a version bump alone still misses secret-only changes. This remains covered by the existing inline finding; no duplicate comment was posted.
Tests
  • ⚠️ 05443_alter_database_replicated_collection_name_access exercises fresh clusterAllReplicas connections, but never creates a background-insert queue. Add focused stateless coverage that creates a queue before credential rotation, retains a pending row, changes collection_name, and verifies that flushing both pending and subsequent inserts succeeds. Cover secret-only rotation as well.
Missing context / blind spots
  • ⚠️ No local build or server binary is available, so runtime tests and the earlier thread's reproduction were not rerun. The remaining finding is independently confirmed by the current cache-refresh and flush paths.
Final Verdict

Status: ⚠️ Request changes. Refresh existing asynchronous-insert pools when database credentials change and add the focused regression coverage above. No additional inline findings were identified.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Sep 1, 2026
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 24d4b3f2b with master 8a8d2e477 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 627ab6805; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

12 object files changed (+68.30 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseReplicated.cpp.o 1.29 MiB 1.33 MiB +45.89 KiB (+3.48%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

34 translation units recompiled, 317 s compile time in total, 34 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -15.5 s (-5%) in total before that adjustment.

Job report

@zlareb1

zlareb1 commented Sep 2, 2026

Copy link
Copy Markdown
Member

Two findings from a review. The first is rig-verified both ways on this PR's CI binary (26.9.1.1, pr/build_arm_release, head 93b3e66).

1. The new upper-bound check blesses values that invert the setting's semantics through UInt32 wraparound: logs_to_keep = 4294967295 makes every fully caught-up replica "lost" on every restart, forever.

The validation added in DatabaseReplicated::applySettingsChanges rejects only values above std::numeric_limits<UInt32>::max(), and its message states that anything up to that bound has the intended meaning ("DDL log entry numbers are 32-bit, so a larger value cannot have the intended meaning"). But both consumers of the Keeper value add in pure 32-bit arithmetic:

  • DatabaseReplicatedDDLWorker::canRemoveQueueEntry: entry_number + logs_to_keep < max_log_ptr — entry_number, logs_to_keep, max_log_ptr are all UInt32 (DatabaseReplicatedWorker.cpp:812-816).
  • initializeReplication: bool lost_according_to_log_ptr = our_log_ptr + logs_to_keep < max_log_ptr; — again all UInt32 (DatabaseReplicatedWorker.cpp:199-234).

With logs_to_keep = 4294967295 (a natural "keep everything forever" attempt, and exactly the maximum the new check permits), x + 4294967295 is x - 1 modulo 2³². So canRemoveQueueEntry returns true for every entry — the cleanup thread prunes the entire DDL log — and lost_according_to_log_ptr is true even when our_log_ptr == max_log_ptr, so every replica runs a full recoverLostReplica on every restart and every Keeper session expiry, permanently. The exact opposite of the requested behavior, silently, and now reachable at runtime on a live database through the statement this PR adds. Any value where entry_number + logs_to_keep can reach 2³² misbehaves proportionally.

Rig on the PR-head binary, single replica, embedded Keeper, pure defaults: create ENGINE = Replicated database, three CREATE TABLE plus one insert (our_log_ptr = max_log_ptr = 4), then a clean stop/start.

Control arm (ALTER DATABASE rdb MODIFY SETTING logs_to_keep = 1500): zero occurrences of Replica seems to be lost after restart.

Fault arm (ALTER DATABASE rdb MODIFY SETTING logs_to_keep = 4294967295 — accepted): after the same clean restart,

<Warning> DDLWorker(rdb): Replica seems to be lost: our_log_ptr=4, max_log_ptr=4, local_digest=932013832505251514, zk_digest=932013832505251514

— a replica that is provably byte-identical to the Keeper state (equal pointers, equal digests) is declared lost and recovered, and this repeats on every subsequent restart.

The wrapping comparisons pre-date this PR (a CREATE-time SETTINGS logs_to_keep = ... could already seed such a value), but the PR adds the validation whose bound advertises these values as meaningful and makes the value settable on a live database, so it seems worth fixing here: either compute both comparisons in UInt64, or tighten the new bound so that entry_number + logs_to_keep cannot reach 2³².

2. Minor: a new data race on cluster_auth_info.

Before this PR, cluster_auth_info was written once in the constructor. Now applySettingsChanges mutates it at runtime under mutex (DatabaseReplicated.cpp:2815), but the Keeper-reconnect path reads cluster_auth_info.cluster_secure_connection without any lock in tryConnectToZooKeeperAndInitDatabase (DatabaseReplicated.cpp:707) and createReplicaNodesInZooKeeper (DatabaseReplicated.cpp:931). Both are reachable after startup — DatabaseReplicatedDDLWorker::initializeMainThread re-runs the connect path whenever the Keeper session expires — concurrently with ALTER DATABASE ... MODIFY SETTING collection_name (which is not gated on readonly). Functional harm is near nil since host_id_default is also checked, but it is TSan-visible; reading the field under the same mutex (or making it atomic) would close it.

@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 4, 2026
1. Clamp when `logs_to_keep` is read on cleanup.
2. Clamp when `logs_to_keep` is read for the status response.
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
Comment thread src/Databases/DatabaseReplicated.cpp Resolved

cluster_auth_info->moveCredsFrom(std::move(*new_cluster_auth_info));

setClusterLocked(nullptr, false);

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.

[Major] Refresh existing Distributed background-insert pools on credential changes

Clearing these two cluster pointers leaves another credential cache intact: StorageDistributed::getDirectoryQueue caches a DistributedAsyncInsertDirectoryQueue and its connection pool. It rebuilds them only when Context::getClustersVersion advances and the addresses change; this ALTER does not advance that version. Queue names contain only shard/replica indexes, so subsequent inserts reuse the same queue with the old credentials.

Reproduced with this head's Fast test binary: create a queue using a collection with an incorrect password, stop background sends and enqueue a row, then switch collection_name to a collection with the correct password. The ALTER succeeds and clusterAllReplicas connects successfully, but SYSTEM FLUSH DISTRIBUTED still returns AUTHENTICATION_FAILED. Inserting another row and flushing fails again; the target remains empty. Thus ordinary asynchronous inserts cannot pick up corrected or rotated credentials without rebuilding the table's queue.

Please propagate credential invalidation to existing queue pools, including pending work, and add a stateless regression that creates the queue before the ALTER. Include cluster_secret in the invalidation identity: merely bumping the global version still misses secret-only rotations because Cluster::Address::tuple excludes it.

This branch was successfully deployed

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

Labels

comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow to alter DatabaseReplicate settings

2 participants