Repository navigation
Clamp max_streams_for_merge_tree_reading to avoid std::length_error - #110936
alexey-milovidov merged 10 commits into
Conversation
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-1:20260718-104200 |
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).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-1:20260718-104200 |
|
cc @vdimir @antaljanosbenjamin — could you review this? It clamps |
|
Workflow [PR], commit [3eb2345] Summary: ✅
AI ReviewSummaryThis PR clamps Findings
Final VerdictRequest changes. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code |
…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]>
…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]>
|
CI fix (df727eb): the new test 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 |
…ms-for-merge-tree-reading
CI finish ledger - df727ebCI finished on head df727eb with two AST-fuzzer segfaults, both non-PR-caused (trunk
Our new test Session id: cron:our-pr-ci-monitor:20260719-020000 |
CI finish ledger — 858ce01Every failure below has an owner: a fixing PR. None is caused by this PR's diff (a
Note: the 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(); |
There was a problem hiding this comment.
This seems like not the good level of abstraction. Cannot we do this clamping in SettingQuirks.cpp::doSettingsSanityCheckClamp?
There was a problem hiding this comment.
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]>
CI finish ledger - 5d11196Every 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
Session id: cron:our-pr-ci-monitor:20260721-173000 |
…ms-for-merge-tree-reading
CI finish ledger for 5d11196Every 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.
174 of 174 check-runs completed, 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: I have merged current master into the branch, so the fix is now present ( 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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code |
CI finish ledger - 7d086a4174 check-runs, all completed, 1 failed. It has an owner.
Not PR-caused. This pull request touches I checked the obvious candidate owner and it does not qualify. #112003 fixed the quadratic Searching open and closed pull requests turns up no fix for the cancellation half, so a fix task Over 30 days CIDB records this hung-check signature 89 times on master and across roughly 300 Session id: cron:our-pr-ci-monitor:20260802-073000 |
|
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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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 units8 translation units recompiled, 39 s compile time in total, 8 of them have a recent master baseline. |
CI finish ledger - 3eb2345CI is fully finished on this head: 177 check-runs, 160 success, 17 skipped, 0 failures. Nothing is owed on this head: there is no failure to assign an owner to.
This head is the conflict-resolution merge ( Session id: cron:our-pr-ci-monitor:20260815-203000 |
ReproducerCREATE 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 * coresResults:
No backport suggested — below the bar for ClickHouse's strict backport policy. CC introducing PR author: @Michicosun CC component owner: @CurtizJ @alexey-milovidov Analysis metadata
|
Closes: #110932
Changelog category (leave one):
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 pathologicalmax_streams_for_merge_tree_readingvalue (near the maximum ofUInt64) together withallow_asynchronous_read_from_io_pool_for_merge_tree = 1. The setting is now clamped to the same ceiling asmax_threads.Description
ReadFromMergeTree's constructor, on the async read path withrequested_num_streams != 1, setrequested_num_streams = std::max(requested_num_streams, max_streams_for_merge_tree_reading). A near-UINT64_MAXsetting value then flowed unclamped intopipes.reserve(num_streams)ingroupPartitionsByStreams(andspreadMarkRanges/groupStreamsByPartition), throwingstd::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" ceilingmax_threadsgets. 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%29Trigger 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
26.8.1.1540(included in26.8and later)