#122377·ClickHouse

Clamping logs_to_keep to UInt32::max breaks old replicas during rolling upgrade

Author: clickgapaiCreated Sep 26, 2026Updated Sep 29, 2026
Labelscomp-database-engines

Describe what's wrong

  • A Replicated database created on a patched server writes 4294967295 for logs_to_keep into Keeper.
  • Trigger: rolling upgrade with database_replicated.logs_to_keep above UInt32::max, or a RESTORE of an old backup.
  • Old replicas wrap this in 32-bit arithmetic and delete the whole DDL log on every cleanup pass.
  • During a rolling upgrade or after rollback this causes silent data loss between replicas.

Root cause: checkOrClampLogsToKeepValue clamps out-of-range values to MAX_LOGS_TO_KEEP (UInt32::max), which DatabaseReplicated::buildDatabaseNodesInZooKeeper persists to Keeper. Unpatched DatabaseReplicatedDDLWorker code evaluates entry_number + logs_to_keep < max_log_ptr in 32-bit arithmetic, so adding 4294967295 wraps and makes the check true for every entry.

Analysis details (evidence, affected locations, impact)

Why we believe this is a bug: Context::getDatabaseReplicatedSettings -> DatabaseReplicatedSettings::loadFromConfig -> checkOrClampLogsToKeepValue sets the value to MAX_LOGS_TO_KEEP (DatabaseReplicatedSettings.cpp:97) -> DatabaseReplicated::buildDatabaseNodesInZooKeeper persists it to <zk_path>/logs_to_keep (DatabaseReplicated.cpp:848-850). An unpatched DatabaseReplicatedDDLWorker reads the node with parse<UInt32> and evaluates entry_number + logs_to_keep < max_log_ptr / our_log_ptr + logs_to_keep < max_log_ptr in 32-bit arithmetic (the lines this PR replaces with isBeyondRetention), so x + 4294967295 wraps to x - 1 and both checks are true for every entry.

Affected locations:

Impact: During the mixed-version window of a rolling upgrade (and after a rollback): DDL log entries are deleted before lagging replicas replay them; unpatched replicas run recoverLostReplica on every re-initialization; the upgraded replica permanently misses the deleted DDL with no digest mismatch to trigger recovery, so replicas diverge (a table exists on one replica only).

Does it reproduce on most recent release?

Yes — confirmed on current master (commit 3349a047fd2e7e).

How to reproduce

Reproduce with a mixed-version cluster (patched node plus 26.5.1.882) sharing a logs_to_keep config above UInt32::max, creating the database on the patched node first.

bash
# A Replicated database created on an upgraded server must stay safe for replicas still on an older release.
import time
import uuid

import pytest

from helpers.cluster import ClickHouseCluster

cluster = ClickHouseCluster(__file__)

# Both servers carry the same legacy `logs_to_keep` default above `UInt32::max`.
node_new = cluster.add_instance(
    "node_new",
    main_configs=["configs/logs_to_keep_overflow.xml"],
    with_zookeeper=True,
    stay_alive=True,
)
node_old = cluster.add_instance(
    "node_old",
    image="clickhouse/clickhouse-server",
    tag="26.5.1.882",
    with_installed_binary=True,
    main_configs=["configs/logs_to_keep_overflow.xml"],
    with_zookeeper=True,
    stay_alive=True,
)

ASYNC_DDL = {"distributed_ddl_task_timeout": 0, "distributed_ddl_output_mode": "none"}

@pytest.fixture(scope="module")
-- def started_cluster():
    -- try:
        cluster.start()
        yield cluster
    -- finally:
        cluster.shutdown()

-- def table_exists(node, db, table, timeout):
    -- for _ in range(timeout * 2):
        -- if node.query(f"EXISTS TABLE {db}.{table}").strip() == "1":
            return True
        time.sleep(0.5)
    return False

-- def log_entries(path):
    return int(
        node_new.query(
            f"SELECT count() FROM system.zookeeper WHERE path = '{path}/log'"
        ).strip()
    )

-- def run_case(creator):
    joiner = node_old if creator is node_new else node_new
    db = f"db_created_by_{creator.name}_{uuid.uuid4().hex[:6]}"
    path = f"/test/{db}"

    creator.query(f"CREATE DATABASE {db} ENGINE = Replicated('{path}', 's1', '{creator.name}')")
    joiner.query(f"CREATE DATABASE {db} ENGINE = Replicated('{path}', 's1', '{joiner.name}')")
    keeper_value = node_new.query(
        f"SELECT value FROM system.zookeeper WHERE path = '{path}' AND name = 'logs_to_keep'"
    ).strip()

    node_old.query(f"CREATE TABLE {db}.t1 (x UInt32) ENGINE = MergeTree ORDER BY x")
    assert table_exists(node_new, db, "t1", 30)

    # The upgraded replica is offline for a moment (e.g. restarting during the rolling upgrade).
    node_new.query(f"DETACH DATABASE {db}")
    node_old.query(
        f"CREATE TABLE {db}.t_missed (x UInt32) ENGINE = MergeTree ORDER BY x",
        settings=ASYNC_DDL,
    )
    entries_before = log_entries(path)

    # A freshly started DDL worker runs one cleanup pass right away.
    node_old.query(f"DETACH DATABASE {db}")
    node_old.query(f"ATTACH DATABASE {db}")
    -- for _ in range(20):
        time.sleep(1)
        -- if node_old.count_in_log(f"DDLWorker({db}): Cleaning queue").strip() not in ("", "0"):
            break
    time.sleep(3)
    entries_after = log_entries(path)
    lost = int(node_old.count_in_log(f"DDLWorker({db}): Replica seems to be lost").strip())

    node_new.query(f"ATTACH DATABASE {db}")
    has_missed_table = table_exists(node_new, db, "t_missed", 30)

    result = {
        "creator": creator.name,
        "keeper_logs_to_keep": keeper_value,
        "log_entries_before_old_cleanup": entries_before,
        "log_entries_after_old_cleanup": entries_after,
        "old_replica_lost_warnings": lost,
        "t_missed_on_node_new": has_missed_table,
    }
    print(result)

    node_new.query(f"DROP DATABASE {db} SYNC")
    node_old.query(f"DROP DATABASE {db} SYNC")
    return result

-- def test_control_database_created_by_old_server(started_cluster):
    r = run_case(node_old)
    assert r["keeper_logs_to_keep"] == "10000000000"
    assert r["log_entries_after_old_cleanup"] == r["log_entries_before_old_cleanup"]
    assert r["old_replica_lost_warnings"] == 0
    assert r["t_missed_on_node_new"]

-- def test_database_created_by_new_server(started_cluster):
    r = run_case(node_new)
    assert r["log_entries_after_old_cleanup"] == r["log_entries_before_old_cleanup"]
    assert r["old_replica_lost_warnings"] == 0
    assert r["t_missed_on_node_new"]

Expected behavior

An old replica should keep all DDL log entries just as it did before the clamp was introduced, matching the previous raw value of 10000000000.

Expected output of the reproducer above:

test_database_created_by_new_server behaves like the control arm:
log_entries_after_old_cleanup == log_entries_before_old_cleanup, old_replica_lost_warnings == 0, t_missed_on_node_new == True

Error message and/or stacktrace

The old replica deletes every DDL log entry on each cleanup pass, logs 'Replica seems to be lost' while fully in sync, and the new replica silently misses DDL executed while it was detached.

Actual output of the reproducer above on master (3349a047fd2e7e):

test_control_database_created_by_old_server PASSED
{'creator': 'node_old', 'keeper_logs_to_keep': '10000000000', 'log_entries_before_old_cleanup': 4, 'log_entries_after_old_cleanup': 4, 'old_replica_lost_warnings': 0, 't_missed_on_node_new': True}
test_database_created_by_new_server FAILED
{'creator': 'node_new', 'keeper_logs_to_keep': '4294967295', 'log_entries_before_old_cleanup': 3, 'log_entrie
Suggested fix

Clamp to a value the overflowing check does not wrap on, e.g. std::numeric_limits<Int32>::max(): it still keeps any realistic DDL log, and entry_number + 2147483647 stays below 2^32 for entry numbers below 2^31, so unpatched replicas treat it as "keep all" too. Trade-off: the effective maximum halves, which no DDL log reaches. Backporting the overflow-safe isBeyondRetention check narrows the exposure but does not cover already-deployed older patch releases.

Additional context

Open risks:

  • An explicit SETTINGS logs_to_keep = 4294967295 (the maximum the new BAD_ARGUMENTS message points users to) writes the same Keeper value, with the same effect on unpatched replicas.
  • RESTORE of an older backup with an out-of-range value writes the same value; the PR's own test_logs_to_keep_restore_of_out_of_range_backup asserts 4294967295 in Keeper.
  • Rollback path not run (see assumptions).

Found during automated review of PR #118103; this finding was not executed, so nobody is tagged. Per git blame, that PR introduced the cited lines (src/Databases/DatabaseReplicatedSettings.cpp:97, src/Databases/DatabaseReplicatedSettings.cpp:56). Severity P2 · Finding h_pr118103_001