Repository navigation
Rebalance the work after File, URL and object storage reads with at least as many files as threads - #125275
Rebalance the work after File, URL and object storage reads with at least as many files as threads#125275groeneai wants to merge 14 commits into
Conversation
…east as many files as threads ReadFromFile, ReadFromURL and ReadFromObjectStorageStep give whole files to min(max_threads, files) streams and add a post-read Resize only when there are fewer streams than threads (ClickHouse#48525). With at least as many files as threads, stream i feeds only chain i, so a file whose rows survive a selective filter keeps one thread busy: ClickBench Q40 over the 100 partitioned Parquet files sends 406063 of 722688 rows to one aggregator on 4 threads. Nothing downstream rebalances: AggregatingStep's strict N to N resize is a no-op below 48 streams (ClickHouse#77112), and StrictResizeProcessor closes the outputs it cannot pair, so one heavy input still feeds one output. AffinityResizeProcessor (N to N) pairs input i with output i. While input i is not finished, output i takes chunks only from it, and input i is asked for data only when an output it may feed waits, so equally loaded streams run as with a direct connection (no read-ahead, which would for example check a staler top-K threshold). Once an input finishes, its output takes chunks of the other inputs; a chunk of an input whose output finished goes to any waiting output. The needed flag of each input is cached, so a port is written only when the wanted value changes instead of two CAS round trips per input on every prepare under the node mutex. With many streams the processor is split into groups of min_outstreams_per_resize_after_split streams, as Pipe::resize splits Resize to avoid contention on one processor. The documentation of the setting now covers AffinityResize. The three read steps share resizeOutputAfterReading(). Nothing changes with parallelize_output_from_storages = 0, with input_format_parquet_preserve_order = 1, or for object storage tables with a sorting key, which may be read in order. A plain Resize N to N was measured too: it regresses GROUP BY URL (Q34, 4 threads, 1.023 [1.003, 1.031], n = 20) and a balanced 16-file aggregation (1.22x at 8 threads), while this processor is neutral on both. The analysis and the first version of the patch are from ClickHouse#125199. Closes ClickHouse#125199 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the AffinityResizeProcessor and resizeOutputAfterReading doc comments to three lines each, shorten the needed-flag comment to one line, drop an obvious section comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 4 findings over 4 rounds, the last one clean) plus my own cold review; rows 7-8 are from the review of the follow-up commit.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261011-223000 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261011-222100 |
|
Workflow [PR], commit [a0ac001] AI ReviewSummaryThis PR rebalances work after Findings❌ Blockers
Tests
Final Verdict❌ Block — Preserve ordered streams in the widening branch and cover the two-input case. No new inline review was submitted; the retained finding already has an author-resolved thread. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes24 object files changed (+95.18 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units333 translation units recompiled, 2492 s compile time in total, 333 of them have a recent master baseline. |
…uet row order File, URL and object storage engines read with the format settings stored at CREATE (`SETTINGS input_format_parquet_preserve_order = 1`), but the check that allows resizing the output of the read used the query setting. So such a table read with at least as many files as threads got `AffinityResize`, which reorders the rows of a file once a stream takes chunks of another one (measured: 5 of 5 runs out of order, master 0 of 5), and with fewer files than threads the existing `Resize`. `checkParallelizeOutputAfterReading` now takes the table's format settings. The object storage step gets the table's answer from `read`, because the step's own format settings may be changed for the data lake reader: Iceberg forces `preserve_order` for its position deletes, which run inside the source. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR found no performance changes. It adds an AffinityResize step after file, url and object-storage reads and passes table-level format settings into the preserve-order check. ClickBench and TPC-H read from MergeTree tables, so neither benchmark runs the changed code. The two flagged ClickBench queries, Q31 (+13.4%) and Q34 (+5.5%), stay inside master's normal range, and their CPU time barely moved (about 2.79 s and 14.5 s on both sides), so leaving them as no-change is correct. The PR's runs for the two benchmarks also shared a machine, which adds noise to wall-clock time. The new storage_read_affinity_resize perf test is the right place to judge this change, and it was not part of this comparison. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
The performance test runner expands every `{name}` in a query as a
substitution placeholder, so `{_partition_id}` failed with
`KeyError: '_partition_id'` and the test never ran. The braces are
doubled now.
The data is also 4 times larger (128M rows, 8M per file). With 2M rows
in the file the filter keeps, the skewed query took about 25 ms and was
slower with the rebalancing (0.028 s against 0.022 s without it, 11 runs
each, `max_threads = 8`): too little aggregation work to pay for the
merge of 8 hash tables. With 8M rows it is 0.030 s against 0.050 s, the
unfiltered control is unchanged (0.152 s against 0.157 s) and the fill
takes about 3 s.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 68dabecEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261012-170014 |
…ren cannot deliver `ReadFromMerge::requestReadingInOrder` asked only the `ReadFromMergeTree` steps of each child plan. A child plan with no such step (an Iceberg table read through `ReadFromObjectStorageStep`, whose metadata carries a sorting key from its Iceberg sort order) was accepted without being asked, so the planner replaced the full sort with a merge of unsorted streams. ORDER BY [DESC] [LIMIT n], DISTINCT, LIMIT BY and aggregation in order over `merge()` of such a table returned wrong results, and in debug builds the in-order DISTINCT tripped the `checkEqualRangeEndAssumeSorted` assertion (AST fuzzer, STID 2508-31ed). `recursivelyApplyToReadingSteps` now rejects a reading leaf that is neither a `ReadFromMergeTree` nor a `ReadNothingStep`. `ReadFromMerge::canReadInOrder(direction)` replaces `canReadInReverseOrder` and asks every reading step of every child plan without switching any of them. `requestReadingInOrder` calls it before it switches the children, so in a mixed `Merge` no `MergeTree` child is left reading in order when another child rejects the request. The `topKThroughJoin` probe calls it for both directions, so for an ascending `ORDER BY ... LIMIT` over such a `Merge` it no longer defers to an in-order read that pass 2 declines (which left neither optimization applied). CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125275&sha=68dabec672d4b2e357a16f21849b2eb329fe931d&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 Found on: ClickHouse#125275 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…er-file-reads # Conflicts: # src/Processors/QueryPlan/ReadFromObjectStorageStep.h
Master now rejects UInt64 columns on CREATE of an Iceberg table (ClickHouse#118596), so the test failed with BAD_ARGUMENTS after the merge of master. The values are non-negative, so the reference is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…05361 `IStorageURLBase::parallelizeOutputAfterReading` and the object storage read step of a data lake table read the table's own format settings, and only `File` and `S3` tables were asserted. A URL table and an `IcebergLocal` table with `input_format_parquet_preserve_order = 1` must get neither `AffinityResize` nor a widening `Resize`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - abf8b4bEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261026-160013 |
|
Fixing PR for the |
|
On a 16-core Graviton3, this PR makes ClickBench Q40 over the 100 partitioned Parquet files 28% faster at 16 threads. At 4 threads the gain is 14%, as in the description. The other
Times are medians; ratios are geometric means of paired per-round ratios. Process CPU time (perf Method
|
…er-file-reads # Conflicts: # src/Formats/FormatFactory.h # src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp # src/Storages/ObjectStorage/StorageObjectStorage.cpp
Master now refuses the post-read resize when `input_format_vortex_preserve_order` is set, and decides it for a data lake with `checkParallelizeOutputAfterReadingForAnyFormat`. The merge passes the table's own format settings to both checks, as this PR already does for Parquet: a `File(Vortex)` table with the setting in its `SETTINGS` must keep its streams instead of getting `AffinityResize`, and a data lake table with a stored Parquet or Vortex order setting must not be resized either. With the Vortex branch reading only the query setting, the two new asserts give 1 instead of 0 (`AffinityResize 2 → 2` at 2 threads, `Resize 3 → 8` at 8 threads). With the data lake check ignoring the table settings, the two stored-order Iceberg asserts of 05361 give 1 instead of 0. The test is separate from 05361 because the Vortex format is not in the fast test and MSan builds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Under ClickBench's server protocol, this PR makes Q39 43% faster at 16 threads on x86, more than the 28% that my one-shot ClickBench has run
Q39 uses the same CPU and spreads it over 5.75 instead of 3.2 busy cores. The extra CPU is specific to Q1 and Q7: Q19 and Q29, also short scans of all 100 files, change by less than 2%. I have not profiled where it goes. My one-shot runs above did not resolve this cost: Q1 (Q2 there) was within noise. Method
|
|
Correction to my previous comment: the extra cost is not specific to Q1 and Q7. Q0,
I did not measure server CPU for Q0. Q0 reads no columns: the row counts come from the Parquet metadata, so there is no per-row work after the read. Master adds no |
The `AffinityResize` node was shared by all streams of its group, so every chunk took its node lock twice, from every thread. On short scans with a cheap filter that cost about 15 us of CPU per chunk at 16 threads: ClickBench Q1 and Q7 (0-based) became 6-9% slower with 12-14% more server CPU (measured in the PR), and 100 Native files read in 1600 chunks went from 51.9 to 75.0 ms of CPU. Now each stream passes its chunks to its own consumer through an `Overflow` processor, which gives a chunk to its second output only when the first one cannot take it. The second outputs of a group go into a `Resize`, which only a `Concat` whose own stream has run out of files reads. So only the chunks that move to another stream pass the shared node. `Concat` gets an option to ask its input for a chunk only when its output can take it: with read-ahead it re-armed the source on another thread, +2-3% of CPU on the same benchmark. `AffinityResizeProcessor` and its tests are removed, and `min_outstreams_per_resize_after_split` again sizes only `Resize` nodes, so its documentation is back to master's. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Fixed in f90ba74 and 347c204: a stream's chunks now go through the shared node only when its own consumer is busy and another stream has run out of files, and reads that only count rows (Q0) keep master's pipeline, which on 16 cores here brings Q1 and Q7 (0-based) to within 1-1.5% of master's CPU while Q39 stays at 0.51; the description has the numbers. |
The chunks of a read that only counts rows (`optimize_count_from_files`) carry no data, so there is nothing after the read worth moving to another stream, and the two processors per stream are pure overhead: ClickBench Q0 (`SELECT COUNT(*) FROM hits` over the 100 partitioned files) was 60% slower with the first version of this PR (measured in the PR) and still 9% slower in median, with 20% more CPU, after the previous commit. Such reads now keep their streams, as reads that may be in order do. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…file Since ClickHouse#125738 a single local Parquet file is read by one source per bucket, so the last query of the test reads its file by two streams for two threads. With as many streams as threads, the output of the read is now rebalanced, so the pipeline has `Overflow`, `Resize` and `Concat` above the two `File` sources. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The remaining balanced-read cost comes from where the tail chunks go, and a sticky variant of the shared In the perf test's balanced query each file holds its own 62.5K groups, so a chunk taken by another stream brings groups its aggregator has not seen, and In the patch below, an output of the shared node keeps taking chunks from the input that gave it its last chunk (at first its own) until that input finishes. An input is needed only while a waiting output sticks to it, or while a waiting output has nothing left to stick to. r7g.4xlarge (16 Neoverse-V1 cores), release build of the PR's diff on master b8c902a (master = the same build with
Two more runs gave 0.927 and 0.938 for the first row, and its memory drops from 733 MB to 534 MB (master 462 MB). Asking for overflow chunks only while an output waits, without stickiness, gives 0.985 [0.961, 1.009], so the stickiness is what matters. At 8 threads the balanced cost is 2-3.5% here and the patch does not change it. ClickBench Q2 and Q8 use 2.7% and 2.4% more CPU than master with wall time within noise, close to your 1-1.5%. When both variants run on one server, the hash table size statistics and the adaptive aggregator's verdict are keyed by the query, not the settings, so a run with On a 4-vCPU x86 VM (2 cores with HT, default Results are identical across variants; Q39-Q41 differ only in the tie order at Patch on ba12fa2diff --git a/src/Storages/prepareReadingFromFormat.cpp b/src/Storages/prepareReadingFromFormat.cpp
index 79a640a..1fdb65b 100644
--- a/src/Storages/prepareReadingFromFormat.cpp
+++ b/src/Storages/prepareReadingFromFormat.cpp
@@ -27,7 +27,9 @@
#include <boost/algorithm/string/predicate.hpp>
+#include <limits>
#include <unordered_map>
+#include <vector>
namespace DB
{
@@ -550,6 +552,223 @@ size_t clampClusterFunctionNumStreams(UInt64 num_streams)
return std::min<UInt64>(num_streams, 256 * getNumberOfCPUCoresToUse());
}
+namespace
+{
+
+/// N inputs and N outputs; input i and output i belong to stream i (see `resizeOutputAfterReading`), and output i asks for
+/// chunks only after stream i has run out of data. An output keeps taking the chunks of the input that gave it its last chunk,
+/// initially its own input, until that input finishes. So a stream that helps the others takes the chunks of one stream at a
+/// time, instead of spreading the groups of every stream over every aggregation state. An input is needed only while a waiting
+/// output sticks to it, or while a waiting output has no unfinished input to stick to.
+class StickyResizeProcessor final : public IProcessor
+{
+public:
+ StickyResizeProcessor(SharedHeader header, size_t num_streams)
+ : IProcessor(InputPorts(num_streams, header), OutputPorts(num_streams, header))
+ {
+ }
+
+ String getName() const override { return "StickyResize"; }
+
+ Status prepare(const UpdatedInputPorts & updated_inputs, const UpdatedOutputPorts & updated_outputs) override
+ {
+ if (!initialized)
+ initialize();
+
+ for (auto * port : updated_outputs)
+ {
+ const size_t output_number = output_index.at(port);
+ auto & output = outputs_state[output_number];
+ if (output.finished)
+ continue;
+
+ if (port->isFinished())
+ {
+ output.finished = true;
+ output.waiting = false;
+ ++num_finished_outputs;
+ }
+ else if (!output.waiting && port->canPush())
+ {
+ output.waiting = true;
+ waiting_outputs.push_back(output_number);
+ }
+ }
+
+ if (num_finished_outputs == outputs_state.size())
+ {
+ for (auto & input : inputs)
+ input.close();
+ return Status::Finished;
+ }
+
+ for (auto * port : updated_inputs)
+ updateInput(input_index.at(port));
+
+ /// Serve the waiting outputs in the order they started to wait.
+ size_t still_waiting = 0;
+ for (size_t i = 0; i < waiting_outputs.size(); ++i)
+ {
+ const size_t output_number = waiting_outputs[i];
+ auto & output = outputs_state[output_number];
+ if (!output.waiting)
+ continue;
+
+ if (!output.port->canPush())
+ {
+ /// The consumer does not ask for data now; it asks again with a port update.
+ output.waiting = false;
+ continue;
+ }
+
+ size_t from = output.source;
+ if (!inputs_state[from].has_data)
+ {
+ if (!inputs_state[from].finished)
+ {
+ waiting_outputs[still_waiting++] = output_number;
+ continue;
+ }
+
+ /// The input this output stuck to has finished: take the chunk that has waited the longest and stick to its input.
+ from = oldestInputWithData();
+ if (from == NONE)
+ {
+ waiting_outputs[still_waiting++] = output_number;
+ continue;
+ }
+ }
+
+ auto & input = inputs_state[from];
+ output.port->pushData(input.port->pullData(/* set_not_needed = */ true));
+ input.has_data = false;
+ input.needed = false;
+ output.waiting = false;
+ output.source = from;
+ updateInput(from);
+ }
+ waiting_outputs.resize(still_waiting);
+
+ if (num_finished_inputs == inputs_state.size())
+ {
+ for (auto & output : outputs)
+ output.finish();
+ return Status::Finished;
+ }
+
+ updateNeeded();
+
+ return waiting_outputs.empty() ? Status::PortFull : Status::NeedData;
+ }
+
+private:
+ static constexpr size_t NONE = std::numeric_limits<size_t>::max();
+
+ struct InputState
+ {
+ InputPort * port = nullptr;
+ UInt64 data_order = 0;
+ bool has_data = false;
+ bool finished = false;
+ bool needed = false;
+ bool wanted = false;
+ };
+
+ struct OutputState
+ {
+ OutputPort * port = nullptr;
+ size_t source = 0;
+ bool waiting = false;
+ bool finished = false;
+ };
+
+ void initialize()
+ {
+ initialized = true;
+ for (auto & input : inputs)
+ {
+ input_index.emplace(&input, inputs_state.size());
+ inputs_state.push_back({.port = &input});
+ }
+ for (auto & output : outputs)
+ {
+ output_index.emplace(&output, outputs_state.size());
+ outputs_state.push_back({.port = &output, .source = outputs_state.size()});
+ }
+ }
+
+ void updateInput(size_t input_number)
+ {
+ auto & input = inputs_state[input_number];
+ if (input.finished)
+ return;
+
+ if (input.port->isFinished())
+ {
+ input.finished = true;
+ input.has_data = false;
+ ++num_finished_inputs;
+ }
+ else if (!input.has_data && input.port->hasData())
+ {
+ input.has_data = true;
+ input.data_order = ++data_counter;
+ }
+ }
+
+ size_t oldestInputWithData() const
+ {
+ size_t res = NONE;
+ for (size_t i = 0; i < inputs_state.size(); ++i)
+ if (inputs_state[i].has_data && (res == NONE || inputs_state[i].data_order < inputs_state[res].data_order))
+ res = i;
+ return res;
+ }
+
+ void updateNeeded()
+ {
+ bool has_free_output = false;
+ for (auto & input : inputs_state)
+ input.wanted = false;
+ for (size_t output_number : waiting_outputs)
+ {
+ auto & input = inputs_state[outputs_state[output_number].source];
+ if (input.finished)
+ has_free_output = true;
+ else
+ input.wanted = true;
+ }
+
+ for (auto & input : inputs_state)
+ {
+ if (input.finished || input.has_data)
+ continue;
+
+ const bool need = has_free_output || input.wanted;
+ if (need == input.needed)
+ continue;
+
+ input.needed = need;
+ if (need)
+ input.port->setNeeded();
+ else
+ input.port->setNotNeeded();
+ }
+ }
+
+ std::vector<InputState> inputs_state;
+ std::vector<OutputState> outputs_state;
+ std::unordered_map<const InputPort *, size_t> input_index;
+ std::unordered_map<const OutputPort *, size_t> output_index;
+ std::vector<size_t> waiting_outputs;
+ UInt64 data_counter = 0;
+ size_t num_finished_inputs = 0;
+ size_t num_finished_outputs = 0;
+ bool initialized = false;
+};
+
+}
+
void resizeOutputAfterReading(Pipe & pipe, size_t resize_to, bool keep_streams, size_t min_streams_per_group)
{
const size_t output_ports = pipe.numOutputPorts();
@@ -571,7 +790,7 @@ void resizeOutputAfterReading(Pipe & pipe, size_t resize_to, bool keep_streams,
for (size_t g = 0, next = 0; g < groups; ++g)
{
const size_t group_size = output_ports / groups + (g < output_ports % groups ? 1 : 0);
- auto resize = std::make_shared<ResizeProcessor>(header, group_size, group_size);
+ auto resize = std::make_shared<StickyResizeProcessor>(header, group_size);
auto resize_input = resize->getInputs().begin();
auto resize_output = resize->getOutputs().begin();
for (size_t i = 0; i < group_size; ++i, ++next, ++resize_input, ++resize_output)
diff --git a/tests/queries/0_stateless/02725_parquet_preserve_order.reference b/tests/queries/0_stateless/02725_parquet_preserve_order.reference
index 3b141c3..508bc7b 100644
--- a/tests/queries/0_stateless/02725_parquet_preserve_order.reference
+++ b/tests/queries/0_stateless/02725_parquet_preserve_order.reference
@@ -9,6 +9,6 @@ ExpressionTransform
ExpressionTransform × 2
(ReadFromFile)
Concat × 2 2 → 1
- Resize 2 → 2
+ StickyResize 2 → 2
Overflow × 2 1 → 2
File × 2 0 → 1
diff --git a/tests/queries/0_stateless/05361_storage_read_affinity_resize.sql b/tests/queries/0_stateless/05361_storage_read_affinity_resize.sql
index bc72671..3b443ec 100644
--- a/tests/queries/0_stateless/05361_storage_read_affinity_resize.sql
+++ b/tests/queries/0_stateless/05361_storage_read_affinity_resize.sql
@@ -26,8 +26,8 @@ SELECT countIf(trimLeft(explain) = 'Overflow × 2 1 → 2') FROM (EXPLAIN PIPELI
-- A single file is resized to `max_threads`.
SELECT countIf(trimLeft(explain) LIKE 'Overflow%'), countIf(trimLeft(explain) = 'Resize 1 → 2') FROM (EXPLAIN PIPELINE SELECT k FROM file(currentDatabase() || '_05361_0.parquet'));
-- With many streams the streams are split into groups of `min_outstreams_per_resize_after_split`.
-SELECT position(arrayStringConcat(groupArray(trimLeft(explain)), '|'), 'Concat × 4 2 → 1|Resize × 2 2 → 2|Overflow × 4 1 → 2') > 0 FROM (EXPLAIN PIPELINE SELECT k % 7 AS g, count() FROM file(currentDatabase() || '_05361_*.parquet') GROUP BY g) SETTINGS max_threads = 4, min_outstreams_per_resize_after_split = 2;
-SELECT position(arrayStringConcat(groupArray(trimLeft(explain)), '|'), 'Concat × 4 2 → 1|Resize 4 → 4|Overflow × 4 1 → 2') > 0 FROM (EXPLAIN PIPELINE SELECT k % 7 AS g, count() FROM file(currentDatabase() || '_05361_*.parquet') GROUP BY g) SETTINGS max_threads = 4, min_outstreams_per_resize_after_split = 0;
+SELECT position(arrayStringConcat(groupArray(trimLeft(explain)), '|'), 'Concat × 4 2 → 1|StickyResize × 2 2 → 2|Overflow × 4 1 → 2') > 0 FROM (EXPLAIN PIPELINE SELECT k % 7 AS g, count() FROM file(currentDatabase() || '_05361_*.parquet') GROUP BY g) SETTINGS max_threads = 4, min_outstreams_per_resize_after_split = 2;
+SELECT position(arrayStringConcat(groupArray(trimLeft(explain)), '|'), 'Concat × 4 2 → 1|StickyResize 4 → 4|Overflow × 4 1 → 2') > 0 FROM (EXPLAIN PIPELINE SELECT k % 7 AS g, count() FROM file(currentDatabase() || '_05361_*.parquet') GROUP BY g) SETTINGS max_threads = 4, min_outstreams_per_resize_after_split = 0;
-- A read that only counts rows keeps its streams.
SELECT countIf(trimLeft(explain) LIKE 'Overflow%') FROM (EXPLAIN PIPELINE SELECT count() FROM file(currentDatabase() || '_05361_*.parquet')) SETTINGS optimize_count_from_files = 1, optimize_trivial_count_query = 1;
SELECT countIf(trimLeft(explain) LIKE 'Overflow%') FROM (EXPLAIN PIPELINE SELECT count() FROM s3(s3_conn, filename = currentDatabase() || '_05361/data_*.parquet')) SETTINGS optimize_count_from_files = 1, optimize_trivial_count_query = 1; |
The shared `Resize` behind the per-stream `Overflow` processors kept all its inputs needed, so every stream parked a chunk in it, and a stream that ran out of files took those chunks from every other stream in turn. When the files hold disjoint groups, each stolen chunk brings new groups to its aggregator: a balanced 16-file aggregation at 16 threads was 1.17x slower than master's pipeline and used 455 MB instead of 149 MB. `StickyResizeProcessor` replaces it. An output keeps taking the chunks of the input that gave it its last chunk until that input finishes, and an input is needed only while a waiting output sticks to it (or has nothing left to stick to). Proposed and measured by @ snelheidai on ClickHouse#125275. The documentation of `min_outstreams_per_resize_after_split`, which sizes its groups, names it. Release build, one server per variant (the hash table statistics are keyed by query, so one server would let one variant tune the other), 16 cores: - balanced 16 files (perf test query 2), 16 threads: master 204 ms, before 238 ms (1.166 [1.145, 1.187]), now 213 ms (1.045 [1.015, 1.076]); memory 149 / 455 / 246 MB. At 8 threads 1.056 before, 1.047 now (unchanged). - skewed (perf test query 1): 0.83 at 16 threads, 0.78 at 8, as before. - groups shared by all files: 0.93 at 16 threads, as before. - ClickBench (100 files), now vs before: at 16 threads Q39 0.92 [0.86, 0.99], Q40 0.93 [0.82, 1.05] (0.50 of master), Q1, Q2, Q8, Q15, Q34, Q37, Q41 within noise; at 32 threads Q2 and Q40 within noise, Q37 1.02 [1.00, 1.04]. - 100 Native files of 655-row chunks, 16 threads: 0.997 [0.970, 1.025]. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Adopted in a0ac001 ( |
Closes: #125199
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reading many files with
file,url,s3and other object storage and data lake engines no longer leaves the work after the read to one thread when one file holds most of the rows that pass a filter: a reading stream that has run out of files now takes the chunks that the other streams cannot process yet. ClickBench Q40 over the 100 partitioned Parquet files is 1.6x faster with 4 threads and 2x faster with 16 threads.Description
ReadFromFile,ReadFromURLandReadFromObjectStorageStepgive whole files tomin(max_threads, files)streams, and add aResizeonly when there are fewer streams than threads (#48525). With at least as many files as threads, stream i feeds only chain i. In ClickBench Q40 (100 files, 4 threads) one aggregator gets 406063 of 722K rows.After these reads, each stream passes through an
Overflowprocessor into aConcatof its own chunks and, once its stream has run out of files, the chunks of aStickyResizeshared by its group.Overflowpasses a chunk to it only when its own consumer cannot take it.StickyResizeasks for chunks only while an output waits, and an output takes the chunks of one stream until that stream finishes, so an aggregator meets few new groups.Concatcan now ask for a chunk only when its output can take it. Groups havemin_outstreams_per_resize_after_splitstreams, as inPipe::resize. Nothing changes withparallelize_output_from_storages = 0,input_format_parquet_preserve_order = 1orinput_format_vortex_preserve_order = 1(now also when set in the table'sSETTINGS), for object storage tables with a sorting key, or for reads that only count rows. This also covers the buckets of one Parquet file (#125738).Release build, one server per variant, PR / master's pipeline (
parallelize_output_from_storages1 vs 0), mean and 2 SE. 16 threads: Q40 0.51 [0.45, 0.57], Q37 0.89, Q15 and Q34 0.97, Q2 and Q8 0.99 (+3-4% CPU); the performance test's skewed query 0.69 and its balanced query (each file has its own groups) 1.06 [1.04, 1.08]. 4 threads: Q40 0.63, skewed 0.69, balanced 1.01. On 2 cores with HT, the skewed query is 1.15x slower at 4 threads (Q40 0.80), like master'sResizefor 3 files (1.11x).The analysis, the first patch and the measurements behind this design come from @ snelheidai (#125199). Tests: gtests, stateless tests (File, S3, URL, Iceberg, Vortex), a performance test.
Workflow [PR]
Sync PR [sync-upstream/pr/125275]