Skip to content

Fix division by zero in ReadFromMergeTree when StorageMerge truncates the number of streams - #113382

Merged
alexey-milovidov merged 52 commits into
masterfrom
fix/merge-num-streams-uint32-truncation
Aug 25, 2026
Merged

alexey-milovidov merged 52 commits into
masterfrom
fix/merge-num-streams-uint32-truncation

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

The AST fuzzer (amd_debug) raised Integer divide by zero on

SELECT id FROM merge(currentDatabase(), '^t$') ORDER BY id DESC
SETTINGS max_streams_to_max_threads_ratio = 1073741824, max_threads = 4

The planner computes max_streams = max_threads * max_streams_to_max_threads_ratio = 2^32, which passes the existing overflow check because it fits in size_t. ReadFromMerge::createPlanForTable passed UInt32(streams_num) to storage->read, truncating 2^32 to zero. The child ReadFromMergeTree then divides by the requested number of streams in spreadMarkRangesAmongStreamsWithOrder.

IStorage::read takes size_t num_streams, so this change removes the narrowing cast and adds a regression test.

Additionally, StorageMerge multiplied the requested number of streams by max_streams_multiplier_for_merge_tables with unchecked Float64 to size_t conversions. Both sites now use a shared checked helper that throws PARAMETER_OUT_OF_BOUND if the product does not fit in size_t.

spreadMarkRangesAmongStreams and spreadMarkRangesAmongStreamsWithOrder also now use a division-based comparison when clamping streams to data, avoiding overflow in num_streams * min_marks_for_concurrent_read.

Because forwarding the full size_t stream count exposes arbitrary child engines to absurd requests, ReadFromMerge::createChildrenPlans now checks the aggregate source count of a Merge read against a limit of 65536 before building any child plan, and rejects excessive reads with PARAMETER_OUT_OF_BOUND. Child storages report a conservative bound on the sources they create through the new IStorage::getMaxReadStreams capability: File, URL, Log, TinyLog, StripeLog, Memory, Null and object-storage engines (S3, HDFS, Azure) with a static key list are covered, proxies forward the capability to the nested storage, and a trivial LIMIT reduces the request the same way GenerateRandom does. View stays on the conservative default because StorageView::readImpl replans 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 master now bounds effective MergeTree stream counts before that code path.

Found by the AST fuzzer on an unrelated PR: CI report

Related: #113010

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 an arithmetic exception in debug and sanitizer builds when reading from a Merge table with a very large max_streams_to_max_threads_ratio: the number of streams was truncated to 32 bits, so multiples of 2^32 became zero. Also throw PARAMETER_OUT_OF_BOUND instead of invoking undefined behavior when multiplying stream counts for a Merge table exceeds size_t, avoid an overflow when limiting MergeTree streams to the amount of data, and reject a Merge table read whose aggregate source count would exceed 65536.


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

Version info

  • Merged into: 26.9.1.60 (included in 26.9 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [45cba01]

Summary: ✅


AI Review

Summary

This PR hardens Merge-table stream fan-out by removing the UInt32 truncation, checking multiplier overflow, and introducing a new aggregate child-source guard via IStorage::getMaxReadStreams. The current head is much safer than the earlier revisions, but the new guard path still has two contract gaps: it can ignore cancellation / time limits during the expensive pre-check, and StorageMemory reports a live-state bound that is not tied to the actual snapshot the child read will consume.

Findings

⚠️ Majors

  • [src/Storages/StorageMerge.cpp:912] The new aggregate guard walks every child before any checkTimeLimit() / KILL QUERY check runs. For Log and StripeLog children the new getMaxReadStreams hooks can load marks / indices and wait on locks, so a Merge over many such tables can spend the whole deadline in the pre-check and only then notice the timeout. Suggested fix: fetch query_status before the aggregate loop and call checkTimeLimit() inside it.
  • [src/Storages/StorageMemory.cpp:222] StorageMemory::getMaxReadStreams reads the current data.get()->size() before ReadFromMerge captures the child StorageSnapshot, so a pinned snapshot or a concurrently published Blocks version can make the actual child read build more sources than this hook reported. Suggested fix: derive the bound from the same snapshot the read will use, or keep Memory on the conservative default.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  1. Make the aggregate getMaxReadStreams pre-check honor query cancellation / time limits between children.
  2. Make the Memory bound use the same snapshot semantics as the actual read path, or stop advertising a tighter bound there.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 103/109 (94.50%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Aug 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check, AST fuzzer (amd_tsan) (report), is the known parallel-replicas logical error Got read request from replica A for unknown stream B — tracked in the reopened issue #110518 and unrelated to this change (this PR only removes a UInt32 narrowing in ReadFromMerge::createPlanForTable; the fuzzer query does not use large max_streams_to_max_threads_ratio). The earlier fix #111689 merged in July, but the error recurred. @groeneai, investigate the failure and provide a fix in a separate PR; if a fix is already in progress, link it here. I merged the latest master to get a fresh fuzzer run.

Comment thread src/Storages/StorageMerge.cpp Resolved
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

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 merge(), not SAMPLE and not the force_* guards: the same query with a plain table in the CTE returns 86 correctly. Nothing in it touches max_streams_to_max_threads_ratio, so your reading is right.

Root cause: ReadFromMerge optimizes each child plan twice. createChildrenPlans optimizes it once (StorageMerge.cpp:992), which applies parallel replicas and inlines the local plan, leaving an already-coordinated ReadFromMergeTree in the outer plan. ReadFromMerge::buildPipeline then intends to skip a second optimization and sets optimization_settings.optimize_plan = false (StorageMerge.cpp:1288) — but that field is read only by optimizeTreeFirstPass (optimizeTree.cpp:57), while applyParallelReplicas runs in optimizeTreeSecondPass (optimizeTree.cpp:379), which never consults it. The already-coordinated read is therefore re-distributed and a second coordinator is allocated; only one of the two ever registers a stream, followers are dispatched against both, and the announcement to the second is dropped at ParallelReplicasReadingCoordinator.cpp:1214 before its read request throws at :1297.

Measured per-query on a debug build, with the two working arms as controls:

arm coordinators created streams registered result
merge() 2 1 abort
plain table instead of merge() 2 2 86
parallel_replicas_local_plan = 0 1 1 86

The 2 created / 1 registered asymmetry is the defect. The fix passes the existing do_optimize = false argument to buildQueryPipeline instead of the ineffective optimize_plan field, which is what the comment there already intends — three changed lines in src. Verified both directions with a per-arm server restart: this query aborts before and returns 86 after, and EXPLAIN indexes = 1 is byte-identical across the two builds.

Two notes on adjacent work:

  • Merged Fix unknown-stream LOGICAL_ERROR in parallel replicas with projection short-circuit #111689 is present in this build, so it is correctly not the owner here: gh api compare/f4f2c33...458ebe36 gives behind_by = 0. It closed the materialized-view-inner-table route, and this merge() route is a different mechanism with no projection short-circuit involved, which is why Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) #110518 recurred rather than regressed.
  • Your 113636 does not cover this one, though it is on the same three call sites: applyParallelReplicas reads only enable_parallel_replicas (no reference to make_distributed_plan anywhere in applyParallelReplicas.cpp), so clearing make_distributed_plan leaves the second-pass parallel-replicas rewrite running. I built your patch alone and this query still aborts with identical arithmetic. The two compose cleanly, but they will conflict textually, so I will rebase onto yours if it lands first.

One caveat on the fresh run you triggered: on 9b64bf4b the only red check is AST fuzzer (amd_debug, targeted), and it failed with a runner communication loss, not this assertion — so that run neither reproduces nor clears the failure.

I am also tracking a JOIN over merge() that still aborts with the same message after this fix, through the sibling optimize() in ReadFromMerge::addFilter. It is pre-existing rather than introduced, and whether it ships here or separately is being decided now; I will say which in the PR.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stress test (arm_release) red is the known harness-setup flake: the verify query SELECT value FROM system.server_settings WHERE name = 'cannot_allocate_thread_fault_injection_probability' in install_thread_pool_fault_injection timed out (TIMEOUT_EXCEEDED, 15 s receive_timeout) right after SYSTEM RELOAD CONFIG, before any test ran — unrelated to this change. Fix is already open: #113248.

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 45cba0125 with master 2797514bd (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
Binary Master PR Δ
programs/clickhouse-stripped 709.23 MiB 706.19 MiB -3.03 MiB (-0.43%)

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 units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 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 02015_async_inserts_5 TOO_MANY_PARTS flake and provide a fix in a separate PR — I found no open tracking issue or fix for it. If a fix is already in progress, link it here.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

A fix is already in progress, and it is your own PR: #113045. Its description already lists 02015_async_inserts_5 as one of its four carriers, next to 02458_relax_too_many_parts, 00980_merge_alter_settings and 02280_add_query_level_settings. It is open and was last updated 46 minutes before your comment, so I have not opened a competing PR. You are right that there is no open tracking issue for it.

Root cause, per that PR: since #109000 a plain INSERT writes through up to max_insert_threads sinks, and each one runs MergeTreeSink::onStart, which is where parts_to_throw_insert is checked. Those checks are not ordered against the other sinks' writes, so a sink scheduled late counts a part its own query has already committed and rejects the query in the middle of it. This test creates the table with parts_to_throw_insert = 1, so one part is enough.

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, INSERT INTO async_inserts VALUES (1, 's'), reported as query 1, line 1 in every one of them, and every one reports Too many parts (1 with average size ...): the query is rejected for the only part it wrote itself, into a table that was empty when it started.

One correction to the triage. Your count of 18 is right, but bucketing on head_ref rather than on pull_request_number, none of them is on master:

head_ref rows distinct carriers
pull request branches 17 16
gh-readonly-queue/master/pr-113646-... 1 1
master 0 0

Master ran this test 10293 times in the same window with no failure of any reason. The one non-pull-request row is a MergeQueueCI run, and it carries pull_request_number = 0, which is what reads as master when the bucketing is on the pull request number.

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 UInt32 truncation of the stream count in ReadFromMerge::createPlanForTable and bounds-checks the Float64 to size_t stream-count conversion in the two max_streams_multiplier_for_merge_tables sites. The failing test is a plain INSERT admission check and reads no Merge table.

Separately, and owed in this thread: the fix I promised here on 08-06 for the merge() unknown-stream abort is #113788. I should have posted the link when it opened on 08-07.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Triage of the five reds on commit 8cacbf2 — all unrelated to this change (which only affects the stream count passed by StorageMerge to child reads); master has been remerged for a fresh run:

🕵 @groeneai, please investigate the two failures without an existing fix and provide fixes in separate PRs (or link them here if already in progress):

  1. The 04305_autopr_output_bytes_estimation_join randomized-settings mass flake (culprit settings per the CI minimizer include enable_join_runtime_filters=1, execute_exists_as_scalar_subquery=1, query_plan_optimize_join_order_randomize): report.
  2. The stress-test hung check caused by an uncancellable AsyncInsertFlush crawling under ThreadFuzzer (consider making the flush respect cancellation or exempting it from the hung check): report.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

Both of these already have owners; neither needs a new PR from me.

1. 04305_autopr_output_bytes_estimation_join is fixed by your own #113908, which pins query_plan_optimize_join_order_randomize=0, enable_join_runtime_filters=0 in exactly this test (plus the four AutoPR join siblings). That covers two of the three culprits your minimizer named; the third, execute_exists_as_scalar_subquery, is a coincidental passenger, since the test has no EXISTS in it.

Mechanism, which confirms the pin is the right shape: AutoPR builds two plans for one query text, and buildQueryPlanForAutomaticParallelReplicas optimizes the candidate plan with a freshly constructed QueryPlanOptimizationSettings, whose constructor substitutes a new randomSeed() when the setting is non-zero. The two builds therefore draw independent seeds, the fake cardinalities from getRandomizedStats decide hash-join build side and whether the row-count-gated runtime filter is installed, the shapes diverge, findCorrespondingNodeInSingleNodePlan fails its hash match and returns nullptr, and the caller returns before the instrumentation runs. No ProfileEvent is emitted, so output_bytes reads 0. That is a fail-closed skip, so the = 0 disjunct fires, which matches the diff you saw (04305_join_inner 0 ..., 04305_join_right 0 ...).

One caveat on that PR rather than on this one: 2 of the 12 all-time failures of this test are Fast test on #69540, which runs --no-random-settings. That arm cannot be a randomization draw and is a distinct, PR-local failure mode (parallel_replicas_local_plan=false makes the candidate plan come back empty). #113908 will not affect it, and it should not be read as a regression of the pin.

2. The AsyncInsertFlush hung check is a real gap, but not an uncancellable flush - the flush is already cancellable, and the check that should have stopped it was in your build. Both is_cancelled in the hung-check dump and the executor's predicate resolve to QueryStatus::isKilled, and StreamingFormatExecutor::execute tests it once per while (true) iteration, before each format->prepare()/work(). The dump shows is_cancelled: 1 with 609 s elapsed, so the loop was not reaching that test often enough, not failing it.

The reason is the block size. The query ran with max_block_size=1, and IRowInputFormat::read() bounds its row loop by rows < max_block_size_rows, so it takes at most one trip per work() call and returns a one-row chunk. Every row is then a full prepare()/work()/PortFull round trip through the executor, and with ThreadFuzzer injecting on each SimpleObjectPool<SimdJSONParser> mutex unlock, each of those 2M rows costs a sleep. So it is exactly as you described, glacial progress rather than a lock cycle, and the cancellation check does fire, just once per row against a fuzzer-inflated per-row cost.

That also means the in-block checkpoint I merged yesterday in #112646 (CurrentThread::checkIfNotCancelled() every 8192 rows in IRowInputFormat::read) does not help this shape: with max_block_size=1 the counter never reaches 8192. That PR merged at 20:17Z on 2026-08-08 and your failing commit 8cacbf2c is from 09:04Z, so the build predates it in any case, but I do not want to claim it as the fix here.

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 no-stress is explicitly rejected by clickhouse-test. The narrower options are to make the cancellation cost O(1) per row rather than O(1) per block, or to have the hung check's existing teardown reach cancelled internal queries; prepare_for_hung_check already issues SYSTEM STOP THREAD FUZZER and kills known-slow queries, but a cancelled AsyncInsertFlush still has to drain 2M rows before it observes the kill. I will confirm which of those the maintainers prefer before opening anything.

Two smaller notes on the same run, for completeness: the test carries no-asan, no-ubsan tags, which the stress job deliberately ignores (clickhouse-test skips no-{build} tags when --stress-tests is passed, and stress.py always passes it), so this is a sanitizer-excluded test being run under a sanitizer by design. And Build (arm_release) / Post Hooks failed separately with No connection to LogCluster, which is infra.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Triage of the two reds on commit ca16d7c, both unrelated to this change; master has been remerged (73038ec) for a fresh run:

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Triage of the single red on commit 73038ec: Stress test (amd_asan_ubsan) (report) aborted on the type-equality chassert in IColumn::insertFrom called from buildAdditionalFilter in HashJoin (STID 2508-2e0c) — unrelated to this change (which only affects the stream count StorageMerge passes to child reads). It is the known issue #113931 (the same STID is cited in its title), with fix #113933 open.

Also, per the AI review, the changelog category is switched to Bug Fix (the second regression test covers a release-visible PARAMETER_OUT_OF_BOUND path). Master has been remerged (bf81f75; master touched StorageMerge.cpp again — the merged TU rebuilds clean, and both regression tests still match their references) and pushed for a fresh CI run.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 9, 2026
Comment thread src/Storages/StorageLog.h Resolved
Comment thread src/Storages/StorageLog.cpp Resolved
Comment thread src/Storages/StorageMerge.cpp Resolved
Comment thread src/Storages/StorageLog.cpp Resolved
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
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Storages/StorageMerge.cpp Resolved
… 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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The two reds on 7e01bc8 — AST fuzzer (amd_debug, targeted) and AST fuzzer (amd_debug, targeted, old_compatibility) — are bare job-level ERRORs with a blank 0s report and no artifacts, although the GitHub jobs ran 18–24 minutes. This matches #111892 (the fuzz run kills the job before artifacts upload). @groeneai, investigate the recurring blank-report targeted-fuzzer ERROR (report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113382&sha=7e01bc8ed790ab7db601f3f1d3edc21791b1ccbd&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29) and provide a fix in a separate PR. If a fix is already in progress, link it here. A fresh CI run on the new head will re-run both fuzzers.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ This new aggregate pre-check now does a full pass over 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 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.

@groeneai

Copy link
Copy Markdown
Collaborator

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:

"status": "ERROR", "info": "", "links": [],
"ext": {"errors": [{"message": "Job failed to produce Result due to a script error or CI runner issue",
                    "from": "AST fuzzer (amd_debug, targeted)"}]}

What eats it is the viewer. result_ast_fuzzer_amd_debug_targeted.json is 403, because the job never uploaded one, and the json.html currently live on S3 still has the 403 early return that aborts the whole render when a per-job report is absent. I removed that in #114921 (merged 2026-08-17). The live file is Last-Modified: Tue, 18 Aug 2026 10:48:50 GMT, and its md5 matches the ci/praktika/json.html blob at e6c2ff2e, which does not contain the fix commit 90fd5d72 (git merge-base --is-ancestor returns 1). Master has the fix, production does not. Publishing it is the manual python -m ci.praktika infrastructure --deploy --only html step in ci/praktika/html_page_development.md, and I have no S3 credentials for it. Nothing in the repo runs it, so a merged viewer change stays undeployed until someone does.

It is not #111892, and the two checks did not die in the fuzzer. Both jobs lost their runner: Set up job, Checkout code and Prepare env script all succeeded, Run is still in_progress with conclusion: null, and Post Checkout code never started. Both were on attempt 3, on i-0cb3b6b3be8bc252c and i-0a35a4ec5e0bd1715. The upload step lives after Run, which is why there are no artifacts and no CIDB row. This is the same shape I measured on this PR on 2026-08-14, and the GitHub-side logs for both are already purged, so I cannot attribute the reclaim further and will not guess.

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 7e01bc8e (diverged, behind 551), so that build could not have carried it in any case. The current head 45cba0125258548547a88722ed778cea8d415226 is ahead of both merges, so the run you triggered is covered for both. Build (amd_debug) is still building, so the two targeted fuzzers have not started yet.

For calibration, over 30 days the job level ERROR rate is 0.239% for targeted and 0.189% for targeted, old_compatibility, against 0.163% for non-targeted AST fuzzer (amd_debug). Targeting is not meaningfully over-represented, so I read this as ordinary runner attrition made to look like a silent failure by the stale viewer.

If you want the viewer publish wired into CI so a merged json.html change cannot sit undeployed, say so and I will open that as its own PR.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 25, 2026
Merged via the queue into master with commit 8f7b809 Aug 25, 2026
525 of 527 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/merge-num-streams-uint32-truncation branch August 25, 2026 02:37
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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