Skip to content

Fix signed integer overflow in RefreshTask attempt log_comment - #108005

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-refreshtask-refresh-retries-int64-overflow
Jul 2, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-refreshtask-refresh-retries-int64-overflow

Conversation

@groeneai

@groeneai groeneai commented Jun 20, 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 signed integer overflow when a refreshable materialized view retries a failed refresh with refresh_retries set to a very large value (near Int64 max). The overflow could abort the server in builds with the undefined-behavior sanitizer.

Description

RefreshTask::executeRefresh formats an (attempt N/total) string for the refresh log comment when a refresh retries, where total = refresh_settings[refresh_retries] + 1. refresh_retries is an Int64 setting that accepts any value, so refresh_retries + 1 overflows when it is set to Int64 max. Signed integer overflow is undefined behavior, which UBSan reports and (with -fno-sanitize-recover) turns into a server abort.

The fix computes the total in UInt64 (range [1, 2^63], no overflow) for non-negative refresh_retries, and omits the denominator entirely when refresh_retries is negative (the documented infinite-retries case, which previously printed a meaningless /0).

Found by the UBSan stress test:

RefreshTask.cpp:938:138: runtime error: signed integer overflow: 9223372036854775807 + 1 cannot be represented in type 'long'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior RefreshTask.cpp:938:138

This is a pre-existing trunk bug surfaced during PR #88234's stress run (that PR does not touch RefreshTask).

Added regression test 03981_refreshable_mv_retries_int64_max that creates a refreshable MV with refresh_retries = 9223372036854775807 and a failing refresh, forcing a second attempt through the formatting branch. The test reproduces the abort without the fix and passes with it.

Version info

  • Merged into: 26.7.1.418 (included in 26.7 and later)

When a refreshable materialized view retries a failed refresh, executeRefresh
formats an '(attempt N/total)' string where total = refresh_retries + 1.
refresh_retries is an Int64 setting that accepts any value (including Int64
max), so refresh_retries + 1 overflows for large values, which is undefined
behavior (UBSan: signed integer overflow at RefreshTask.cpp:938).

Compute the total in UInt64 to avoid the overflow, and omit the meaningless
denominator when retries is negative (the documented infinite-retries case,
which previously printed '/0').

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE MATERIALIZED VIEW rmv REFRESH AFTER 1 YEAR SETTINGS refresh_retries = 9223372036854775807 (x Int64) ENGINE Memory AS SELECT throwIf(number = 0) AS x FROM numbers(1) aborts the server 100% of the time on an ASAN+UBSAN build once the second refresh attempt starts. Exact finding: RefreshTask.cpp:938:138: runtime error: signed integer overflow: 9223372036854775807 + 1 (matches CI STID 2962-2bcc).
b Root cause explained? refresh_retries is an Int64 setting accepting any value. On a retry (attempt_number > 1) line 938 computed the display total as refresh_settings[refresh_retries] + 1 in Int64. At Int64 max, + 1 overflows. Signed overflow is UB; with -fno-sanitize-recover UBSan aborts the server.
c Fix matches root cause? Yes. The bad value is a legitimate fuzzed setting value (not upstream corruption), so the fix belongs at this arithmetic site. The total is now computed in UInt64 (static_cast<UInt64>(retries) + 1, range [1, 2^63], no overflow), and the denominator is dropped for negative retries (documented infinite case, previously printed /0).
d Test intent preserved / new tests added? New regression test 03981_refreshable_mv_retries_int64_max exercises exactly this path (retry with refresh_retries = Int64 max). No existing test weakened.
e Both directions demonstrated? Yes. Without the fix: server SIGABRT (exit 134) with the UBSan overflow at RefreshTask.cpp:938:138. With the fix: 5/5 passes (and self-parallel 3x), server alive. Existing 03258_refreshable_mv_misc still passes.
f Fix is general, not a narrow patch? Audited all refresh_settings[...] arithmetic in RefreshTask.cpp: line 1227 is a comparison (no overflow), 849/1239 are guarded decrements; 938 was the only overflow-prone + N. Also covered the second degenerate input (refresh_retries = -1, infinite retries).

Session id: cron:clickhouse-worker-slot-2:20260619-233900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @tuanpach — could you review this? It fixes a signed-integer overflow in RefreshTask::executeRefresh: the (attempt N/total) log comment computed refresh_retries + 1 in Int64, which overflows (UBSan abort) when refresh_retries is set near Int64 max. The total is now computed in UInt64, and the denominator is omitted for the documented infinite-retries case (refresh_retries = -1).

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [07b96e4]

Summary: ✅


AI Review

Summary

This PR fixes the refresh_retries + 1 overflow in RefreshTask by formatting the total attempt count in UInt64, and it adds a focused stateless regression test that drives the second-attempt path with refresh_retries = 9223372036854775807. I did not find a remaining correctness, compatibility, or coverage issue in the current diff.

Final Verdict
  • Status: ✅ Approve

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

Copy link
Copy Markdown
Collaborator Author

CI finished on 8f5bfbdd900. AI Review approved. The two test failures are pre-existing trunk issues, not caused by this PR (a 1-line UInt64 cast in RefreshTask.cpp + one refreshable-MV regression test):

("CH Inc sync" is fork-sync infra noise.) The fix itself is green: the new 03981_refreshable_mv_retries_int64_max test passed, and no failure touches the changed code.

@alexey-milovidov alexey-milovidov self-assigned this Jun 20, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, provide a fix for StatisticsCountMinSketch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov I investigated the StatisticsCountMinSketch::serialize segfault (STID 2046-3fcd). It is an incidental victim frame of heap corruption in the merge-finalize path, not a count_min bug.

Crash: OPTIMIZE/merge -> MergedBlockOutputStream::finalizePartOnDisk -> serializeStatisticsPacked -> StatisticsCountMinSketch::serialize -> WriteBuffer::write -> memcpy. The memcpy source is a fresh local bytes = sketch.serialize(), so a wild source pointer means the sketch object's own fields (_num_buckets/_total_weight/_sketch_array) were already overwritten by an external corruptor.

The count_min code is sound (so a guard there would only mask the corruption):

  • count_min_sketch::serialize writes a fixed-size array (7*2718 entries, sized at construction) and derives its length from the object's own fields.
  • count_min_sketch::merge throws on config mismatch, else element-wise add over the fixed array; ClickHouse always uses 7/2718, so it cannot corrupt the data pointer.
  • ColumnStatistics::merge keys stats by StatisticsType, so the typeid_cast in StatisticsCountMinSketch::merge cannot mismatch.

Evidence it is external corruption, likely a residual of the merge UAF you fixed in #107451:

  • Built ASan, ran 03913_partially_materialized_statistics 40x sequential + 96x concurrent with refresh_statistics_interval=1 (to race the background refreshStatistics task against merges): 0 crashes.
  • CIDB: STID 2046-3fcd is a single occurrence (this PR's arm_asan_ubsan, targeted, 0 on master). The dominant merge-finalize corruptor was the MergeTreeSequentialSource::generate assumeMutableRef().shrinkToFit() UAF (STID family 1760-433a / 2046-4f7a / 2046-50c3), fixed by Use COW-safe IColumn::mutate when finalizing merge output columns #107451; 2046-50c3 has zero hits after 06-14. This PR's commit already contains Use COW-safe IColumn::mutate when finalizing merge output columns #107451, so 2046-3fcd is a rare residual in that path.
  • Crash core: build-id mismatch (PR rebuild overwrote the binary), so unsymbolizable. Server log confirms the crash table is the 03913 test_table with the background refreshStatistics task active, and the crash thread is MergeMutate.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108005&sha=8f5bfbdd900048f1945da44f1083a6de6489290a&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29

I can keep hunting the residual corruptor, but I cannot reproduce it and the core is unsymbolizable, so I would need it to recur with a usable core to pin the writer. Do you want me to instrument/stress the refreshStatistics-vs-merge interaction further, or did you have a specific suspect in mind?

(cron:clickhouse-worker-slot-2:20260620-193900)

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master to refresh CI (the branch was 329 commits behind). The merge is clean — RefreshTask.cpp auto-merged with no conflicts, and the net 3-dot diff against master is unchanged: exactly the 3 files of this PR (the static_cast<UInt64> overflow fix + the 03981_refreshable_mv_retries_int64_max regression test).

Pushed 9d070d5ccce..566d48ecc94.

Sole CI red was an unrelated master-wide breakage, now fixed by the merge

The previous run's only failures were 02354_vector_search_rescoring (a vector-search test, unrelated to RefreshTask), failing across many stateless jobs. It was a master-wide breakage, not a flake specific to this PR — on 2026-06-29 it failed 572 times across ~50 PRs and on master itself (pull_request_number = 0).

Root cause: it was introduced by #105591 and reverted by e531152b092 ("Revert "Apply exact row-positioning for vector search rescoring queries"", 2026-06-29 13:12 UTC). The failure timeline confirms the fix — master failures drop to 0 after 13:00:

hour (UTC, 2026-06-29) total fails master fails
11:00 11 11
12:00 116 24
13:00 201 11
14:00 159 0
15:00 79 0
16:00 6 0

That revert is included in the master merged here, so the fresh CI run on 566d48ecc94 should no longer hit 02354_vector_search_rescoring.

The PR remains approved (@alexey-milovidov), AI-Review is ✅ Approve, and there are no unresolved review threads — blocked only on the fresh CI run.

@alexey-milovidov

Copy link
Copy Markdown
Member

Re-checked after the master merge (566d48ecc94, now 0 commits behind master, MERGEABLE). The net 3-dot diff is still exactly the 3 files of this PR: the static_cast<UInt64> overflow fix in RefreshTask.cpp (+ the negative-refresh_retries infinite case) and the 03981_refreshable_mv_retries_int64_max regression test. The change is correct, and the test's memory-engine tag is valid (matches the sibling 03258_refreshable_mv_misc).

Sole completed CI failure is an unrelated flake

Stateless tests (arm_binary, parallel) → 03164_parallel_replicas_range_filter_min_max. This is a timeout flake, not a regression from this PR (a 1-line UInt64 cast in RefreshTask):

  • CI's own rerun diagnosis on this PR: 157/158 — Result: All reruns passed. The failure is not reproducible.
  • The same test flaked on unrelated PRs in the same window: Revive SZ3 compression codec #108788 (6/158 reruns failed) and Support CAST from QBit to Array #108072 (Fast test, a different error mode).
  • 0 hits on master (pull_request_number = 0) over the last 14 days.
  • The test (03164_parallel_replicas_range_filter_min_max.sql, 178 lines of parallel-replicas queries, no long/no-parallel tag) times out under heavy parallel load; the failing run's output matched the reference, consistent with a timeout rather than a wrong result.

The rest of CI is still in progress on the fresh merge. The PR remains approved (@alexey-milovidov), AI-Review is ✅ Approve, and there are no unresolved review threads — blocked only on the fresh CI run completing.

@groeneai, there is no tracking issue for the 03164_parallel_replicas_range_filter_min_max flakiness (it failed on #108005, #108788, and #108072 in two days, never on master). Could you investigate and provide a fix in a separate PR? If a fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov 03164_parallel_replicas_range_filter_min_max is not a timeout flake, it is the connection-pool packet desync. The three hits (#108005, #108788, #108072) all failed in 0.2-2.2s with Code 102 UNEXPECTED_PACKET_FROM_SERVER (expected TablesStatusResponse, got Data) thrown from connection establishment for the cluster(...) queries, with output matching the reference; #108788 reproduces it at 6/158 same-settings reruns, so it is not a randomized-settings issue. (The 2026-06-08 hit on PR 106734 was that PR's own part_minmax_index_columns BAD_ARGUMENTS, unrelated.)

This is the #93018 recurrence, already being fixed in your #108854. Its ConnectionEstablisher::run retry on UNEXPECTED_PACKET_FROM_SERVER is packet-type-agnostic, so it also covers the "got Data" variant here. 03164 has 0 master hits in 14d, but the desync family has 7 master / 55 total across 47 PRs in 14d, so a separate test-only PR is not warranted (it would mask the engine bug). Tracking #108854.

@alexey-milovidov

Copy link
Copy Markdown
Member

Re-checked the fresh CI on 566d48ecc94 (0 behind master, MERGEABLE, approved, AI ✅, no unresolved threads). The net 3-dot diff is unchanged — exactly the static_cast<UInt64> overflow fix in RefreshTask.cpp (+ the negative-refresh_retries infinite case) and the 03981_refreshable_mv_retries_int64_max regression test (no 03981 prefix collision on master). No code change is needed.

All three current reds are known, unrelated flakes:

The two Hung-check reds cannot be caused by this PR: the change is a pure log_comment string-formatting fix (a UInt64 cast — no locks, no threading, no concurrency change), and the hung-check dumps contain no RefreshTask/refreshable-MV frames.

Blocked only on the fresh CI run completing and a maintainer rerun/merge of the flaky reds.

…nt64-overflow

Pull in the fix for the flaky '03164_parallel_replicas_range_filter_min_max'
distributed-query test (PR ClickHouse#108854, 'Unexpected packet from server') to refresh CI.
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master (the branch was 1319 commits behind after a busy day). The merge is clean — RefreshTask.cpp auto-merges and the net 3-dot diff is unchanged (RefreshTask.cpp +10/-1 plus the 03981 test .sh/.reference).

The key reason for this refresh: #108854 ("Fix flaky distributed query 'Unexpected packet from server (expected TablesStatusResponse, got ProfileInfo)'") merged into master today, which is exactly the connection-pool packet-ordering flake that failed 03164_parallel_replicas_range_filter_min_max on the previous run. Pulling it in should clear that failure. The remaining reds on the prior run were TSan Hung-check flakes (#107941, unrelated to this string-only fix).

Approval still stands and there are no unresolved threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

Re-checked the fresh CI on 07b96e46a4d (the master re-merge). The run is still in progress — Fast test is running and the stateless/stress/integration matrix (including 03981_refreshable_mv_retries_int64_max) is gated behind it, so it hasn't scheduled yet.

The reds so far are not caused by this PR:

  • Bugfix validation (functional tests, amd64) and (aarch64) fail at the Start ClickHouse Server setup step, not in the test itself. The server prints its pre-logging banner and then exits with code 115 (~2s later) before writing a single line — clickhouse-server.err.log is never even created. There is no stack trace, no sanitizer report, and no coredump; exit 115 is a plain process exit (< 128), not a signal. This is the transient Bugfix-validation startup flake from the 2026-07-01 ~23:5x UTC window that also hit the unrelated Fix DECIMAL_OVERFLOW in changeYear/changeXxx for nanosecond DateTime64 #108681 and Delete Iceberg table files on DROP with iceberg_delete_data_on_drop #109071. It needs a re-run once the overall run completes — it is not a regression in the fix or in the regression test.
  • CH Inc sync is the fork-sync infra check (known noise here).

The net 3-dot diff is unchanged — exactly the static_cast<UInt64> overflow fix in RefreshTask.cpp (plus the negative-refresh_retries infinite-retries branch) and the 03981 test .sh/.reference. Approved, no unresolved threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

The fresh CI run on 07b96e46a4d completed, and I re-ran the three failed jobs. All three reds are unrelated flakes, not caused by this string-format fix:

Re-running the failed jobs now; Fast test is a required gate, so it needs to go green before the downstream stateless/stress matrix (including 03981) is scheduled. The diff is unchanged (approved, no unresolved threads, AI review clean).

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.70% +0.10%

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

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 2, 2026
Merged via the queue into ClickHouse:master with commit 2700103 Jul 2, 2026
344 of 348 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 2, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing out the StatisticsCountMinSketch request. No fix is warranted, and the data now supports that rather than only the code reading.

Since my 2026-06-20 analysis, the StatisticsCountMinSketch::serialize crash frame appears exactly once in 120 days of CIDB: the original STID 2046-3fcd on this PR. Zero on master, zero anywhere since. The wider merge-finalize crash family (finalizePartOnDisk plus a segfault / use-after-free / "Server died" marker) last fired on 2026-06-22 and has been silent for 51 days.

That is consistent with the incidental-victim reading: the corruptor lived in the merge COW path and #107451 closed it. The single 2026-06-20 hit landed on a commit that already contained #107451, so it was the tail of that family rather than a count_min defect.

StatisticsCountMinSketch is unchanged on master and still has no defect at the crash site: serialize writes a fixed 7x2718 array sized at construction and derives its length from the object's own fields, and merge throws on a config mismatch. A guard there would have masked the corruption instead of fixing it, so I am not making a code change. If the frame recurs with a usable core, I will take it from the writer side.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…shtask-refresh-retries-int64-overflow

Fix signed integer overflow in RefreshTask attempt log_comment
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 22, 2026
…ckoff

backoff() bounds only the product refresh_retry_initial_backoff_ms *
multiplier, never the value it returns, so both branches can hand back an
arbitrary setting value: the else branch returns refresh_retry_max_backoff_ms
verbatim, and the if branch reaches the same magnitude at retry_idx = 0 via
initial * 1. Both settings are plain RefreshSettingsUInt64 with no upper bound
at parse or DDL time.

determineNextRefreshTime then computed
  when = znode.last_attempt_time + backoff(...)
whose common type is milliseconds, so the sys_seconds operand was promoted by
1000 and the addition overflowed signed int64. last_attempt_time is itself read
from Keeper without validation, so it is a second untrusted operand.

Reported by BuzzHouse (arm_asan_ubsan), STID 3978-3a6d:
  duration.h:403: signed integer overflow:
    1785593651000 + 9223372036854775807 cannot be represented in type
    'long long'

In a release build the wrapped instant lands about a millisecond before
start_time, so the "scheduled time not arrived yet" branch is skipped and the
view refreshes on every scheduling pass, ignoring the configured backoff.

Bound both operands in their own units before the conversions that widen them,
and do the addition with common::addOverflow. The retry instant is widened by
1000 three times over: seconds to milliseconds here, milliseconds to
system_clock's microseconds when constructing the time_point, and microseconds
to nanoseconds inside condition_variable::wait_for, which
BackgroundSchedulePool reaches from the delay this instant produces. Three
static_asserts pin those three requirements separately; none follows from the
others, so retuning one constant cannot silently break the argument.

A fourth requirement is not expressible as a static_assert and is stated as a
comment: last_attempt_time flows into CalendarTimeInterval::floor, which builds
a std::chrono::year_month_day, and std::chrono::year holds a short. A year
outside [year::min(), year::max()] wraps silently with both year().ok() and
ymd.ok() still true, so the bound has to clear every consumer's type limits and
not only the arithmetic domains.

Neither bound is reachable by any clock: 9e11 seconds is year ~30489 and the
delay bound is 95 years, against a largest in-tree fake clock of 2070. That
matters because last_attempt_time is written from a real timestamp, so a
wall-clock-reachable bound would clamp genuine retry timestamps into the past,
make when <= now, and recreate the very immediate-refresh loop this fixes. The
saturated instant also stays strictly below time_point::max(), which the
scheduler uses as the "no refresh scheduled" sentinel. No REFRESH AFTER/EVERY
period and no RANDOMIZE FOR window is bounded.

Verified with a deterministic reproducer on an ASAN+UBSAN build: the abort at
duration.h:403 is gone, and so is the further nanosecond-domain abort at
duration.h:93 that a milliseconds-only or microseconds-only bound would leave
behind. An exhaustive corner sweep over the bounds against two start times
finds no overflow in any domain.

Note the retry path is not the only caller of the scheduler's delay
arithmetic. src/Core/BackgroundSchedulePool.cpp remains able to overflow for a
corrupt last_attempt_time at its bound, and is independently reachable from a
plain REFRESH AFTER with no settings at all; that is a pre-existing bug in
another layer, tracked separately and deliberately not touched here.

ClickHouse#108005 fixed the sibling refresh_settings[refresh_retries] + 1 overflow in
this file and its closing note asked for this sweep.
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 pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants