Repository navigation
Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when max_replicated_logs_to_keep = 0 - #117147
Conversation
… 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.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex). 6 findings over three cold reviews
Severity: ❌ blocker / Also noticed and deliberately left alone: Session id: cron:clickhouse-review-slot-8:20260830-113700 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260830-105300 |
|
Workflow [PR], commit [4401a1a] Summary: ❌
AI ReviewSummaryThis PR fixes the fresh-input paths for Findings❌ Blockers
Final VerdictStatus: ❌ Block Minimum required action: preserve compatibility for previously accepted stored/configured LLVM Coverage ReportMeasured on commit 4401a1a.
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
|
cc @CheSema @alesapin, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 25 s compile time in total, 8 of them have a recent master baseline. |
CI finish ledger -
|
| 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.
Session id: cron:our-pr-ci-monitor:20260830-180000
CI finish ledger: 3bbddc8Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
This PR's own new test ran in that shard at position 3906 of 13374 and passed in 16.55 s, against a Session id: cron:our-pr-ci-monitor:20260831-093000 |
|
@groeneai |
|
Agreed, and the documented domain already says so: the description of I would keep the clamp in the cleanup thread as well, because The regression test has to move for the same reason: it currently creates the table with |
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.
|
Pushed as
The clamp in the cleanup thread stays, and the test now covers both halves. With only the clamp reverted the server still aborts with |
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.
CI finish ledger - 4401a1aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260901-173000 |
1d58ae0
…geTree cleanup thread when `max_replicated_logs_to_keep = 0`
Backport #117147 to 26.8: Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when `max_replicated_logs_to_keep = 0`
Backport #117147 to 26.3: Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when `max_replicated_logs_to_keep = 0`
…geTree cleanup thread when `max_replicated_logs_to_keep = 0`
…geTree cleanup thread when `max_replicated_logs_to_keep = 0`
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a server crash in the
ReplicatedMergeTreecleanup thread for tables that setmax_replicated_logs_to_keep = 0. The thread read one element past the end of the list of ZooKeeper/logentries, and that aborts the process because the bounds assertion ofstd::vectoris enabled in release builds too.max_replicated_logs_to_keep = 0is now rejected, which matches the documented domain of the setting.Description
Found by the fuzzer; no open issue matches this signature.
4806-4fa5, checkBuzzHouse (amd_tsan), commitb5b3a8d8703016e124272adadf4d0d516cc9ce53libc++ Hardening assertion __n < size() failed: vector[] index out of boundsinstd::vector<String>::operator[], fromReplicatedMergeTreeCleanupThread::clearOldLogsA table with
max_replicated_logs_to_keep = 0takes the whole server down once its cleanup thread runs. The threshold entry is indexed asentries.size() > N ? entries.size() - N : 0, which forN == 0yieldsentries.size(), one past the end. Release builds abort too, becausecmake/cxx.cmakeselects_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 rejects0wherever the value is assigned, soCREATE,ALTER TABLE ... MODIFY SETTING, anATTACHcarrying a full definition, the<merge_tree>config section and loading a table from existing metadata are all covered.sanityCheckreaches none of the last three, since it runs only formode <= LoadingStrictnessLevel::CREATE. With0unrepresentable the indexing expression is master's again and needs no clamp, and theBuzzHouserange for the setting moves to the non-zero one its siblings use.One consequence: a table whose stored metadata already holds
0now fails to attach withBAD_ARGUMENTS. That is the existing contract of everyNonZeroUInt64setting, and such a table currently aborts the server from a background thread on every cleanup round instead.05053_replicated_max_logs_to_keep_zeroasserts 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
markLostReplicasindexesmulti_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
26.9.1.496-master(included in26.9and later)