Skip to content

Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when max_replicated_logs_to_keep = 0 - #117147

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-replicated-max-logs-to-keep-zero-oob
Sep 1, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-replicated-max-logs-to-keep-zero-oob

Conversation

@groeneai

@groeneai groeneai commented Aug 30, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a server crash in the ReplicatedMergeTree cleanup thread for tables that set max_replicated_logs_to_keep = 0. The thread read one element past the end of the list of ZooKeeper /log entries, and that aborts the process because the bounds assertion of std::vector is enabled in release builds too. max_replicated_logs_to_keep = 0 is now rejected, which matches the documented domain of the setting.

Description

Found by the fuzzer; no open issue matches this signature.

A table with max_replicated_logs_to_keep = 0 takes the whole server down once its cleanup thread runs. The threshold entry is indexed as entries.size() > N ? entries.size() - N : 0, which for N == 0 yields entries.size(), one past the end. Release builds abort too, because cmake/cxx.cmake selects _LIBCPP_HARDENING_MODE_FAST.

The documented domain is "Any positive integer", so following review the declaration enforces it: the setting becomes NonZeroUInt64, like 13 other MergeTree settings. The field type rejects 0 wherever the value is assigned, so CREATE, ALTER TABLE ... MODIFY SETTING, an ATTACH carrying a full definition, the <merge_tree> config section and loading a table from existing metadata are all covered. sanityCheck reaches none of the last three, since it runs only for mode <= LoadingStrictnessLevel::CREATE. With 0 unrepresentable the indexing expression is master's again and needs no clamp, and the BuzzHouse range for the setting moves to the non-zero one its siblings use.

One consequence: a table whose stored metadata already holds 0 now fails to attach with BAD_ARGUMENTS. That is the existing contract of every NonZeroUInt64 setting, and such a table currently aborts the server from a background thread on every cleanup round instead.

05053_replicated_max_logs_to_keep_zero asserts the three SQL-reachable rejections and that a positive value is still stored. On an unpatched server all three rejection assertions flip and the test fails; with the change it passes 50 consecutive runs.

I also noticed that markLostReplicas indexes multi_responses.responses[0] unguarded: a different mechanism, absent from this stack, no reproducer, so I left it alone.


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

Version info

  • Merged into: 26.9.1.496-master (included in 26.9 and later)

groeneai and others added 3 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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex). 6 findings over three cold reviews
and three gate passes, 2 fix rounds.

# Sev Finding Verdict Evidence / action
1 ❌ The test passed its ZooKeeper path through a shell variable, which ci/jobs/scripts/check_style/various_checks.sh rejects, so Style check would have failed AGREE, fixed That checker emitted exactly one line over the whole tree and it named this file. The literal path is now inlined, as in 01396_inactive_replica_cleanup_nodes_zookeeper.sh, and the checker is clean, re-verified against a control that reintroduces the defect so the clean result cannot be a silent no-op
2 ⚠️ The test never observed the clamped threshold: with one always-active replica the value's only consumer is unreachable, so an entries[0] mutant passed too AGREE, fixed A detached second replica plus one is_lost assertion per replica, which also makes the log trim itself depend on which entry was chosen. The entries[0] mutant was built and measured to fail both threshold-dependent lines while both threshold-independent ones held. markLostReplicas runs strictly before the log removals, and the only path that skips it also skips every removal, so an observed trim implies the is_lost values are already settled
3 ⚠️ The wait stopped on the /log child count alone and then read the replica's log pointer once, so it could finish one pointer step early AGREE, fixed /log reaches one child as soon as the pointer reaches entries - 1, which admits 7 while the read demanded 8, and nothing orders the pointer write against the removal transaction. Both conditions are now polled and latched. The losing state was then forced with SYSTEM STOP PULLING REPLICATION LOG: the old form left the wait at once and printed 0, the new form stayed in it and left only after the pointer advanced
4 ⚠️ The changelog category should be Critical Bug Fix because the process aborts DISAGREE That category is not selected without an explicit request from a maintainer of this repository, and Bug Fix (user-visible misbehavior in an official stable release) is independently correct: cmake/cxx.cmake selects _LIBCPP_HARDENING_MODE_FAST for every non-debug build, _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS is enabled in that mode, and the expression predates the 2020 move of dbms/ to src/
5 💡 The description called KeeperSnapshotManager.cpp:454 the only other site with this shape, but a plain grep also matches Parquet/Decoding.cpp:1972 AGREE, fixed That site's count is sizeof(T), a compile-time non-zero constant, so it is not a carrier. The sentence now reads "the only other place where that count comes from a setting"
6 💡 The test number 05053 is also taken by a test that reached master while this branch was open AGREE, not acted on Cosmetic: the filenames differ, git merge-tree reports no conflict, no style check covers duplicate prefixes, and master already carries a duplicate 05051 pair. Renaming would not durably remove the race either. Left as is, and a one-line change if a reviewer prefers otherwise

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Also noticed and deliberately left alone: markLostReplicas indexes multi_responses.responses[0]
without a guard. Different mechanism, absent from this stack, no reproducer, so it is not patched
speculatively.

Session id: cron:clickhouse-review-slot-8:20260830-113700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE ... ENGINE = ReplicatedMergeTree with SETTINGS max_replicated_logs_to_keep = 0, min_replicated_logs_to_keep = 1, cleanup_delay_period = 0, cleanup_thread_preferred_points_per_iteration = 0, then a few inserts: the server aborts within seconds. Shipped as 05053_replicated_max_logs_to_keep_zero; every unpatched run aborted, so it is not a low-rate flake.
b Root cause explained? Yes. max_replicated_logs_to_keep is UInt64 with no lower bound, so 0 is accepted. The threshold index was entries.size() > N ? entries.size() - N : 0; the guard exists to stop the subtraction underflowing, but for N == 0 it admits the subtraction and yields entries.size(), one past the end, so libc++'s hardened operator[] calls __libcpp_verbose_abort and the process dies in the cleanup thread.
c Fix matches root cause? Yes: the arithmetic is made total at the site that computes it, not guarded at the crash point. Rejecting 0 at validation cannot retire the read, because sanityCheck runs only at LoadingStrictnessLevel::CREATE, so a table whose metadata already holds 0 would still abort on ATTACH and at startup.
d Test intent preserved / new tests added? New test 05053_replicated_max_logs_to_keep_zero.sh. It observes /log trimming down to min_replicated_logs_to_keep, which is strictly downstream of the aborting read, and it polls a second observable in the same loop: that the active replica's log pointer passed the 8 inserted entries. Both are latched, so the reference pins "one child after a trim" rather than "one child", and the wait cannot end one pointer step early on a trim that is already visible. A second, detached replica puts the threshold's only consumer on the executed path and adds one is_lost assertion per replica, so the test discriminates which entry the threshold names rather than only the absence of a crash. No existing test weakened, removed or re-tagged.
e Both directions demonstrated? Yes, on three Build-ID-verified binaries running the same final test. Unpatched: test FAIL, ch-guard scope exited with code 134, libc++ Hardening assertion __n < size() failed: vector[] index out of bounds, and clearOldLogs in the fatal stack, frame-for-frame identical to the CI stack, with the fatal header's own build id matching the unpatched binary. Patched: 50 tests passed. 0 tests skipped. with randomization on, min 2.23 s, median 3.79 s, max 3.95 s. Third arm, to show the test is not vacuous: a binary differing only in that the threshold reads entries[0], which is in bounds and therefore does not abort, fails the test on both threshold-dependent assertions (/log never trims, the detached replica is never marked lost) while both threshold-independent assertions still hold. Fourth arm, for the wait itself: SYSTEM STOP PULLING REPLICATION LOG holds the log pointer one step short while a further insert lets the cleanup thread trim /log to a single child, and on that state a wait keyed on the child count alone reports the pointer assertion as 0, whereas the shipped two-observable wait stays in the loop and passes once the pointer advances.
f Fix is general across code paths? Yes. Swept all 8794 .cpp/.h/.hpp/.cc files under src/ for the size() > N ? ... - N : 0 shape. Exactly one true carrier, fixed here. The one structurally identical site, KeeperSnapshotManager.cpp:454 with snapshots_to_keep, was read at its site: already excluded from the zero case by if (!existing_snapshots.empty() && snapshots_to_keep > 0). The other two matches use a compile-time non-zero count or no subtraction. min_saved_record_log_str has exactly one consumer, so the blast radius is that one comparison.
g Fix generalizes across inputs (params/datatypes/wrappers)? The input is a single UInt64 setting, not a column, so no type wrappers apply and the domain was enumerated instead: size in 1..40 against N in 0..45 plus N = UINT64_MAX, comparing the old and new expressions transcribed from the patched source. Zero divergences for every N >= 1; the old form is out of bounds in exactly the 40 N == 0 cases; the new form never is. entries.size() >= 1 is guaranteed by the entries.empty() return above.
h Backward compatible? (maintainer-approved exception only) Yes, and no exception is needed. No setting is added, renamed or re-defaulted, so no SettingsChangesHistory.cpp row. Behaviour is bit-identical for every documented value ("Any positive integer"); only 0, which is undocumented and previously aborted the server, changes meaning. No format or serialization change.
i Invariants and contracts preserved? Yes. The invariant is that min_saved_record_log_str must name a /log entry that exists, since it is compared against replicas' log pointers at the single consumer; it now holds on the whole UInt64 domain instead of all-but-zero. The value is still a String by value, so the later entries.erase calls cannot dangle. No locking, ordering or ZooKeeper batching changed. On the N == 0 path the threshold errs toward the newest entry, i.e. toward not marking a replica lost, which is the safe direction since marking one lost forces a full re-clone. Verified empirically: for max_replicated_logs_to_keep of 10 and of 1000000, whether a detached replica gets marked lost is identical on the patched and unpatched binaries.

Session id: cron:clickhouse-impl-slot-5:20260830-105300

@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4401a1a]

Summary: ❌

job_name test_name status info comment
Docs examples FAIL
Documentation examples FAIL cidb IGNORED
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL IGNORED
Bugfix validation (functional tests, amd64) ERROR IGNORED
Bugfix validation (functional tests, aarch64) ERROR IGNORED

AI Review

Summary

This PR fixes the fresh-input paths for max_replicated_logs_to_keep = 0 by declaring the setting as NonZeroUInt64, so CREATE, full-definition ATTACH, and ALTER ... MODIFY SETTING now reject 0. The remaining problem is that the same type change also rejects previously accepted on-disk metadata and server config during upgrade, so the fix is not backward-compatible as written.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeSettings.cpp:1325] [dismissed by author -- https://github.com/Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when max_replicated_logs_to_keep = 0 #117147#discussion_r3903068327] Turning max_replicated_logs_to_keep into NonZeroUInt64 applies the new validation to existing state, not just fresh SQL. That means an existing <merge_tree> / <replicated_merge_tree> config with 0 now fails during startup, and a table created by an older server with stored max_replicated_logs_to_keep = 0 no longer attaches when its metadata is replayed. This is a backward-incompatible upgrade path for a setting that older releases accepted.
    Suggested fix: keep rejecting 0 on fresh user input (CREATE, full-definition ATTACH, ALTER), but preserve load-time compatibility for existing config / metadata by keeping the runtime clamp in clearOldLogs or an equivalent legacy-load path.
Final Verdict

Status: ❌ Block

Minimum required action: preserve compatibility for previously accepted stored/configured 0 values while still rejecting new ones from fresh user input.

LLVM Coverage Report

Measured on commit 4401a1a.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 80.90% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @alesapin, could you review this? clearOldLogs indexes the log threshold as entries.size() > N ? entries.size() - N : 0, so max_replicated_logs_to_keep = 0 passes the guard and reads one past the end, and the libc++ bounds assertion is enabled in release builds too. The fix clamps the kept count to at least one, which is bit-identical for every documented value of the setting.

@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4401a1a33 with master 8bbf2a548 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ef510b2203edc68a0e0a0bc712f7135ae99f4dc6

CI has finished on this head. Every failure below has an owner: a fixing PR, or a full-effort fix
task whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Cannot start clickhouse-server CI harness on master, not this diff: tests/config/install.sh:148 links silk.xml unconditionally, so the previous-release server rejects enable_silk_runtime with Code: 137 ... UNKNOWN_ELEMENT_IN_CONFIG and never starts #117172 (ours, open)
Upgrade check (amd_release) / Check failed the same job-level abort row as above, sharing one task_url; not an independent failure #117172 (ours, open)

The Upgrade check condition is fleet-wide and started at a clean cliff on 2026-08-30 13:48:57Z,
80 seconds after v26.8.1.2041-lts was published and became the previous release. It has since hit
more than 40 distinct unrelated PRs and zero true-master runs, so it is not attributable to any PR
that carries it. Counts are given rather than PR links to avoid cross-referencing unrelated PRs.

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117147&sha=ef510b2203edc68a0e0a0bc712f7135ae99f4dc6&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29

Session id: cron:our-pr-ci-monitor:20260830-180000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger: 3bbddc8

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) job-budget overrun, no failing test: Job timed out ... timeout [9000], exit code [-15] after 11827 of 13374 tests, every reported test OK #116209 (ours, open)

LLVM Coverage is DROPPED as that job's cascade, and says so itself: Dropped due to previous failure [Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel)]. Same owner.

This PR's own new test ran in that shard at position 3906 of 13374 and passed in 16.55 s, against a
slowest-test figure of 459 s, so it is not what exhausted the budget. #116209 records 12 at-cap runs
on this shard in 90 days.

Session id: cron:our-pr-ci-monitor:20260831-093000

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai max_replicated_logs_to_keep = 0 shouldn't be allowed

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed, and the documented domain already says so: the description of max_replicated_logs_to_keep in MergeTreeSettings.cpp reads "Possible values: - Any positive integer". I am adding that bound to MergeTreeSettingsImpl::sanityCheck, next to the existing index_granularity and shared_merge_tree_range_for_merge_window_size checks.

I would keep the clamp in the cleanup thread as well, because sanityCheck only guards two of the paths that can set the value. It runs on CREATE (MergeTreeData.cpp:788, mode <= LoadingStrictnessLevel::CREATE) and on ALTER TABLE ... MODIFY SETTING (MergeTreeData::changeSettings, where run_sanity_checks defaults to true). ATTACH and server startup (FORCE_ATTACH), RESTORE and the secondary CREATE of a Replicated database (SECONDARY_CREATE, InterpreterCreateQuery.cpp:1732) all skip it, so a table that already carries 0, or an explicit ATTACH TABLE ... SETTINGS max_replicated_logs_to_keep = 0, still reaches entries[entries.size()]. That read aborts in release builds too, not only under sanitizers: vector::operator[] guards it with _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS, which _LIBCPP_HARDENING_MODE_FAST enables (cmake/cxx.cmake:5), and the caller is a background thread, so the process aborts rather than one query failing.

The regression test has to move for the same reason: it currently creates the table with 0, which the new check rejects, so it becomes an explicit ATTACH carrying the setting (same shape as 04062_table_readonly_replicated.sh). I will push all three changes shortly. Say so if you would rather have the validation alone and no clamp.

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.
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed as 34543f5.

MergeTreeSettingsImpl::sanityCheck now rejects max_replicated_logs_to_keep < 1, next to the index_granularity bound. Measured: both CREATE ... SETTINGS max_replicated_logs_to_keep = 0 and ALTER TABLE ... MODIFY SETTING max_replicated_logs_to_keep = 0 fail with BAD_ARGUMENTS. No other test in the tree sets the value below 1 and clickhouse-test does not randomize it, so nothing else is affected.

The clamp in the cleanup thread stays, and the test now covers both halves. With only the clamp reverted the server still aborts with vector[] index out of bounds in clearOldLogs once the value arrives through an ATTACH with a full definition, which is also why the reproduction moved off CREATE: the new check rejects it there. 50 of 50 runs pass.

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.
@PedroTadim PedroTadim self-assigned this Sep 1, 2026
@PedroTadim
PedroTadim enabled auto-merge September 1, 2026 14:05
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4401a1a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, aarch64) job-level abort before any server starts: AssertionError: Could not find master builds in S3 at ci/jobs/functional_tests.py:734, so nothing was validated and no test is attributed #117433 (mine, open)
Bugfix validation (functional tests, amd64) same Could not find master builds in S3 abort as the row above #117433 (mine, open)
Finish Workflow / Post Hooks workflow_hooks/new_tests_check.py reads the two Bugfix validation results above and fails on their ERROR state, so it is downstream of the same defect #117433 (mine, open)
Docs examples / Documentation examples the toYYYYMM documentation example pinned its own output to 202608, so SELECT toYYYYMM(now(), 'US/Eastern') started returning 202609 at 2026-09-01 00:00 America/New_York and the check now fails on master and on 158 pull requests #117459 (mine, merged 2026-09-01), absent from this tree

Session id: cron:our-pr-ci-monitor:20260901-173000

@PedroTadim
PedroTadim added this pull request to the merge queue Sep 1, 2026
Merged via the queue into ClickHouse:master with commit 1d58ae0 Sep 1, 2026
170 of 175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 1, 2026
@PedroTadim PedroTadim added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 2, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 2, 2026
robot-clickhouse added a commit that referenced this pull request Nov 2, 2026
…geTree cleanup thread when `max_replicated_logs_to_keep = 0`
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 2, 2026
Backport #117147 to 26.8: Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when `max_replicated_logs_to_keep = 0`
PedroTadim added a commit that referenced this pull request Nov 2, 2026
Backport #117147 to 26.3: Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when `max_replicated_logs_to_keep = 0`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…geTree cleanup thread when `max_replicated_logs_to_keep = 0`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…geTree cleanup thread when `max_replicated_logs_to_keep = 0`
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants