Skip to content

Fix silent wrong results for a granularity close to the maximum of UInt64 - #116528

Open
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-116428-index-granularity-ceil-overflow
Open

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-116428-index-granularity-ceil-overflow

Conversation

@groeneai

@groeneai groeneai commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116428
Related: #108650

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):

Fix SELECT silently returning wrong results when the GRANULARITY of a secondary index is close to the maximum value of UInt64: a filtered query skipped the whole part, and a top-K ORDER BY ... LIMIT read past the end of an empty granule array or dropped a whole part. A top-K read over a coarse minmax index could also run out of memory.

Description

On 26.10, a secondary index with a GRANULARITY close to 2^64 loses rows without an error:

CREATE TABLE s (x UInt64, y UInt64, INDEX i y TYPE minmax GRANULARITY 18446744073709551615)
ENGINE = MergeTree ORDER BY x SETTINGS index_granularity = 64;
INSERT INTO s SELECT number, number FROM numbers(4096);
SELECT count() FROM s WHERE y = 500;   -- 0, expected 1
SELECT y FROM s ORDER BY y LIMIT 1;    -- reads past the end of an empty array

The index mark range is rounded up as (end + granularity - 1) / granularity, which wraps once the sum reaches 2^64 and gives an empty range: filtering drops every granule, and top-K indexes an unfilled granule array. The rounding now avoids that sum at the three sites that map data marks to index marks. #120906 already did the same for the data marks of a non-adaptive part (the index_granularity repro of the issue) and for the reverse-read split; the test keeps covering both.

Top-K also multiplied LIMIT by the index GRANULARITY; the wrapped product kept too few granules and dropped a whole part, so it now saturates.

Once top-K works at such a GRANULARITY, the AST fuzzer ran the server out of memory on this test's table: each of top-K's one-mark ranges re-read the index granule covering it, appending all its marks. On 26.8 this happens at ordinary values too: ORDER BY y LIMIT 1 over four parts of 65409 marks with a GRANULARITY 100000 minmax index exhausts 8 GB. Each index granule is now read once.

Validated both ways: on master the test returns the wrong count and then aborts on a libc++ out-of-bounds check (UBSan reports the wrap at the first rounding site); with the fix it passes, 40/40 randomized and clean under ASan+UBSan.


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

…ze_t

Two read paths returned no rows, with no error raised anywhere.

A MergeTree part with index_granularity_bytes = 0 and an index_granularity
within rows_count of 2^64 accepted the INSERT and reported its rows in
system.parts and in SELECT count(), but SELECT sum(x) gave 0 and SELECT x
gave zero rows. Separately, a query filtered by a secondary index declared
with a GRANULARITY close to 2^64 skipped every granule and so pruned the
whole part, while an unfiltered read of the same table was correct. Both
paths are compiled into every shipped binary, unlike the debug-only
allocator abort fixed in ClickHouse#108650.

Both come from the same ceil-division idiom

    (a + granularity - 1) / granularity

which wraps once the sum reaches 2^64 and therefore reports zero granules.
In MergeTreeIndexGranularityConstant::fixFromRowsCount the part's single
data mark then satisfies num_marks_without_final > expected_data_marks, is
reclassified as a final mark, and getTotalRows returns 0. In
getMarksCountForSkipIndex and in the two index mark range computations in
MergeTreeDataSelectExecutor the index range comes out empty, so the granule
loop never runs and an empty MarkRanges is returned. SELECT count() keeps
answering from count.txt, which is what made the loss silent.

Compute the rounding so that the sum is never formed, at all four sites.
Both granularities are already validated to be at least 1, index_granularity
in MergeTreeSettingsImpl::sanityCheck and the index GRANULARITY in
IndicesDescription, so the remainder is safe on the same precondition the
division already required. The new form also returns 0 for rows_count == 0,
so the separate special case for that is dropped.

The write side needed no change: MergeTreeDataPartWriterOnDisk closes an
index granule on an equality counter rather than a division, so it already
writes the single granule that the corrected rounding expects.

Bounding index_granularity from above was considered and rejected. It would
not repair parts that are already written, since sanityCheck runs only at
LoadingStrictnessLevel::CREATE, and it would reject ALTER TABLE ... MODIFY
SETTING on such a table and refuse server startup when the value comes from
the global <merge_tree> config section.

Closes ClickHouse#116428
The test proved that the rows come back, but not that the index mark range
was recomputed. force_data_skipping_indices only validates that the named
index is in the useful set, and filterMarksUsingIndex returns the ranges
unchanged when the per-part index cannot be deserialized, so the filtered
arm would answer 1 500 even if the index were never consulted. Assert the
number of granules the index keeps, read out of EXPLAIN indexes = 1, with
the GRANULARITY 1 table as the control that shows the count is able to
observe pruning at all.

Only the Granules: prefix is matched, never a denominator, because
randomized settings move the number of marks in the part. Measured on both
binaries and on eight combinations of index_granularity_bytes and
min_bytes_for_wide_part: at the near-maximum granularity every granule is
kept with this change and all of them are dropped without it, while the
control reads 1 either way. The primary key block of the plan cannot match
either pattern, since it never drops a granule here.

The fourth corrected site, getMinMaxIndexGranules, gets no arm. It serves
top-K ORDER BY ... LIMIT reads, and at MergeTreeDataSelectExecutor.cpp an
empty granule list leaves the mark ranges the primary key selected, so the
same marks are read and no rows are lost. Reverting that hunk on its own
leaves the whole test green, and at a granularity that large there is
nothing for top-K to prune because one index granule spans the part.
The reverse branch of the read-in-order range split divides `max_block_size` by
`index_granularity` with the same ceil-division idiom. At a granularity close to the
maximum of `size_t` the sum wraps, `max_marks_in_range` comes out 0, and
`marks_in_range` is then clamped to 0, so `range.end` stops advancing and the loop
appends zero-length ranges until the memory tracker stops the query. The forward
branch leaves its loop through a different condition and is unaffected, which is why
this site had been classified as a harmless heuristic.

`getMinMaxIndexGranules` has two callers and they are not equivalent. The
analysis-time one falls back to the mark ranges the primary key selected when the
granule list is empty. The read-time one in `MergeTreeIndexReadResultPool` indexes
the granule array directly, so an array that was never filled is read past its end
once the top-K threshold has been published, which a build with hardened libc++ turns
into an abort. The test now carries an arm that reaches it and pins the five settings
the suite randomizes, so the path is armed on every run rather than on a lucky draw.

The new non-matching-predicate arm disables part pruning by column statistics.
Otherwise statistics prune the whole part before the index is consulted, and the
granule assertion would pass even if the index were never consulted at all.

The reverse arm is placed last and the top-K arm after the row arms, because a test
file stops at its first exception and the earlier arms would otherwise be masked.
…lel replicas off

Three of the arms read the query plan, and the ParallelReplicas job randomizes
parallel_replicas_local_plan (tests/clickhouse-test:1636) while taking
enable_parallel_replicas from the default profile. With no local plan the
initiator has no read step, so those arms saw no index description and read 0:
"drops every granule" and "drops all but one granule" were a coin flip in that
job. Pinning enable_parallel_replicas = 0 in the explained query keeps them, and
every arm, live there; the no-parallel-replicas tag would have skipped the whole
file. With the pin removed and that profile forced, the test fails 3 runs out of
3, and the failing lines are exactly those plan-text values dropping to 0.

The reverse arm asserted only the three rows, which an ordinary sort returns as
well, so it could not tell a terminating reverse split from read-in-order having
declined. It now also asserts Read type: InReverseOrder. The literal is the
pretty spelling that describeActions emits; with optimize_read_in_order = 0 the
same query renders Read type: Default and the oracle reads 0.

The top-K arm catches the read indexing an empty granule array, but goes quiet
rather than failing if the read-time path is ever not selected. No row, mark or
range count can cover that: the part has one index granule, its minimum is the
value the threshold converges to, so no mark is ever skippable and read_rows is
4096 whether the read consults the granules or not. The new arm asserts instead
that the granule filter is selected for the shape, which is the half that can be
observed; use_skip_indexes_for_top_k = 0 takes it to 0.

Both new arms read 1 on every build, including the ones that revert a single
site. They assert that the arms above them are armed; they do not add coverage of
the defect.

Test only. 50 runs out of 50 with settings randomization on, and 50 out of 50
again with the ParallelReplicas settings profile.
… reading plan text

The previous round pinned enable_parallel_replicas = 0 on the arms that count
plan text and left the two arms that only execute unpinned, which was half a fix.
ReadFromMergeTree.cpp:1942 derives need_split from is_local_plan_initiator ||
!is_parallel_reading_from_replicas, and the corrected split_ranges lambda runs
only inside that branch, so with parallel_replicas_local_plan = 0 (randomized on
every run by tests/clickhouse-test:1636, and not pinned by the ParallelReplicas
job profile) the reverse arm never enters the code it exists to cover. Measured
on a build reverting only the reverse-split site, with that job's four settings
and local_plan = 0 forced: unpinned the arm returns the correct three rows,
pinned it fails with Code: 241. The rows are identical either way, so nothing the
arm prints could have separated the two states.

On the top-K read arm the same pin is for determinism, not for redness: that site
sits in the reader, which runs on the replica side as well, so the arm aborts in
both states on a build reverting only it. The pin removes the randomized draw and
matches the arming arm next to it.

The two reads before DETACH/ATTACH pin it for a third reason. With
prefer_localhost_replica = 0 that read is served over replica connections and can
still hold the storage when the ATTACH runs two statements later, which
DatabaseAtomic refuses with TABLE_ALREADY_EXISTS. It is not new here: the
pre-round file fails 1 run in 20 under that profile, 4 in 150 cumulatively, and 0
in 60 once pinned.

The top-K arming arm's comment now names the site it covers,
MergeTreeDataSelectExecutor::getMinMaxIndexGranules, so a later reader does not
take it for decoration.
`MergeTreeIndexBulkGranulesMinMax::getTopKMarks` budgets how many granules to keep
as `n * index_granularity`, the requested `LIMIT` times the skip index
`GRANULARITY`. That product wraps for a granularity of this size: `LIMIT
18446744073709551615` with `GRANULARITY 18446744073709551615` gives 1. One granule
is then kept, the trailing equal-threshold loop cannot rescue a part whose minimum
differs, and `MergeTreeDataSelectExecutor.cpp:1313` assigns the empty result over
that part, because the guard there tests the input granule list rather than the
result. The part's rows disappear with no error.

Both overloads carry the product, so both saturate. The per-part one takes its
`n >= granules.size()` early return at the `LIMIT` above, but it is reached at
smaller `n` and does wrap there: `GRANULARITY 9223372036854775808` with `LIMIT 2`
over one part of ten data marks wraps to 0, measured. It still cannot lose a row,
because one index granule expands into candidates that all carry the same value, so
they all tie and the trailing equal-threshold loop keeps every one. It is saturated
for symmetry, not on a measured loss. The loss is in the cross-part overload at
`MergeTreeIndexMinMax.cpp:462`, which has no early return and merges parts whose
minima differ, and that is the shape the new arm covers.

The ceil-division fixes earlier on this branch make the index mark range non-empty
for these granularities, so the top-K path now reads granules where it previously
read none. Without this change those fixes would turn a query that answered 128
rows into one that answers 64.

The new test arm keeps two parts of two data marks each, the smallest fixture that
exhibits it, and counts the granule filter on the same query that returns its rows:
the aggregate-wrapped form of that query is not armed at this `LIMIT`, so an arm
written that way would pass on a broken binary.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two independent reviews of this change: a cold review of the resulting tree, and a second-model
pass (codex) over the full diff, callers, loaders and existing tests. Six rounds; four of them each
turned up a further defect of the same class, all now fixed here.

# Finding Verdict
❌ The fourth changed site, getMinMaxIndexGranules, had no test arm, and its two callers are not equivalent. AGREE, fixed. The analysis-time caller falls back harmlessly at the guard at MergeTreeDataSelectExecutor.cpp:1313, where an empty input granule list leaves the primary key's ranges in place, but the read-time one indexes the empty array (MergeTreeIndexReadResultPool.cpp:603-607). With max_block_size = 64 the unpatched read aborts on an out-of-bounds std::vector::operator[], 3 runs of 3, and returns normally with use_skip_indexes_on_data_read = 0. Covered by the top-K arm.
❌ A near-maximum index_granularity was assumed to only degrade the reverse read-in-order range split. AGREE, fixed. True for direction == 1 only. Reversed, max_marks_in_range is 0, so marks_in_range is clamped to 0 and the loop appends zero-length ranges forever. ReadFromMergeTree.cpp:1846 is the fifth site, with its own arm bounded by max_memory_usage.
❌ The same top-K path carries a second, different overflow: n * index_granularity, the requested LIMIT times the index GRANULARITY, is unchecked. AGREE, fixed. This one matters because of the change itself: the five ceil-division fixes make the top-K index mark range non-empty at these granularities, so that path now reads granules where it previously read none, and the wrapped product then keeps too few. Measured: without the saturation this change turns a query that answered 128 rows into one that answers 64. Both overloads now saturate. The loss is in the cross-part one (MergeTreeIndexMinMax.cpp:462), which has no early return and merges parts whose minima differ; a new arm over two parts of two data marks covers it, and a build reverting only that hunk fails that arm and no other line of the file. The per-part one (:382) is reached at smaller n and its product does wrap there, but it cannot lose a row, because one index granule expands into candidates that all carry the same value, so they all tie and the trailing equal-threshold loop keeps every one. It is saturated for symmetry, not on a measured loss.
⚠️ The skip-index granule oracle was one-sided: it also passes when the index is never consulted. AGREE, fixed. Added a non-matching predicate on the same near-maximum index, which must drop every granule, so the pair differs only in the predicate. It needs use_statistics_for_part_pruning = 0, otherwise filterPartsByStatistics prunes the part first and the oracle answers without the index.
💡 Asked for an arm that observes the read-time top-K path declining, without reading the query plan. DISAGREE, raised three times and measured each time. No such observable exists on this fixture. Keyed on log_comment and current_database so the probe cannot count itself: with the read-time path on and off, read_rows 4096/4096, SelectedMarks 64/64, SelectedRanges 64/64, all identical. Only use_skip_indexes_for_top_k = 0 moves anything (SelectedRanges 1), and that is the analysis-time selection the plan-text arm already asserts. The reason is structural: at this GRANULARITY the part has exactly one index granule whose minimum is the value a top-K threshold converges to, so canSkipMark is reached for every mark and can never skip one, and MergeTreeIndexReadResultPool.cpp increments no counter that records a granule consultation. A fixture that could skip needs a second part whose granule minimum sits above the threshold, which makes the arm depend on part read order and on background merges not having run. I declined to add a knowingly flaky arm. Read-time liveness rests instead on the build that reverts only that site, which aborts at that arm.
💡 Claimed that a near-maximum granularity also breaks IMergeTreeDataPart::loadRowsCount at :2322, where rows_approx < rows_count + last_mark_index_granularity wraps, and asked for an overflow-safe comparison there. DISAGREE. The arithmetic is right, the reachability is not. That comparison lives in the final else of loadRowsCount (:2291), reached only when the part is non-empty and the :2229 condition is false, that is storage.format_version < MERGE_TREE_DATA_MIN_FORMAT_VERSION_WITH_CUSTOM_PARTITIONING and the part is not Compact and has no parent part. Inside that branch :2293 returns at :2297 whenever the part has count.txt. MergedBlockOutputStream::finalizePartOnDisk writes count.txt unconditionally for every part (MergedBlockOutputStream.cpp:391), and CHECK TABLE rejects a part without it (:2904, :2969), so no part any supported version produces reaches the wrapping comparison. It is also untouched here and ordered before the corrected code, so this change cannot affect it. I did not add a guard for a path I cannot reach with a query.

Also noted and deliberately not changed, none of them reachable with a query.
roundRowsOrBytesToMarks (MergeTreeDataSelectExecutor.cpp:1899) carries the same idiom over
index_granularity, but it only sizes min_marks_for_seek, so an underestimate costs seeks and
never rows; its sibling minMarksForConcurrentRead (:1912) already guards the overflow
explicitly. readFromPool's min_marks_for_concurrent_read * fixed_index_granularity
(ReadFromMergeTree.cpp:690) can wrap to zero on this shape, but nothing divides by it and
MergeTreeReadPoolBase.cpp:156 clamps it back up. The num_marks_without_final - 1 expressions in
MergeTreeIndexGranularityConstant are reachable identically before and after this change, and
getMarkUpperBoundForRow's wrapped product is never read because getTotalRows == 0 makes the
early return at :123 unconditional. Two further same-class products are unreachable for one shared
reason, that every index-granule number is bounded by ceil(marks_count / granularity), so at a
granularity near 2^64 the multiplier is 0 or 1 and the product cannot wrap:
MergeTreeIndexMinMax.cpp:325 and the index_mark * skip_index_granularity products in
MergeTreeDataSelectExecutor.cpp. Finally, and found by
reading only, MergeTreeIndexText.cpp:1447 uses the same idiom over dictionary_block_size; that
is a different index type with a different bound and I have not measured it, so I record it as
unverified rather than as a defect.

@clickhouse-gh clickhouse-gh Bot closed this Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [773df68]

Summary: ✅


AI Review

Summary

The change prevents overflow when rounding secondary-index marks and budgeting top-K candidates, and avoids repeatedly expanding the same minmax index granule. No outstanding findings at head 773df68dbcdc0340c95fc1f0bfbb2883293d8d79. The earlier text-index dictionary finding is addressed by merged PR #116634. The added regression test passes in the Fast test report.

Missing context / blind spots
  • ⚠️ The broader CI rerun, including sanitizer tests, is still in progress after the review-thread gate cleared. Its completion will supply the remaining runtime validation; no local tests were run in this CI review job.
Final Verdict

Status: ✅ Approve

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, five shapes, 100% on demand. (1) index_granularity_bytes = 0, index_granularity = 18446744073709551615 over numbers(10): sum(x) gives 0, expected 45. (2) INDEX i y TYPE minmax GRANULARITY 18446744073709551615 with index_granularity = 64 over 4096 rows: count() WHERE y = 500 gives 0, expected 1. (3) Top-K over that index, ORDER BY y LIMIT 1 SETTINGS max_block_size = 64, reads past the end of an empty granule array, which hardened libc++ turns into an abort at MergeTreeIndexReadResultPool.cpp:607. (4) Reverse read at index_granularity = 18446744073709551615, index_granularity_bytes = 1024: ORDER BY x DESC LIMIT 3 never terminates and dies on the memory limit. (5) Two parts of two data marks under that index, ORDER BY y LIMIT 18446744073709551615: LIMIT times GRANULARITY wraps to 1, one granule is kept, the second part is dropped, 2 of 4 rows returned. Shapes 1, 2 and 5 raise no error at all.
b Root cause explained? One ceil-division idiom, (a + granularity - 1) / granularity, wraps size_t once the sum reaches 2^64 and reports zero. For a non-adaptive part's data marks the single mark then satisfies num_marks_without_final > expected_data_marks, is reclassified as a final mark, and getTotalRows returns 0. For a secondary index the index mark range comes out empty, so no granule is deserialized: filtering prunes the whole part, and the top-K reader indexes a granule array that was never filled. In the reverse read-in-order split max_marks_in_range is 0, marks_in_range is clamped to 0, and the loop stops advancing. Shape 5 is a second, separate overflow: n * index_granularity in both MergeTreeIndexBulkGranulesMinMax::getTopKMarks overloads wraps to a small budget, the trailing equal-threshold loop cannot rescue a part whose minimum differs, and because the guard at MergeTreeDataSelectExecutor.cpp:1313 tests the input granule list rather than the result, the assignment at :1315 puts that empty result over a part whose input list was not empty. count() keeps answering from count.txt, which is what makes the loss silent. Confirmed by instrumentation rather than by reading: the overflow arm printed expected_data_marks=0 where the index_granularity = 8192 control printed 1 on the same path, and the reverse split's allocation frame is ReadFromMergeTree.cpp:1876.
c Fix matches root cause? Yes. The rounding is computed without ever forming the wrapping sum, at the source of the bad value. No widened bound, no no-random-* tag, no reduced dataset, no downstream guard at the symptom site. The multiplication saturates for the same reason, upward, because the product is a lower bound on how many granules to keep.
d Test intent preserved / new tests added? New test 04798_index_granularity_near_max_ceil_overflow: eight discriminating arms (write, ordered read, reload via DETACH/ATTACH, index-filtered read, top-K read, granules kept by the index, top-K across two parts, reverse read) and four attribution controls (unfiltered read, the same filtered query at GRANULARITY 1, its granule count, and a non-matching predicate on the near-maximum index). Granule counts are asserted as SELECT countIf(explain LIKE ...) FROM (EXPLAIN indexes = 1 ...), so they do not depend on the full plan text, and they match only the Granules: 0/ and Granules: 1/ prefixes, never a denominator, so a randomized mark count cannot make them flaky. The non-matching arm pins use_statistics_for_part_pruning = 0; without it filterPartsByStatistics prunes the part first and the assertion passes even when the index is never consulted. Two further arms assert only that the arms above them are armed, that the reverse read really is planned InReverseOrder and that the top-K granule filter is selected at all; both are identical on every binary and add no defect coverage. The cross-part arm carries a third such assertion, counted on the same query that returns its rows, because the aggregate-wrapped form of that query was measured to be unarmed at this LIMIT and would have passed vacuously; it also stops merges, since one merged part gives every granule the same minimum and the tie loop then keeps them all. Eleven statements pin enable_parallel_replicas = 0, for three measured reasons: with parallel_replicas_local_plan = 0 (randomized every run by clickhouse-test) the initiator plans no local read step, so the plan-text arms have no index description to count and read 0 instead of 1, the test failing 3 runs of 3 under the ParallelReplicas profile with the pin stripped; the reverse arm passes unpinned on a binary missing the very reverse-split fix it exists to catch, and fails there with Code: 241 when pinned; and a replica-side read before the DETACH/ATTACH pair can still hold the table when the ATTACH runs, which DatabaseAtomic refuses with TABLE_ALREADY_EXISTS, giving 4 failures in 150 unpinned runs against 0 in 60 pinned. No existing test weakened or removed. One earlier arm was deleted after measuring that it cannot fail: for a part emptied by ALTER ... DELETE WHERE 1 the probe shows num_marks_without_final=0, so the early return fires before the changed statement.
e Both directions demonstrated? Yes, on one tree, with every binary's Build ID asserted server-side via SELECT lower(buildId()) against readelf. The patched binary (e2d2a325d366f1ebb00cd32d2bfe60a5a03f6d0d) matches .reference byte for byte. The unpatched one returns written 0 0, reloaded 0 0, an empty ordered read, skip index, filtered 0 0, a granule count moving from 0 to 1, and then aborts on the top-K arm. Every control arm is identical on both, which attributes the loss to the read paths rather than to the insert. Per-site reverting builds each stop at their own arm and nowhere else: Code: 241 on the reverse arm for the build missing only the reverse-read site, vector[] index out of bounds on the top-K arm for the build missing only the top-K site, and the cross-part arm alone for the build missing only the saturation. Also 50 runs of 50 with settings randomization, 50 of 50 with the settings profile of the ParallelReplicas job, and 30 of 30 with that profile plus the two draws that previously exposed an ATTACH race.
f Fix is general across code paths? Yes. A tree-wide sweep for this idiom over any granularity found five sites, all fixed: MergeTreeIndexGranularityConstant.cpp:154, MergeTreeIndexGranularity.cpp:223 (getMarksCountForSkipIndex, three call sites), MergeTreeDataSelectExecutor.cpp:2605 and :2965, and ReadFromMergeTree.cpp:1846. MergeTreeIndexGranularityAdaptive structurally cannot carry the first defect: it stores marks_rows_partial_sums and never divides by a granularity. The write side needed no change and was verified: MergeTreeDataPartWriterOnDisk.cpp:300 closes a granule on an equality counter, with no division, so it already writes the single granule the corrected rounding expects. skipIndexWindowsOverlapping uses a form already clamped by std::min. A sixth site is a different idiom, the unchecked product n * index_granularity, and both getTopKMarks overloads carry it and both are fixed. The per-part one at MergeTreeIndexMinMax.cpp:382 is reached at smaller n and its product does wrap there, yet it cannot lose a row: one index granule expands into candidates that all carry the same value, so they all tie and the trailing equal-threshold loop keeps every one. It is saturated for symmetry, not on a measured loss. The cross-part one at :462 has no early return, merges parts whose minima differ, and is the site that loses rows. Each site was checked for a separately observable symptom by reverting it alone and rebuilding, and every one of the six has an arm that fails when only that site is missing. Two of those arms were found this way rather than by reading: getMinMaxIndexGranules has two callers, and while the analysis-time one falls back harmlessly at the guard at MergeTreeDataSelectExecutor.cpp:1313, where an empty input granule list leaves the primary key's ranges in place, the read-time one in MergeTreeIndexReadResultPool.cpp indexes the empty array; and split_ranges is a harmless heuristic in the forward direction but does not terminate in the reverse one.
g Fix generalizes across inputs? The new form equals exact ceil division in 396/396 boundary pairs across granularity and row counts spanning 1 to 2^64-1, and over all granularity, rows in [1,400] it never differs from the old form outside the overflow domain, so the change is a no-op everywhere except the broken regime. Both call sites of fixFromRowsCount are covered, write via MergedBlockOutputStream and load via IMergeTreeDataPart. Both skip-index read strategies are covered: the randomizer flips use_skip_indexes_on_data_read between 0 and 1 across the 50 randomized runs, and the top-K arm pins it so the read-time strategy is exercised on every run. The fifth site is driven by max_block_size rather than by a granularity, and the same rounding also repairs a max_block_size close to 2^64 with a default granularity. The sixth was measured over LIMIT in {2, 3, 2^64-1} against index GRANULARITY in {2^63, 1.2e19, 2^64-1}, giving products 0, 1 and huge, over one and two data marks per part and one and two parts: every wrapped product in these cells lost rows before the change and none does after, and the huge-product cells are unchanged in both directions. A wrapped product does not always lose rows: in a single part whose one index granule expands into candidates that all tie, the trailing equal-threshold loop keeps every granule, which is why the per-part overload is saturated for symmetry rather than on a measured loss.
h Backward compatible? Yes. No setting default changed, no new validation, no serialization or format change, no gate, so no SettingsChangesHistory.cpp entry is required (index_granularity has never had one). Behaviour is bit-identical outside the overflow regime, so no existing table, part or query can observe the change except the broken case it repairs. Saturating the product keeps strictly more granules than wrapping it did, so no answer that was already correct can change. Bounding index_granularity from above was rejected partly on compatibility: it would reject ALTER TABLE ... MODIFY SETTING on an existing table and refuse startup when the value comes from the global <merge_tree> config.
i Invariants and contracts preserved? Yes. Each changed expression keeps its contract, ceil(a / granularity), and now holds over the whole domain the validation layer admits rather than part of it. The new % needs the same precondition the existing / already needed, and it is enforced upstream: index_granularity < 1 is rejected at MergeTreeSettings.cpp:2660, index GRANULARITY == 0 at IndicesDescription.cpp:133, and max_block_size is declared NonZeroUInt64. The saturated product preserves its own contract, a lower bound on granules to keep, and the loop that consumes it is already bounded by !queue.empty(), so the saturated value cannot overrun the queue. No lock, lifetime, ownership or error path is touched, and there are no new early returns. The regression suite over the skip_index, minmax, secondary_ind and granular families (206 tests) was run against both binaries: no test fails with the change that passes without it.

Session id: cron:clickhouse-review-slot-10:20260826-134700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer @CurtizJ, could you review this? A ceil-division idiom wraps at a granularity close to 2^64 and reports zero granules, so a non-adaptive part reads as empty and a secondary index prunes the whole part, both with no error raised; the rounding is now computed without ever forming the wrapping sum, at the five sites those read paths use. It also saturates the separate LIMIT times GRANULARITY product in getTopKMarks, which the ceil fixes make reachable for the first time.

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@PedroTadim

Copy link
Copy Markdown
Member

Very high index granularity doesn't make sense, closing it

@PedroTadim PedroTadim closed this Aug 26, 2026
@PedroTadim PedroTadim reopened this Aug 26, 2026
@PedroTadim

Copy link
Copy Markdown
Member

but ok maybe the issue will trigger again

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 04a45fc. Build (arm_tidy) was failing on two of my own lines: .clang-tidy enables cppcoreguidelines-init-variables with WarningsAsErrors: '*', and I had declared the saturating product uninitialized. common::mulOverflow writes its out-parameter on both the overflow and the no-overflow path, so the value was never read unset and the saturating behaviour is unchanged; the established form at the other common::mulOverflow call sites in src/ is = 0. Verified with clang-tidy-21 and with the clang-tidy-22 that ci/defs/defs.py pins: two diagnostics before the change, none after, and re-introducing one declaration alone brings back exactly that one. The full check set reports no error on any of the five translation units this PR touches.

On the dictionary_block_size finding: the wrap is real, and the consequence is worse than described. With dictionary_block_size = 18446744073709551615 and two tokens I measure 0 rows where 1 is expected, and the row is lost with no force_data_skipping_indices as well, so an ordinary hasToken query answers wrongly. The same query at dictionary_block_size = 4 returns 1, and count() still reports both rows.

I am not folding it into this PR. It is a different setting in a different file, it wants a text-index reviewer rather than the granularity owners I asked here, and the title and changelog entry are scoped to index_granularity. It gets its own change, with that reproducer.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim agreed the configuration is unusual, and MergeTreeSettings.cpp already says so at the other end: index_granularity < 1 throws "value {} makes no sense". There is no upper bound, so the CREATE TABLE in the description is accepted and the rows are then lost with no error. On an unpatched master build:

count()                10   (answered from count.txt)
count() WHERE x >= 0    0
sum(x)                  0   (45 expected)
system.parts rows      10

One of the other shapes, a reverse-order read, does not terminate at all.

The reachable region is narrow: the wrap needs marks + granularity - 1 >= 2^64, so only granularities within a few of 2^64 get there.

This PR makes the rounding overflow-safe at the five read sites. The smaller alternative is an upper bound next to the existing lower ones, for index_granularity, for the index GRANULARITY clause, and for dictionary_block_size (the same idiom in the text index, in my comment above). Which do you prefer? I will build that one.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The dictionary_block_size wrap is now filed as #116634, with that reproducer as a regression test.

.clang-tidy enables cppcoreguidelines-init-variables and sets
WarningsAsErrors to '*', so the uninitialized declaration at the two
getTopKMarks sites failed Build (arm_tidy). common::mulOverflow writes its
out-parameter on both the overflow and the no-overflow path, so the value was
never read unset and the saturating behaviour is unchanged; every other
common::mulOverflow call site in src/ already declares its out-parameter as
`= 0`.

Reproduced and verified with both clang-tidy-21 and the clang-tidy-22 that
ci/defs/defs.py ToolSet pins: two diagnostics at MergeTreeIndexMinMax.cpp:382
and :462 before this change, none after, and re-introducing one declaration
alone brings back exactly that one diagnostic. The full .clang-tidy check set
reports no error on any of the five translation units this PR changes.
@groeneai
groeneai force-pushed the fix-116428-index-granularity-ceil-overflow branch from 04a45fc to f5626f5 Compare August 29, 2026 21:16
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 773df68db with master 4bb4fd70a (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

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b2b9af5

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
Build profile diff infra: the job exits 1 before any comparison, on Code: 497 ACCESS_DENIED for default.binary_sizes in the CI logs cluster (has_pr_data, build_profile_diff_job.py:721); reproduced on unrelated PRs by other authors a fix task is created (investigating at full effort, fixing PR link to follow here)

PR is the workflow rollup and is red only because of the row above. Coverage: 9 checks ran and
passed, 163 skipped, 0 dropped, nothing queued; Config Workflow, Style check (0/15),
Code Review, both Bugfix validation (functional tests, *) arms, CH Inc sync,
Finish Workflow and Mergeable Check are all green, and Mergeable Check reports no drops.

Session id: cron:our-pr-ci-monitor:20260907-213102

alexey-milovidov and others added 3 commits September 26, 2026 02:50
A top-K read gives every selected mark its own range. At read time
getMinMaxIndexGranules maps each range to the index granule covering it and
reads that granule, and every read appends one entry per data mark the granule
covers. When many ranges share one index granule, the same entries are
appended once per range, so memory grows with the number of selected marks
times the index GRANULARITY.

With the rounding fixes in this branch the top-K path is live at a GRANULARITY
close to 2^64, where one index granule covers the whole part, and the growth
becomes quadratic in the number of marks of a part. The AST fuzzer grew the
test's own table to four parts of 65409 marks, and the server was killed by the
OOM killer while it ran the test's top-K query. The same growth is reachable at
an ordinary GRANULARITY on released versions: on 26.8.10.6,
`SELECT y FROM t ORDER BY y LIMIT 1` over four parts of 65409 rows with
`index_granularity = 1` and a minmax index with `GRANULARITY 100000` exhausts
an 8 GB container, and completes with `use_skip_indexes_on_data_read = 0`.

Ranges within a part are sorted, so two consecutive ranges share at most the
index granule on their boundary. Skipping a granule equal to the one just read
therefore removes every duplicate and can never skip a granule that was not
read, whatever the order of the ranges.

The stateless test profile sets `max_rows_to_read`, which turns the read-time
index path off, so the read-time top-K arm now sets it to 0: without that, a
build reverting the rounding in getMinMaxIndexGranules passed the whole file
under the CI profile. A new arm bounds the memory of a top-K read over 2048
marks that share one index granule: at most 1.1 MiB over 51 randomized runs
with this change, 385 MiB in 20 of 20 runs without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The stress profile sets `ast_fuzzer_runs = 5` with `ast_fuzzer_any_query`,
so each INSERT is followed by fuzzed re-runs that add rows to the table:
under that profile the fixture held 12288 rows instead of 2048. The fuzzed
re-runs of the measured query would also keep its `log_comment`, which the
`system.query_log` lookup matches. Both statements now set
`ast_fuzzer_runs = 0`, the same query-level pin other `query_log` tests use,
and the rest of the file stays open to the fuzzer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…anularity-ceil-overflow

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
#	src/Storages/MergeTree/MergeTreeIndexGranularityConstant.cpp
@clickhouse-gh clickhouse-gh Bot added comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 24, 2026

This branch has not been deployed

No deployments
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 comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

index_granularity near 2^64: ceil-division overflow makes the part read as empty

3 participants