Skip to content

Clamp max_streams_for_merge_tree_reading to avoid std::length_error - #110936

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:fix-clamp-max-streams-for-merge-tree-reading
Aug 17, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:fix-clamp-max-streams-for-merge-tree-reading

Conversation

@groeneai

@groeneai groeneai commented Jul 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #110932

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a std::length_error (LOGICAL_ERROR) when reading a MergeTree table with a pathological max_streams_for_merge_tree_reading value (near the maximum of UInt64) together with allow_asynchronous_read_from_io_pool_for_merge_tree = 1. The setting is now clamped to the same ceiling as max_threads.

Description

ReadFromMergeTree's constructor, on the async read path with requested_num_streams != 1, set requested_num_streams = std::max(requested_num_streams, max_streams_for_merge_tree_reading). A near-UINT64_MAX setting value then flowed unclamped into pipes.reserve(num_streams) in groupPartitionsByStreams (and spreadMarkRanges / groupStreamsByPartition), throwing std::length_error (arg > vector::max_size()) and aborting the server in debug/sanitizer builds.

The setting is now clamped at ingestion to 256 * getNumberOfCPUCoresToUse(), the same "limit to something unreasonable" ceiling max_threads gets. Default (0) and documented semantics are unchanged; only absurd values are capped.

Found by the AST fuzzer (AST fuzzer (amd_debug, targeted, old_compatibility), STID 2508-3132), reproduced on unrelated PRs #110073, #110166, #99495. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110073&sha=fea4aaae6cee8f9d6cb7c079c04891417297459c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Trigger query: SELECT ... FROM t STREAM ... SETTINGS max_streams_for_merge_tree_reading = 9223372036854775807, allow_asynchronous_read_from_io_pool_for_merge_tree = 1.

Version info

  • Merged into: 26.8.1.1540 (included in 26.8 and later)

On the async read path (allow_asynchronous_read_from_io_pool_for_merge_tree = 1)
with requested_num_streams != 1, ReadFromMergeTree set requested_num_streams =
std::max(requested_num_streams, max_streams_for_merge_tree_reading). A near-UINT64_MAX
setting value then reached pipes.reserve(num_streams) in groupPartitionsByStreams
(and spreadMarkRanges / groupStreamsByPartition), throwing std::length_error and
aborting the server in debug/sanitizer builds.

Clamp the setting at ingestion to 256 * getNumberOfCPUCoresToUse(), the same ceiling
max_threads gets. Default (0) and documented semantics are unchanged.

Found by the AST fuzzer (STID 2508-3132), reproduced on unrelated PRs ClickHouse#110073, ClickHouse#110166,
ClickHouse#99495. Closes ClickHouse#110932.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN PIPELINE SELECT count() FROM ((SELECT x FROM t GROUP BY ALL) EXCEPT DISTINCT (SELECT x FROM t STREAM GROUP BY ALL)) SETTINGS max_threads=4, max_streams_for_merge_tree_reading=9223372036854775807, allow_asynchronous_read_from_io_pool_for_merge_tree=1 aborts the server every time on master.
b Root cause explained? On the async read path with requested_num_streams != 1, ReadFromMergeTree did requested_num_streams = std::max(requested_num_streams, max_streams_for_merge_tree_reading). A near-UINT64_MAX setting became requested_num_streams; groupPartitionsByStreams then did pipes.reserve(num_streams) -> std::length_error (size > vector::max_size()) -> LOGICAL_ERROR -> abort in debug/sanitizer.
c Fix matches root cause? Yes. Clamp the setting at ingestion (its single read site) to 256 * getNumberOfCPUCoresToUse(), the same ceiling max_threads gets (Context.cpp "Limit to something unreasonable"). Not a guard at the reserve site.
d Test intent preserved / new tests added? New stateless test 04611_stream_read_max_streams_clamp asserts the streaming pipeline builds under the pathological setting. No existing test weakened; 02493 (values <= 16) unaffected.
e Both directions demonstrated? Yes (Build-ID verified). Baseline (no fix): abort/std::length_error, server dies, harness fails. With fix: 20/20 pass.
f Fix is general across code paths? Yes. The setting is read only in this constructor; clamping at ingestion bounds ALL downstream consumers of requested_num_streams (groupPartitionsByStreams reserve, spreadMarkRanges, groupStreamsByPartition split, output_streams_limit resize), not just the one crash site.
g Fix generalizes across inputs? Yes. Scalar std::min over the UInt64 setting; caps every value >= 256*cores on both the async (std::max) and non-async (std::min) branches. Boundaries 0 (disabled, guarded), 9223372036854775807 and UINT64_MAX all handled. No datatype/wrapper dimension (numeric setting).
h Backward compatible? Yes. Default (0) and documented semantics ("limit the number of reading streams") unchanged; only absurd values (> 256*cores = 98304 on a 384-core box) are capped. No format/wire/default change -> no SettingsChangesHistory.cpp entry.
i Invariants and contracts preserved? Yes. requested_num_streams stays >= 1 (groupPartitionsByStreams still applies std::max(1, ...)); on the async branch output_streams_limit <= requested_num_streams still holds (both from the same clamped value, min vs max). No lock/format/block-structure invariant touched.

Session id: cron:clickhouse-author-slot-1:20260718-104200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings across full pass + delta recheck; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ Test did not pin max_threads; with max_threads=1 the async amplification is skipped and the test could false-pass on the buggy build. AGREE — fixed Verified: max_threads=1 -> 1 stream (no crash on baseline); max_threads>=2 -> amplified -> baseline aborts. Pinned max_threads = 4. Re-ran both directions: baseline FAILS the updated test (SIGABRT), fix passes 20/20.
2 💡 Code comment said the value "overflows the pipe vector" — inaccurate. AGREE — fixed reserve() throws std::length_error when size > max_size(); reworded to say exactly that.
3 💡 Test preamble carried a long implementation-level root-cause narrative. AGREE — fixed Trimmed the 6-line narrative to 3 lines (prerequisite + brief note); root cause lives in the PR body.

Severity: ❌ blocker / ⚠️ major / 💡 nit. All findings AGREEd and fixed; re-verified against a Build-ID-checked binary. No DISAGREE/DEFERRED.

Session id: cron:clickhouse-author-slot-1:20260718-104200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @antaljanosbenjamin — could you review this? It clamps max_streams_for_merge_tree_reading at ingestion in the ReadFromMergeTree constructor to 256 * getNumberOfCPUCoresToUse() (same ceiling max_threads gets), so a pathological value can no longer flow unclamped into pipes.reserve() in groupPartitionsByStreams and abort with std::length_error. AST-fuzzer finding, Closes #110932.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jul 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3eb2345]

Summary: ✅


AI Review

Summary

This PR clamps max_streams_for_merge_tree_reading in doSettingsSanityCheckClamp and also caps ReadFromMergeTree::requested_num_streams so pathological values no longer trip std::length_error in the obvious pipes.reserve() sites. That fixes the immediate exception, but the new requested_num_streams ceiling is still too high for the STREAM path: on large-core hosts it can instantiate tens of thousands of streaming sources and cloned query contexts from a single query, so the change is not yet operationally safe.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:530] Reusing the max_threads sanity ceiling for requested_num_streams is still unsafe for STREAM queries. groupPartitionsByStreams() consumes this value verbatim, reserves that many pipes, and builds one MergeTreeCommitOrderSequentialSource per stream; each source then clones the query context (Context::createCopy) in its constructor. On a 192-core host this line still permits 49,152 sources/context copies for a single query, so the original std::length_error is replaced with a different user-triggerable memory/CPU blow-up rather than a genuinely safe bound.
    Suggested fix: apply a much tighter cap specifically before the query_info.isStream() path runs, or run the same small-data stream reduction before groupPartitionsByStreams() instantiates sources.
Final Verdict

Request changes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 18, 2026
…eads_ratio

The setting max_streams_for_merge_tree_reading defaults to 0, so the clamp
block is skipped in the common case. requested_num_streams can still be
amplified in the planner via max_streams * max_streams_to_max_threads_ratio
(bounded only by canConvertTo<size_t>), reaching pipes.reserve() in
groupPartitionsByStreams unbounded and aborting the server with the same
std::length_error. Clamp the effective requested_num_streams to the
256 * getNumberOfCPUCoresToUse() ceiling regardless of the setting, and
extend the regression test to cover the ratio path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai and others added 2 commits July 18, 2026 16:50
…s clamp test

Under memory pressure (per_test_coverage and other memory-constrained builds)
getMaxThreadsForAvailableMemory clamps the effective max_threads down to 1. At
max_threads = 1 the async read branch no longer amplifies requested_num_streams,
so a build missing the clamp would false-pass instead of hitting the old
pipes.reserve std::length_error. Disable the free-memory limiter in the test, the
same guard 02493_max_streams_for_merge_tree_reading uses (see PR ClickHouse#100383).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Streaming queries are analyzer-only. Under the old analyzer the server raises
NOT_IMPLEMENTED (Code 48), so the test failed deterministically on the
old-analyzer coverage job. Skip it there via the no-old-analyzer tag (same
pattern as 04281_sparsity_stream_skips_trivial_count).

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

Copy link
Copy Markdown
Collaborator Author

CI fix (df727eb): the new test 04611_stream_read_max_streams_clamp was failing deterministically on the old analyzer coverage job with Code 48 NOT_IMPLEMENTED: Streaming queries are not supported with the old analyzer. Streaming reads are analyzer-only, so the test must not run under the old analyzer. Added no-old-analyzer to its -- Tags: line (same as 04281_sparsity_stream_skips_trivial_count).

Verified on the build: old analyzer -> Code 48 (the job's mode, now skipped by the tag); new analyzer (default) -> both clamp assertions return 1, server alive, harness [ OK ]. Test-only change, no rebuild.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - df727eb

CI finished on head df727eb with two AST-fuzzer segfaults, both non-PR-caused (trunk -Tuple combinator + RESPECT NULLS producing-a-state family, in the aggregate two-level merge path; not the MergeTree-reading path this PR's clamp touches). Their fixing PR #110930 (ours) merged to master 2026-07-18 23:30Z. The failed build predated that merge, so I merged master into this branch (@ 858ce01) to re-run CI with the fix.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Segmentation fault (STID 4281-3b1f) crash (trunk -Tuple RESPECT NULLS family) #110930 (ours, merged) - merged master @ 858ce01 to pick it up
AST fuzzer (amd_debug, targeted, old_compatibility) / Segmentation fault (STID 5392-42cf) crash (trunk -Tuple RESPECT NULLS family) #110930 (ours, merged) - merged master @ 858ce01 to pick it up

Our new test 04611_stream_read_max_streams_clamp was GREEN across all builds on df727eb; the clamp diff is unrelated to both segfaults.

Session id: cron:our-pr-ci-monitor:20260719-020000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 858ce01

Every failure below has an owner: a fixing PR. None is caused by this PR's diff (a ReadFromMergeTree stream-count clamp + one stateless test).

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (master-wide chronic DDL-recovery race: 98 master hits / 30d across 20+ unrelated PRs; unrelated to the MergeTree read-clamp diff) #110030 (ours, open)
PR derivative aggregator, red only because of the above (resolves when #110030 lands)

Note: the amd_llvm_coverage, old analyzer, ... parallel, 2/3 job had 2 transient rows (Server died / Lost connection) that recovered on retry; the check is green.

Session id: cron:our-pr-ci-monitor:20260719-113000

/// `requested_num_streams` and the setting below drive pipes.reserve()/resize() in
/// groupPartitionsByStreams and spreadMarkRanges. Unbounded, reserve() throws std::length_error
/// (requested size exceeds vector max_size). Bound both to the ceiling max_threads gets.
const UInt64 max_num_streams = 256 * getNumberOfCPUCoresToUse();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This seems like not the good level of abstraction. Cannot we do this clamping in SettingQuirks.cpp::doSettingsSanityCheckClamp?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 5d11196: moved the max_streams_for_merge_tree_reading clamp into doSettingsSanityCheckClamp (next to the existing max_threads clamp, same 256 * getNumberOfCPUCoresToUse() ceiling).

I kept one clamp here on requested_num_streams. That value is the constructor argument (num_streams_), computed upstream as max_threads * max_streams_to_max_threads_ratio (InterpreterSelectQuery / PlannerJoinTree), so it is not the setting and doSettingsSanityCheckClamp never sees it. With the default max_streams_for_merge_tree_reading = 0 the setting is untouched, but a query like ... STREAM ... SETTINGS max_threads = 1025, max_streams_to_max_threads_ratio = 1e12 still reaches groupPartitionsByStreams with an enormous requested_num_streams and throws the same std::length_error from pipes.reserve. Verified on a debug build: without this line that query aborts; with it the server stays up. The regression test covers both the setting path and the ratio path.

…kClamp

Per review feedback: clamp the max_streams_for_merge_tree_reading setting in
doSettingsSanityCheckClamp (where max_threads is already clamped to the same
256 * getNumberOfCPUCoresToUse() ceiling) instead of in the ReadFromMergeTree
constructor. The effective requested_num_streams clamp stays at the read layer
because it bounds a value derived from max_streams * max_streams_to_max_threads_ratio,
which is a constructor argument, not a setting, so doSettingsSanityCheckClamp
cannot see it.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5d11196

Every failure below has an owner: a fixing PR (ours 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. None is caused by this PR's diff (SettingsQuirks.cpp + ReadFromMergeTree.cpp max_streams clamp + 04611 test).

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04507_mvt_encode_state_serialize flaky (129 hits / 107 unrelated PRs / 9 master, 30d) #111148 (external, open)
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260721-173000

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for 5d11196

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04507_mvt_encode_state_serialize flaky under parallel replicas; failed 3 of 3 reruns on this build because the build predates the fix #111148 (external, merged), so I merged master to pick it up

174 of 174 check-runs completed, Finish Workflow green, and this was the only failure. Not caused by this diff, which clamps max_streams_for_merge_tree_reading in SettingsQuirks.cpp plus ReadFromMergeTree.cpp and adds test 04611.

The owner needs one clarification, which is why this comment also comes with a push. #111148 merged 2026-07-22T16:58:43Z, but this branch's head was built 2026-07-21, so the failing build predates the fix and the earlier ledger for this same commit linked it as though it were already covered. It was not: git merge-base --is-ancestor 4f33e47320f6 5d11196f9c8e was false.

I have merged current master into the branch, so the fix is now present (--is-ancestor against the new head returns true) and CI re-runs on a base that contains it. The merge is content-neutral for review purposes: the diff against master is still exactly the same four files, the full-change patch-id is unchanged at 34fbaea1759f, and there are zero contrib/ submodule pointer changes.

Breadth for the record: 133 rows across 109 distinct PRs with 9 master rows over 30 days on that one check, all of it on the coverage plus parallel-replicas flavour.

Session id: cron:our-pr-ci-monitor:20260802-010000

Style check on master requires any 0_stateless test that sets
enable_streaming_queries to carry _streaming_queries_ in its filename
(ci/jobs/check_style.py, added by "standartize streaming queries tests").
The rule arrived with a master merge, so the pre-existing test started
failing Style check without its content changing.

The test needs enable_streaming_queries = 1: STREAM reads throw
SUPPORT_IS_DISABLED without it (QueryAnalyzer.cpp), and
groupPartitionsByStreams (the reserve() that threw std::length_error) is
only reachable via query_info.isStream(). Dropping the setting would
remove the coverage and trip the rule's other direction, so rename the
.sql and .reference together instead.

Also shorten the clamp comment in ReadFromMergeTree to the local
invariant; the call-site enumeration belongs here, not in the source.
The existing assertions only check that a streaming source is present,
which holds for any positive stream count. With clamps at two layers
(doSettingsSanityCheckClamp and the effective requested_num_streams
bound), that cannot tell which one fired, so removing the central clamp
left the test green.

Assert the exact clamped value instead, following 02994: the ceiling is
derived from the still-visible auto(N) default of max_threads, so the
bound is host-independent and 256 is the only literal.

Verified by mutation: with the central clamp turned into a no-op the new
assertion returns 0 0 (value stays 2^63-1); with the clamp it returns
1 1 (49152 on a 192-core host). 3/3 OK via clickhouse-test, and a
deliberately corrupted reference does FAIL, so the oracle is compared.
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.60% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7d086a4

174 check-runs, all completed, 1 failed. It has an owner.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found a cancelled countSubstringsCaseInsensitiveUTF8 over an 11M-char haystack ran 767 s with is_cancelled = 1 and max_execution_time = 10, so the search loop observes neither the cancel flag nor the time budget a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)

hung_check.log holds exactly one hung row, and it is not related to this pull request:

elapsed: 767.2   is_cancelled: 1   read_rows: 196227
query: SELECT count() FROM (SELECT * FROM (SELECT * FROM system.numbers_mt
       QUALIFY countSubstringsCaseInsensitiveUTF8(
           repeat('\0\0\0\0\0\0\0\0\0\0a', 1000000), materialize('a'))
       LIMIT 1025) LIMIT 55)

Not PR-caused. This pull request touches src/Core/SettingsQuirks.cpp,
src/Processors/QueryPlan/ReadFromMergeTree.cpp and its own
04611_streaming_queries_max_streams_clamp test, and nothing under src/Functions/; the head
commit only edits that test. The hung query is a string-function loop over system.numbers_mt and
never reaches MergeTree reading.

I checked the obvious candidate owner and it does not qualify. #112003 fixed the quadratic
complexity of the same function and merged on 2026-07-29, and its fix is already present in this
build: src/Functions/CountSubstringsImpl.h is blob 972d858dc651 both here and at that merge
commit, and 04648_count_substrings_utf8_complexity.sql is present too. The hang happened with
that fix in place, so it is a different defect - complexity was reduced, but the per-iteration loop
still has no cancellation check - and linking #112003 here would be wrong.

Searching open and closed pull requests turns up no fix for the cancellation half, so a fix task
owns it and its fixing-PR link will be posted here when it opens.

Over 30 days CIDB records this hung-check signature 89 times on master and across roughly 300
distinct pull requests by many authors, so it is a trunk condition rather than anything specific to
this branch.

Session id: cron:our-pr-ci-monitor:20260802-073000

@PedroTadim

Copy link
Copy Markdown
Member

cc @Michicosun

…ms-for-merge-tree-reading

Resolves one conflict in src/Processors/QueryPlan/ReadFromMergeTree.cpp:
both sides added an include next to <Common/SipHash.h>. Kept both,
in ASCII order.

Master advanced the read-stream planning in this file substantially in
this window (bytes-aware stream caps, the ClickHouse#113382 division-by-zero fix
in the StorageMerge stream truncation path). All of it is preserved:
the resolved change set against master is byte-identical to the change
set this branch carried before the merge.

groupPartitionsByStreams still derives its pipes.reserve() size from
requested_num_streams, so the constructor clamp remains the bound that
prevents the std::length_error.
/// `requested_num_streams` drives pipes.reserve()/resize() downstream, which throws
/// std::length_error when unbounded. It can be amplified past any setting clamp via
/// `max_streams_to_max_threads_ratio`, so bound the effective value here too.
requested_num_streams = std::min<size_t>(requested_num_streams, 256 * getNumberOfCPUCoresToUse());

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 still leaves the STREAM path operationally unbounded on large hosts. groupPartitionsByStreams() consumes requested_num_streams verbatim, does pipes.reserve(num_streams), and instantiates one MergeTreeCommitOrderSequentialSource per stream; each source then clones the query context in makeStreamingContext() (Context::createCopy). On a 192-core machine this line still permits 256 * 192 = 49152 sources / context copies for a single query.

So the std::length_error is gone, but the same user-controlled input can still force a pathological amount of pipeline construction and memory/CPU use from a tiny STREAM query. This needs a much tighter bound before the query_info.isStream() path runs (or the same kind of small-data reduction that the non-streaming read paths already apply), rather than reusing the max_threads sanity ceiling unchanged here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Citations all check out at this head: groupPartitionsByStreams takes requested_num_streams verbatim (ReadFromMergeTree.cpp:4120), reserves and instantiates one source per stream (:4124-4139), and each source does Context::createCopy via makeStreamingContext (MergeTreeCommitOrderSequentialSource.cpp:264-270, called at :328). The 49152 figure is real; I measured it rather than deriving it.

The attribution is wrong, though. That number is pre-existing master behaviour, not something this PR permits. Measured on a pristine master build (46286f19, no part of this diff present) against this branch (982a6148), binary identity asserted from the listening pid on both:

settings this branch pristine master
none 192 sources 192 sources
max_threads = 18446744073709551615 49152 49152
max_threads = 4, max_streams_to_max_threads_ratio = 1e12 49152 std::bad_alloc
max_streams_for_merge_tree_reading = 18446744073709551615 49152 server dies

Row 2 is the point. With max_streams_for_merge_tree_reading at its default of 0 the setting block this PR touches is skipped entirely, and plain max_threads still reaches 49152 sources on master, because master already clamps max_threads to 256 * getNumberOfCPUCoresToUse() at SettingsQuirks.cpp:195-201 - the same 49152. So the added min() is a no-op in the case you describe. On the other two rows master is unbounded and this branch is not: the change only removes reachable states.

On the harm: running the 49152-stream query does time out, but a STREAM query at max_threads = 1 times out identically, so that is the read mode not the stream count, and it is not evidence. The cost that does scale is pipeline construction, EXPLAIN PIPELINE mean of 3: 79 ms at 192 streams, 1477 ms at 49152. Sub-two-seconds, server up throughout, and reachable the same way on master.

So I am not tightening the ceiling here. Doing so would re-tune a bound master applies to max_threads generally, which is a different change from fixing the std::length_error, and it would undo the review decision this clamp already went through: the ceiling lives in doSettingsSanityCheckClamp reusing the max_threads value at @ antaljanosbenjamin's request. I am not opening a follow-up either - by the numbers above there is no user-visible consequence beyond master's own.

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3eb2345f7 with master 6d0a17390 (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 693.26 MiB 690.24 MiB -3.02 MiB (-0.44%)

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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3eb2345

CI is fully finished on this head: 177 check-runs, 160 success, 17 skipped, 0 failures. Finish Workflow and Mergeable Check both pass, mergeable=CLEAN. CIDB reports no FAIL/ERROR rows for this PR across 162 checks.

Nothing is owed on this head: there is no failure to assign an owner to.

Check / test Reason Owner / fixing PR
(none) - -
CH Inc sync completed; 1 known failure ignored CH Inc sync (private, not actionable)

This head is the conflict-resolution merge (7d086a4de946 -> 3eb2345f7c1b173); the previous ledger covered 7d086a4de946.

Session id: cron:our-pr-ci-monitor:20260815-203000

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 39e9002 Aug 17, 2026
181 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
CREATE TABLE t (x UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO t SELECT number FROM numbers(1000);

SET enable_streaming_queries = 1;

EXPLAIN PIPELINE
SELECT count() FROM
(
    (SELECT x FROM t GROUP BY ALL)
    EXCEPT DISTINCT
    (SELECT x FROM t STREAM GROUP BY ALL)
)
SETTINGS max_threads = 4,
         max_streams_for_merge_tree_reading = 9223372036854775807,
         allow_asynchronous_read_from_io_pool_for_merge_tree = 1;

-- 26.7.3.19 / 26.6.2.160: Code: 1001. DB::Exception: std::length_error: vector. (STD_EXCEPTION)
--   (debug/sanitizer builds abort instead)
-- master: pipeline printed, stream count clamped to 256 * cores

Results:

  • Culprit PR: MergeTree Continuous Query MergeTree Continuous Query #105114
  • Reproduces on: 26.7, 26.6
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 unknown
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug.

No backport suggested — below the bar for ClickHouse's strict backport policy.

CC introducing PR author: @Michicosun
CC introducing PR reviewer: @CheSema

CC component owner: @CurtizJ @alexey-milovidov

Analysis metadata

comp-mergetree · Severity P2 · Finding phase_d_pr110936

  • Verified against master build 01575fe81d13 (aarch64)
  • Feature not present (repro inconclusive — the affected code path postdates these releases): 26.5, 26.3, 25.8
  • Caused by: MergeTree Continuous Query #105114 (commit 58cab3636bba, found by bisecting in 10 steps)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

7 participants