Repository navigation
Fix division by zero in ReadFromMergeTree when StorageMerge truncates the number of streams - #113382
Conversation
With `max_threads = 4` and `max_streams_to_max_threads_ratio = 1073741824`, the planner computes `max_streams = 2^32`, and the `UInt32(streams_num)` cast in `ReadFromMerge::createPlanForTable` truncated it to 0. The child `ReadFromMergeTree` then divided by zero in `spreadMarkRangesAmongStreamsWithOrder` (`(info.sum_marks - 1) / num_streams`), crashing debug and sanitizer builds (release builds eliminate the dead division). `IStorage::read` takes `size_t num_streams`, so the cast was a pointless leftover. Found by the AST fuzzer on an unrelated PR: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113010&sha=59507af89c33f62942e855b50b3e66704cbcf2e9&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 Related PR: #113010 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [45cba01] Summary: ✅
AI ReviewSummaryThis PR hardens Findings
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 103/109 (94.50%) · Uncovered code |
…ms-uint32-truncation
…ms-uint32-truncation
|
🕵 The only red check, |
|
Confirmed unrelated to this PR, and a fix is in progress — I will post the PR link in this thread when it opens. The failing query is an AST-fuzzer mutation, recovered from the job log rather than from the reported test label: WITH cte1 AS (SELECT n FROM merge(currentDatabase(), '^numbers_1e3__fuzz_0$')),
cte2 AS (SELECT n FROM numbers_1e3__fuzz_2 PREWHERE n IN (cte1) WHERE n IN (cte1) LIMIT 86)
SELECT DISTINCT count() FROM cte2
SETTINGS enable_parallel_replicas = 1,
cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost',
parallel_replicas_for_non_replicated_merge_tree = 1, max_parallel_replicas = 255;The discriminator is Root cause: Measured per-query on a debug build, with the two working arms as controls:
The Two notes on adjacent work:
One caveat on the fresh run you triggered: on I am also tracking a JOIN over |
…roduct against overflow The AI review pointed out that `StorageMerge` multiplies `requested_num_streams` by `max_streams_multiplier_for_merge_tables` (clamped to the number of selected tables) with unchecked `Float64` -> `size_t` casts in two places, and the planner only bounds-checks the earlier `max_threads * max_streams_to_max_threads_ratio` product. A product exceeding the range of `size_t` made the cast undefined behavior. Both multiplications now go through a shared helper that throws `PARAMETER_OUT_OF_BOUND` (same as the planner check) when the product is not representable. The narrow-pipe site also cast the raw `Float64` setting to `size_t` before clamping, which was itself undefined behavior for huge settings; it now clamps in `Float64` (`std::floor` preserves the old truncation semantics). Adds test `04820_merge_streams_multiplier_overflow`. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 The |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units681 translation units recompiled, 5134 s compile time in total, 681 of them have a recent master baseline. |
…ms-uint32-truncation
…ms-uint32-truncation
|
🕵 Triage of the four reds on commit 0726c8f, all unrelated to this change:
I merged master (8cacbf2), which pulls in the fixes for the first two, and pushed for a fresh CI run. @groeneai, please investigate the |
|
A fix is already in progress, and it is your own PR: #113045. Its description already lists Root cause, per that PR: since #109000 a plain The failing statement is not one of the asynchronous inserts the test is named for. All 18 failures in the last 30 days are the synchronous setup insert on line 13, One correction to the triage. Your count of 18 is right, but bucketing on
Master ran this test 10293 times in the same window with no failure of any reason. The one non-pull-request row is a The onset matches #109000 rather than a long-standing flake. In the ten days before it merged at 2026-08-01 20:48:23Z the test has 54594 green runs over 5923 commits and zero failures of any reason; the first failure is 2026-08-02 14:40:21, 17.9 hours after the merge. That is also why the fix belongs in the engine and #113045 changes no test file. None of this touches this PR: your diff only removes the Separately, and owed in this thread: the fix I promised here on 08-06 for the |
…ms-uint32-truncation
|
🕵 Triage of the five reds on commit 8cacbf2 — all unrelated to this change (which only affects the stream count passed by
🕵 @groeneai, please investigate the two failures without an existing fix and provide fixes in separate PRs (or link them here if already in progress):
|
|
Both of these already have owners; neither needs a new PR from me. 1. Mechanism, which confirms the pin is the right shape: AutoPR builds two plans for one query text, and One caveat on that PR rather than on this one: 2 of the 12 all-time failures of this test are 2. The The reason is the block size. The query ran with That also means the in-block checkpoint I merged yesterday in #112646 ( I own the follow-up and will carry it on the task that already tracks this signature. On your suggested directions: exempting it from the hung check looks wrong to me, since a genuinely stuck flush would then be invisible, and Two smaller notes on the same run, for completeness: the test carries |
…ms-uint32-truncation
|
🕵 Triage of the two reds on commit ca16d7c, both unrelated to this change; master has been remerged (73038ec) for a fresh run:
|
…ms-uint32-truncation
|
🕵 Triage of the single red on commit 73038ec: Also, per the AI review, the changelog category is switched to |
…ms-uint32-truncation
An empty marks-backed `Log` table reported zero streams from `getMaxReadStreams` while `createReadingPipe` still emits one `NullSource`, so the aggregate guard in `ReadFromMerge::createChildrenPlans` undercounted empty `Log` children, inconsistently with `StripeLog`. Clamp the bound to at least one stream, matching the read path.
…reads These engines bound their actual source counts regardless of the requested number of streams, but they inherited the default `getMaxReadStreams`, so the aggregate guard in `ReadFromMerge::createChildrenPlans` rejected safe reads over them with `PARAMETER_OUT_OF_BOUND` once `max_threads * max_streams_to_max_threads_ratio` crossed 65536. - `Memory` reports its snapshot block count, matching the clamp in `ReadFromMemoryStorageStep::makePipe`. - `Null` reports one stream: a read always produces exactly one `NullSource`. - `View` reports the context `max_threads` bound: the inner query is planned by the interpreter from the query context, so the `Merge` fan-out request does not amplify the inner read. Adds `05029_merge_bounded_engines_num_streams` covering all three engines through `Merge` with 262144 requested streams.
The test created a `File` table with an explicit file name, which resolves to the shared user files directory: repeated or concurrent runs appended to the same file, so the count grew across runs (CI got 2 instead of 1, reproducible 350/350). Without an explicit path the data file lives in the table's own directory and is removed with the table. CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113382&sha=a52d5568ab088dbdefc6404c3670949a964650c3&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
… for `StorageObjectStorage` `StorageView::readImpl` ignores the requested number of streams and replans the inner query from the query context, so `max_threads` was an undercount for e.g. a view over another `Merge` table. Remove the override: a `View` child now stays on the conservative default and an excessive request over it is rejected by the aggregate guard. `StorageObjectStorage` (S3/HDFS/Azure) reads with a static key list clamp their sources to the key count in `ReadFromObjectStorageStep`, so report that bound through `getMaxReadStreams`; globbed, archive, data lake and distributed reads keep the default because their key count is unknown until the storage is listed.
…ms-uint32-truncation # Conflicts: # src/Storages/StorageMerge.cpp
|
🕵 The two reds on 7e01bc8 — |
| size_t total_streams = 0; | ||
| for (const auto & table : selected_tables) | ||
| { | ||
| const size_t child_streams = std::get<1>(table)->getMaxReadStreams(streams_per_table, context); |
There was a problem hiding this comment.
selected_tables before createChildrenPlans ever fetches query_status or calls checkTimeLimit(). That bypasses the cancellation / timeout_overflow_mode = 'break' safeguard a few lines below.
For cheap hooks that is fine, but several of the new getMaxReadStreams overrides are not cheap: StorageLog and StorageStripeLog can load marks / indices from disk and wait on rwlock before they return. A Merge over many such tables can therefore spend the whole query budget in this pre-check and only then notice the timeout or KILL QUERY, which is exactly the failure mode the later checkTimeLimit() loop is trying to avoid.
Please move the query_status->checkTimeLimit() check into this loop (or before each getMaxReadStreams call) so the new guard preserves the existing cancellation contract.
| return std::make_shared<StorageSnapshot>(*this, metadata_snapshot, std::move(snapshot_data)); | ||
| } | ||
|
|
||
| size_t StorageMemory::getMaxReadStreams(size_t num_streams, ContextPtr) |
There was a problem hiding this comment.
getMaxReadStreams is now part of the safety contract for Merge, but this Memory override is not tied to the snapshot the child read will actually use.
ReadFromMerge::createChildrenPlans calls this hook first, and only later takes the child StorageSnapshot. For StorageMemory, getStorageSnapshot() can return a pinned query snapshot, and even without that a concurrent insert can publish a new Blocks version between these two calls. In both cases this hook can accept on an older/smaller data.get()->size(), while ReadFromMemoryStorageStep::makePipe() then reads a different snapshot and creates one source per block from that newer/larger state.
That breaks the new "getMaxReadStreams is an upper bound on the sources this read can create" invariant and can reopen the oversized-fanout path under concurrent writes. This needs to derive the bound from the same snapshot the read will consume, or keep Memory on the conservative default.
|
Two separate things here, and the fix for the one you linked is already merged. The blank page is a stale viewer, not a missing diagnosis. The report JSON does carry the reason, on both job nodes: What eats it is the viewer. It is not #111892, and the two checks did not die in the fuzzer. Both jobs lost their runner: The #111892 arithmetic also does not fit. That wedge is a post-fuzz probe loop costing about 66 minutes, which cannot happen inside an 18 to 24 minute job. Its fix, #115915, merged 2026-08-22, after For calibration, over 30 days the job level ERROR rate is 0.239% for If you want the viewer publish wired into CI so a merged |
The
AST fuzzer (amd_debug)raisedInteger divide by zeroonThe planner computes
max_streams = max_threads * max_streams_to_max_threads_ratio = 2^32, which passes the existing overflow check because it fits insize_t.ReadFromMerge::createPlanForTablepassedUInt32(streams_num)tostorage->read, truncating2^32to zero. The childReadFromMergeTreethen divides by the requested number of streams inspreadMarkRangesAmongStreamsWithOrder.IStorage::readtakessize_t num_streams, so this change removes the narrowing cast and adds a regression test.Additionally,
StorageMergemultiplied the requested number of streams bymax_streams_multiplier_for_merge_tableswith uncheckedFloat64tosize_tconversions. Both sites now use a shared checked helper that throwsPARAMETER_OUT_OF_BOUNDif the product does not fit insize_t.spreadMarkRangesAmongStreamsandspreadMarkRangesAmongStreamsWithOrderalso now use a division-based comparison when clamping streams to data, avoiding overflow innum_streams * min_marks_for_concurrent_read.Because forwarding the full
size_tstream count exposes arbitrary child engines to absurd requests,ReadFromMerge::createChildrenPlansnow checks the aggregate source count of aMergeread against a limit of 65536 before building any child plan, and rejects excessive reads withPARAMETER_OUT_OF_BOUND. Child storages report a conservative bound on the sources they create through the newIStorage::getMaxReadStreamscapability:File,URL,Log,TinyLog,StripeLog,Memory,Nulland object-storage engines (S3,HDFS,Azure) with a static key list are covered, proxies forward the capability to the nested storage, and a trivialLIMITreduces the request the same wayGenerateRandomdoes.Viewstays on the conservative default becauseStorageView::readImplreplans the inner query from the query context and ignores the requested stream count, so no tighter bound can be reported. When a child's reported bound is below the request, its output resize (parallelize_output_from_storages) is disabled so the constructed pipeline matches the accounting.The previously added streaming-read guard and its test are removed because current
masternow bounds effectiveMergeTreestream counts before that code path.Found by the AST fuzzer on an unrelated PR: CI report
Related: #113010
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix an arithmetic exception in debug and sanitizer builds when reading from a
Mergetable with a very largemax_streams_to_max_threads_ratio: the number of streams was truncated to 32 bits, so multiples of2^32became zero. Also throwPARAMETER_OUT_OF_BOUNDinstead of invoking undefined behavior when multiplying stream counts for aMergetable exceedssize_t, avoid an overflow when limitingMergeTreestreams to the amount of data, and reject aMergetable read whose aggregate source count would exceed 65536.Workflow [PR]
Sync PR [sync-upstream/pr/113382]
Version info
26.9.1.60(included in26.9and later)