Repository navigation
Conversation
…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.
Internal second-model reviewTwo independent reviews of this change: a cold review of the resulting tree, and a second-model
Also noted and deliberately not changed, none of them reachable with a query. |
|
Workflow [PR], commit [773df68] Summary: ✅
AI ReviewSummaryThe change prevents overflow when rounding secondary-index marks and budgeting top-K candidates, and avoids repeatedly expanding the same Missing context / blind spots
Final VerdictStatus: ✅ Approve |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-10:20260826-134700 |
|
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 |
|
Very high index granularity doesn't make sense, closing it |
|
but ok maybe the issue will trigger again |
|
Pushed 04a45fc. On the 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 |
|
@PedroTadim agreed the configuration is unusual, and One of the other shapes, a reverse-order read, does not terminate at all. The reachable region is narrow: the wrap needs 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 |
|
The |
.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.
04a45fc to
f5626f5
Compare
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units9 translation units recompiled, 26 s compile time in total, 9 of them have a recent master baseline. |
CI finish ledger - b2b9af5Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260907-213102 |
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
Closes: #116428
Related: #108650
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
SELECTsilently returning wrong results when theGRANULARITYof a secondary index is close to the maximum value ofUInt64: a filtered query skipped the whole part, and a top-KORDER BY ... LIMITread past the end of an empty granule array or dropped a whole part. A top-K read over a coarseminmaxindex could also run out of memory.Description
On 26.10, a secondary index with a
GRANULARITYclose to 2^64 loses rows without an error: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 (theindex_granularityrepro of the issue) and for the reverse-read split; the test keeps covering both.Top-K also multiplied
LIMITby the indexGRANULARITY; 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 1over four parts of 65409 marks with aGRANULARITY 100000minmax 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]