Skip to content

Rebalance the work after File, URL and object storage reads with at least as many files as threads - #125275

Open
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:affinity-resize-after-file-reads
Open

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:affinity-resize-after-file-reads

Conversation

@groeneai

@groeneai groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125199

Changelog category (leave one):

  • Performance Improvement

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

Reading many files with file, url, s3 and 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, ReadFromURL and ReadFromObjectStorageStep give whole files to min(max_threads, files) streams, and add a Resize only 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 Overflow processor into a Concat of its own chunks and, once its stream has run out of files, the chunks of a StickyResize shared by its group. Overflow passes a chunk to it only when its own consumer cannot take it. StickyResize asks 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. Concat can now ask for a chunk only when its output can take it. Groups have min_outstreams_per_resize_after_split streams, as in Pipe::resize. Nothing changes with parallelize_output_from_storages = 0, input_format_parquet_preserve_order = 1 or input_format_vortex_preserve_order = 1 (now also when set in the table's SETTINGS), 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_storages 1 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's Resize for 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]

groeneai and others added 2 commits October 11, 2026 22:27
…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 11, 2026
@groeneai

groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ❌ The read-in-order carve-out relied on a step member that the CH Inc-only ReadFromObjectStorageStep::serialize cannot be assumed to carry AGREE, fixed streams are kept for any table with a sorting key, derived from metadata every step has
2 ⚠️ No test reached the keep-streams branch on object storage AGREE, fixed IcebergLocal sorted and unsorted tables in the stateless test; a mutation of the predicate fails exactly those asserts
3 ⚠️ One processor for all streams may bring back the node-lock contention Pipe::resize splits Resize for at 48+ streams AGREE, fixed grouped by min_outstreams_per_resize_after_split, as Pipe::resize does; asserted in the stateless test, re-measured at 64 and 96 threads
4 ⚠️ The documentation of min_outstreams_per_resize_after_split still names only Resize and StrictResize AGREE, fixed the setting's description now covers AffinityResize
5 💡 Helper name equal to IStorage::parallelizeOutputAfterReading AGREE, fixed renamed resizeOutputAfterReading
6 💡 gtests beside a stateless test DISAGREE they cover port orders SQL cannot drive; each fails under a mutation of its rule
7 ❌ A table's stored input_format_parquet_preserve_order was not checked, so AffinityResize reordered that table's rows (5 of 5 runs, master 0 of 5) AGREE, fixed in e481eb8 checkParallelizeOutputAfterReading takes the table's format settings; the object storage step gets the table's answer from read; asserted for File and S3 tables
8 ❌ That answer is a step member the CH Inc-only serializer may not carry DISAGREE a step without it falls back to the query setting, as before; carrying it needs the private serializer

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261011-223000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ClickBench Q40 over the 100 Parquet files, 4 threads: one aggregator gets 406063 of 722688 rows on master, at most 279737 with this change; the new test asserts the pipeline shape (File × 4 vs AffinityResize 4 → 4).
b Root cause explained? The File, URL and object storage reads add a post-read Resize only with fewer streams than threads, so with at least as many files stream i feeds only chain i; nothing downstream rebalances (AggregatingStep's strict resize is a no-op below 48 streams, StrictResize closes unpaired outputs).
c Fix matches root cause? Yes: the rebalancing is added at the site that already rebalances the fewer-streams case, for exactly the case it skipped.
d Test intent preserved / new tests added? New: processor gtests (6 mutants, each fails one), one stateless test for File, S3, URL and Iceberg (pipeline and grouped shape, sorted Iceberg keeps its streams, identical results across max_threads and with the setting off, LIMIT), one performance test.
e Both directions demonstrated? Yes: the test's EXPLAIN assertion gives 0 on the master binary and 1 here; 50/50 randomized runs pass.
f Fix is general across code paths? The three whole-file read steps share one helper; ReadFromMergeTree already balances at mark granularity.
g Fix generalizes across inputs (params/datatypes/wrappers)? Not type-dependent (chunks move whole). Covered 0 to 4 streams, uneven groups, max_threads = 1, exceptions in port data; measured at 4, 16, 64 and 96 threads and on a skewed file set.
h Backward compatible? (maintainer-approved exception only) Yes: no new setting, same results; parallelize_output_from_storages = 0, input_format_parquet_preserve_order = 1 and object storage tables with a sorting key keep today's pipeline.
i Invariants and contracts preserved? All outputs finished closes the inputs, all inputs finished finishes the outputs, an output whose input finished keeps the other inputs asked so it cannot starve; only this processor writes the cached needed flags; each group is its own N to N processor.

Session id: cron:clickhouse-impl-slot-5:20261011-222100

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a0ac001]


AI Review

Summary

This PR rebalances work after File, URL, and object-storage reads using per-stream Overflow and Concat processors with a shared StickyResize. The benchmarks demonstrate the intended improvement and quantify the remaining balanced-read overhead. One previously reported ordering concern remains in the current code; there are no new inline findings.

Findings

❌ Blockers

  • src/Storages/prepareReadingFromFormat.cpp:556 — [dismissed by author -- https://github.com/Rebalance the work after File, URL and object storage reads with at least as many files as threads #125275#discussion_r4244110632] The helper retains the pre-existing widening path before checking keep_streams. An ordered Iceberg read with two files and max_threads = 4 can therefore receive Resize 2 → 4 despite passing keep_streams = true. ResizeProcessor can send chunks from different sorted inputs to the same output, breaking that output's ordering. Meanwhile, requestReadingInOrder allows the optimizer to replace sorting with MergingSortedTransform, which requires sorted inputs; ORDER BY and LIMIT can consequently return incorrect results. The concern still holds because the guard excludes only the equal-width rebalancing branch. Skip widening for ordered reads as well. The author's resolution is respected: the existing thread is left closed, without another reply.
Tests
  • ⚠️ Add a focused ordered Iceberg case with two files, multiple chunks per file, and four threads. Assert that no post-read resize is inserted and compare the ordered result with optimize_read_in_order = 0. The added sorted-table assertions use two threads, so they do not exercise widening. A single sorted input split among several outputs is insufficient to demonstrate the mixing problem.
  • ⚠️ This review used source tracing and the published benchmark evidence; no local ClickHouse build or executable was available for a query-level reproduction.
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.

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a0ac001c5 with master 0e42176d2 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

24 object files changed (+95.18 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/ResizeProcessor.cpp.o 144.41 KiB 199.38 KiB +54.98 KiB (+38.07%)
src/CMakeFiles/dbms.dir/Storages/prepareReadingFromFormat.cpp.o 327.89 KiB 356.05 KiB +28.16 KiB (+8.59%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.68, programs/clickhouse-keeper ×0.68 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.1 s 12.6 s +8.4 s (+199%)
Compile time of recompiled translation units

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

Job report

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

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 31 not_sure 261 296 +13.4% <0.0001 aggregation: This query reads a MergeTree table, so it never reaches the file, url or object-storage resize path this PR changes. CPU time is unchanged and the median stays inside master's normal range.
⚠️ 34 not_sure 1005 1060 +5.5% <0.0001 aggregation: This query does not touch the file, url or object-storage reads that get the new AffinityResize step. It has a noisy history, CPU time is flat and the median stays inside master's normal range.

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
  • StressHouse run: 5e441def-b2c1-4d81-8246-763993d1b9df
  • MIRAI run: 1511ce92-871d-49d3-8810-1d3743c550ef
  • PR check IDs:
    • clickbench_1008804_1791790011
    • clickbench_1008810_1791790011
    • clickbench_1008816_1791790011
    • tpch_adapted_1_official_1008827_1791790011
    • tpch_adapted_1_official_1008839_1791790011
    • tpch_adapted_1_official_1008875_1791790011

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 68dabec

Every failure below has an owner: a fixing PR (mine 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.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-31ed) not from this PR's code: the fuzzer turned the new test 05361 into a merge() read over a sorted Iceberg table, which hits a bug already on master (ReadFromMerge accepts read-in-order for non-MergeTree children); reproduced on a master build without this PR #125383 (mine, open)
PR praktika rollup of the row above #125383 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261012-170014

qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Oct 15, 2026
…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]>
groeneai and others added 3 commits October 26, 2026 11:47
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - abf8b4b

Every failure below has an owner: a fixing PR (mine 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.

Check / test Reason Owner / fixing PR
Code Review CI infrastructure, not this diff: all 3 review attempts ended with Selected model is at capacity. Please try a different model., and the job retries the same model after 2 s and 4 s. The job failed the same way on 5 other PRs between 13:11 and 14:50 UTC today a fix task is created (investigating at full effort - fixing-PR link to follow here)
PR praktika rollup of the row above a fix task is created (the same one as the row above)

Mergeable Check, Finish Workflow and CH Inc sync are green. CIDB has no FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261026-160013

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Code Review job failure (model at capacity) in the CI finish ledger above: #127861

@snelheidai

Copy link
Copy Markdown

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 CounterID = 62 queries and five full-table controls show no significant slowdown.

ClickBench query (1-based) Threads master → PR, ms PR/master [95% CI]
Q40 16 145.5 → 105.0 0.717 [0.677, 0.759]
Q40 4 175.0 → 148.0 0.857 [0.780, 0.941]
Q37–Q39, Q41–Q43 16 35.5–85.0 on master 0.999–1.051, all CIs include 1 (largest: Q39, 1.051 [0.994, 1.110])
Q37–Q39, Q41–Q43 4 36.0–92.0 on master 0.979–1.027, all CIs include 1
Q13 (GROUP BY SearchPhrase) 16 232.0 → 227.0 0.978 [0.964, 0.994]
Q34 (GROUP BY URL) 16 900.5 → 878.5 0.977 [0.965, 0.990]
Q2, Q20, Q21 16 38.0–483.5 on master 0.985–1.003, all CIs include 1

Times are medians; ratios are geometric means of paired per-round ratios. Process CPU time (perf task-clock) is 5% higher for Q40 at 16 threads (609 → 641 ms) and 3.5% higher at 4 threads; the other queries are within about ±3%. Four concurrent clients, each running Q37–Q43 three times at 16 threads, took 4.36 s with the PR and 4.55 s on master (median of 3 rounds; noisy). Full results are identical between the builds (checked for Q37–Q43, Q21 and Q34).

Method
  • Builds: master 607c2a3, and the same commit with this PR (abf8b4b) merged. The merge has three small conflicts with master's data-lake format check (checkParallelizeOutputAfterReadingForAnyFormat) in FormatFactory.h, ReadFromObjectStorageStep.cpp and StorageObjectStorage.cpp, resolved by keeping master's check and this PR's resize. This benchmark reads a File table, so it does not reach that code.
  • Data: ClickBench clickhouse-parquet-partitioned (ENGINE = File(Parquet, 'hits_*.parquet')), files in the page cache.
  • One clickhouse local --time process per query with --max_threads=T --max_parsing_threads=T, pinned to T cores with taskset.
  • 8 paired rounds at 16 threads and 5 at 4 threads, rotating the build order. 95% CI: Student-t on log ratios.
  • Correctness: count(), sum(cityHash64(*)) of each full result without LIMIT. Q40's LIMIT 10 OFFSET 1000 output varies between runs on master too, because of ties in PageViews.

…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]>
@snelheidai

Copy link
Copy Markdown

Under ClickBench's server protocol, this PR makes Q39 43% faster at 16 threads on x86, more than the 28% that my one-shot clickhouse local runs on Graviton3 showed above. Q36 is 16% faster. Q1 and Q7 become 0.7–0.9 ms (6–9%) slower and use 12–14% more server CPU.

ClickBench has run clickhouse-parquet-partitioned through clickhouse-server since ClickHouse/ClickBench@bbc2118, restarting it before each query; the hot time is the best of runs 2 and 3. Query numbers here are 0-based, as on benchmark.clickhouse.com, so Q39 is the description's Q40.

Query (0-based) Median hot time, ms: master → PR PR/master [95% CI]
Q39 114 → 64.5 0.571 [0.536, 0.608]
Q36 53.5 → 45.5 0.837 [0.796, 0.881]
Q12 192 → 180 0.932 [0.921, 0.943]
Q14 232 → 217.5 0.944 [0.925, 0.963]
Q32–Q34 500–834 on master 0.972–0.988, all CIs below 1
Q1 9 → 10 1.111 (9 vs 10 ms in all 10 rounds)
Q7 10 → 11 1.077 [1.023, 1.135]
Q19, Q20, Q27, Q37, Q38, Q40–Q42 11–550 on master 0.990–1.023, all CIs include 1

clickhouse benchmark -c1 -i200 against the warm server, with two alternating passes per build, resolves the short queries better:

Query Time per query, ms: master → PR Server CPU per query, ms
Q1 9.92 → 10.84 90 → 103
Q7 11.47 → 12.16 101 → 113
Q19 11.30 → 11.34 95 → 96
Q29 29.5 → 29.7 259 → 262
Q39 106.1 → 58.6 339 → 337

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
  • This PR's head 73c3c5e merged onto master b8c902a, against that master; one Release clang-21 build tree without LTO.
  • r6i.8xlarge (Xeon 8375C); server and client pinned to cores 0–15 with taskset; max_threads = max_parsing_threads = 16; the entry's config.yaml and users.yaml; the 100 partitioned files in the page cache, so only hot times are shown.
  • 10 paired rounds after a dropped first round, alternating the build order. Ratios are geometric means of the per-round ratios of hot times; 95% CI: Student-t on log ratios. The client's --time has 1 ms resolution, hence the batch runs.

@snelheidai

Copy link
Copy Markdown

Correction to my previous comment: the extra cost is not specific to Q1 and Q7. Q0, SELECT COUNT(*) FROM hits over the same 100 files, becomes 2.3 ms (60%) slower with the same builds and setup:

Q0 master PR
clickhouse benchmark -c1 -i200, ms per query (two alternating passes) 3.86, 3.76 6.21, 5.96
Hot time under the ClickBench server protocol, ms (7 paired rounds) 3 in every round 6 in six rounds, 5 in one

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 Resize here (16 streams for 16 threads), so the new processor is the only change in this query's pipeline.

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]>
@groeneai

groeneai commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

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.

groeneai and others added 3 commits November 11, 2026 06:20
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]>
@snelheidai

Copy link
Copy Markdown

The remaining balanced-read cost comes from where the tail chunks go, and a sticky variant of the shared Resize removes most of it at 16 threads while keeping Q40.

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 Resize hands a waiting stream chunks of every running stream in turn. With groups shared by all files (key % 1000003 instead of key % 1000000) the same read is 5-9% faster with the PR, so the stealing itself pays.

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 parallelize_output_from_storages = 0), one server per variant, 7-13 warm rounds, wall time ratio with 95% CI (ClickBench numbers 1-based):

Query Threads PR / master PR + patch / PR
perf test Q2 (balanced, 16 files) 16 1.124 [1.091, 1.159] 0.926 [0.903, 0.948]
perf test Q2 8 1.018 [0.987, 1.050] 1.006 [0.967, 1.048]
perf test Q1 (one heavy file) 16 0.672 [0.656, 0.688] 1.003 [0.978, 1.028]
balanced, groups shared by all files 16 0.928 [0.900, 0.957] 0.996 [0.959, 1.034]
ClickBench Q40, 100 files 16 0.616 [0.555, 0.683] 1.004 [0.926, 1.088]
ClickBench Q2, Q8, Q15, Q34, Q37, Q39, Q41 16 0.97-1.03, all n.s. 0.95-1.04, all n.s.

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 parallelize_output_from_storages = 1 changes the next run of the same query with 0. At 16 threads this made the balanced query alternate between about 160 and 210 ms with the run order, for master's pipeline too. One server per variant avoids it.

On a 4-vCPU x86 VM (2 cores with HT, default max_threads 4), perf test Q1 is 4.8% slower with the PR (1.048 [1.012, 1.084], CPU +11%): master already keeps about 1.85 cores busy decoding Parquet there, so the stolen chunks mostly add the cost of rebuilding file 0's groups in more aggregators.

Results are identical across variants; Q39-Q41 differ only in the tie order at OFFSET 1000, and their full aggregation results match. Against master's pipeline, 676 queries (1-64 threads, LIMIT, throwIf, timeout_overflow_mode = 'break', 64 files in two groups) gave no difference or hang. The patch renames the processor in the EXPLAIN checks of 05361 and 02725; I did not run those two tests. The class is local to prepareReadingFromFormat.cpp only to keep my rebuilds small; it could sit next to OverflowProcessor with a gtest.

Patch on ba12fa2
diff --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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Adopted in a0ac001 (StickyResizeProcessor next to OverflowProcessor, with gtests); the description has the updated numbers.

This branch has not been deployed

No deployments
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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

2 participants