Skip to content

Cherry pick #117147 to 26.3: Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when max_replicated_logs_to_keep = 0 - #128613

Merged
PedroTadim merged 7 commits into
backport/26.3/117147from
cherrypick/26.3/117147
Nov 2, 2026
Merged

PedroTadim merged 7 commits into
backport/26.3/117147from
cherrypick/26.3/117147

Conversation

@robot-clickhouse-ci-1

Copy link
Copy Markdown
Contributor

Original pull-request #117147

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 7 commits August 30, 2026 08:48
… max_replicated_logs_to_keep = 0

`ReplicatedMergeTreeCleanupThread::clearOldLogs` picked the log-retention threshold with
`entries[entries.size() > N ? entries.size() - N : 0]`, where `N` is
`max_replicated_logs_to_keep`. The guard is there to stop the subtraction underflowing, and it
does, but for `N == 0` it admits the subtraction and yields `entries.size()` itself: one past
the end of a non-empty vector. libc++'s hardened `operator[]` then calls
`__libcpp_verbose_abort` and the whole server process dies, from a background thread, with no
query in flight.

`max_replicated_logs_to_keep` is declared as a `UInt64` with no lower bound, so `0` is an
accepted value even though the documentation says "Any positive integer". This is not
debug-only either: `cmake/cxx.cmake` selects `_LIBCPP_HARDENING_MODE_FAST` for every non-debug
build, and `_LIBCPP_ASSERT_VALID_ELEMENT_ACCESS`, the check at `__vector/vector.h:412`, is
enabled in that mode, so a release build aborts as well.

Found by the fuzzer, STID 4806-4fa5, check `BuzzHouse (amd_tsan)`, commit
b5b3a8d:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110073&sha=b5b3a8d8703016e124272adadf4d0d516cc9ce53&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29
Exactly one of that run's twenty replicated tables carried the value, and the server aborted in
`clearOldLogs`. There is no open issue for this signature.

The threshold count is now clamped to at least one and the index computed as
`entries.size() - std::min(kept, entries.size())`, the idiom already used two statements later
at the `entries.erase` call and in `clearOldBlocks`. Enumerating both expressions over `size` in
1..40 against `N` in 0..45, plus `N` = `UINT64_MAX`, they agree on every `N >= 1`; the old form
is out of bounds in exactly the forty `N == 0` cases and the new one never is. So behaviour is
bit-identical across the documented domain, and the only value whose meaning changes is `0`,
which previously aborted the server and now keeps the newest entry.

Clamping is the right reading of `0` rather than treating it as "no limit":
`KeeperSnapshotManager` handles `snapshots_to_keep == 0` as literal zero, and the threshold has
to name an entry that exists, because its single consumer compares replicas' log pointers
against it to decide whether an inactive replica is lost. Stopping one entry short errs toward
not marking a replica lost, which is the safe direction, since marking one lost forces a full
re-clone.

Fixing the arithmetic rather than rejecting `0` at validation is deliberate.
`MergeTreeData` runs `sanityCheck` only at `LoadingStrictnessLevel::CREATE`, so a table whose
metadata already holds `0` would keep aborting on `ATTACH` and at server startup no matter what
validation rejects at creation time.

The new test drives the cleanup thread on a single-replica table with the setting at `0` and
waits for `/log` to be trimmed down to `min_replicated_logs_to_keep`. The trim happens strictly
after the threshold is computed, so observing it proves the thread walked through the read that
used to abort; the test also asserts that at least the eight inserted entries had reached `/log`,
so the expected single remaining child is the result of a trim and not of a log that was never
longer. Without this change the test takes the server down with the stack above; with it, the
test passes 50 consecutive randomized runs.

Co-Authored-By: Claude Opus 5 <[email protected]>
…d fix its ZooKeeper path style

The test passed its ZooKeeper path through a shell variable, which
`ci/jobs/scripts/check_style/various_checks.sh` cannot see: it requires the literal
`$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX` token on the same line as the `Replicated...MergeTree(`
call, so `Style check` reported the file. The path is now written out at each use site and the
resolved string is unchanged.

The test also could not tell which `/log` entry the retention threshold names.
`min_saved_record_log_str` is read at one place only, in the branch for a replica that has no
`is_active` node and whose `is_lost` is `0`, and the test had a single, permanently active
replica, so that read was never reached: a threshold of `entries[0]`, which is in bounds and
therefore does not abort, would have passed just as well. A second replica is now created on the
same path and detached before the inserts, and `is_lost` is asserted for both replicas.

That makes both observables depend on the threshold. With the clamp, the detached replica
compares stale, is marked lost, and `/log` is trimmed to one child. With a threshold of
`entries[0]` the replica compares fresh, `min_saved_log_pointer` collapses to zero, the
`lower_bound` erase empties the removal list, and `clearOldLogs` returns before
`markLostReplicas`: `/log` is never trimmed and the replica is never marked lost, so the test
fails on both counts.

No source change.

Co-Authored-By: Claude Opus 5 <[email protected]>
The wait left the poll as soon as `/log` held a single child and only then read
`log_pointer >= 8`, once. The two are not coupled, so the assertion could be
evaluated one pointer step early and print 0.

With `M` the highest `/log` index present and `k` the active replica's log
pointer as `ReplicatedMergeTreeCleanupThread::clearOldLogs` reads it, the
threshold is `entries[E-1]`, the trim then drops the newest
`min_replicated_logs_to_keep` entry and everything below `log-<k>`, so `/log`
reaches one child exactly when `k >= M`. For `M` of 7 that admits `k` of 7,
which is one short of the eight inserted entries the assertion names. Nothing
serialises the two: `log_pointer` is written by the queue updater in its own
multi, and the removal multi guards only the `/replicas` node version and lost
replicas' `/host` versions, neither of which a pointer write bumps.

Both conditions are now polled in one loop with latched flags, and the loop
leaves only once each has been seen. That is strictly stronger than the one-shot
read: the pointer is monotonically non-decreasing for a replica that is never
marked lost, which the `is_lost` line for replica `1` asserts, and `/log` can
rise above one child again once a merge entry is logged. Each read keeps its own
return-code and numeric guard so a failed or empty read cannot latch a flag.

Confirmed by forcing the state rather than waiting for it:
`SYSTEM STOP PULLING REPLICATION LOG` holds the pointer at 7 while one further
insert makes `log-7` the newest entry, and on that state the previous form
reports the pointer assertion as 0 while this form stays in the loop and passes
once the pointer advances. The reference is unchanged, and a binary whose
threshold reads `entries[0]` still fails the test on both threshold-dependent
lines while both threshold-independent lines hold.
The setting is documented as accepting any positive integer, but it had no lower
bound, so 0 was accepted. With 0 the cleanup thread indexed entries with
entries.size(), one past the end, and libc++ hardening turns that into an abort
in release builds as well: cmake/cxx.cmake sets _LIBCPP_HARDENING_MODE_FAST for
every non-debug build, and vector::operator[] is guarded there by
_LIBCPP_ASSERT_VALID_ELEMENT_ACCESS. The caller is a background thread, so the
process aborts rather than one query failing.

Reject the value in MergeTreeSettingsImpl::sanityCheck, next to the existing
index_granularity bound. That covers CREATE TABLE and
ALTER TABLE ... MODIFY SETTING, the two paths that call it.

The clamp in the cleanup thread stays, because settings are not checked when a
table is loaded from metadata that already exists: MergeTreeData calls
sanityCheck only for LoadingStrictnessLevel::CREATE, so ATTACH, server startup
(FORCE_ATTACH), RESTORE and the secondary CREATE of a Replicated database
(SECONDARY_CREATE) all skip it. A table created by an older server keeps its
value and still reaches the log threshold computation with 0.

The test asserts both halves: the value is rejected on CREATE and on ALTER, and
the cleanup thread trims /log for a table that carries 0 in through an ATTACH
with a full definition. Reverting only the clamp makes that ATTACH path abort
the server with "vector[] index out of bounds" in clearOldLogs, which is the
signature the fuzzer reported.
Declare the setting as NonZeroUInt64 instead of checking the bound by hand in
MergeTreeSettingsImpl::sanityCheck.

sanityCheck runs only for mode <= LoadingStrictnessLevel::CREATE, so the hand
written bound left 0 reachable through an ATTACH that carries a full definition
and through loading a table whose stored metadata already holds it. The field
type rejects the value wherever it is assigned, so CREATE, ALTER MODIFY SETTING,
ATTACH, the server config and loading existing metadata are all covered, and the
clamp in clearOldLogs is no longer reachable and goes away.

A table whose stored metadata holds 0 now fails to attach with BAD_ARGUMENTS
instead of aborting the server from a background thread.

BuzzHouse generates values for this setting, so its range moves to
highRangeNonZeroSetting, which is what the other NonZeroUInt64 table settings
already use.
…eep-zero-oob

Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when `max_replicated_logs_to_keep = 0`
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Nov 2, 2026
@PedroTadim
PedroTadim merged commit a0918e8 into backport/26.3/117147 Nov 2, 2026
186 of 194 checks passed
@PedroTadim
PedroTadim deleted the cherrypick/26.3/117147 branch November 2, 2026 12:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants