Skip to content

Speed up window functions by evaluating each MergeTree partition independently - #114783

Merged
nihalzp merged 28 commits into
ClickHouse:masterfrom
nihalzp:window-partitions-independently
Aug 24, 2026
Merged

nihalzp merged 28 commits into
ClickHouse:masterfrom
nihalzp:window-partitions-independently

Conversation

@nihalzp

@nihalzp nihalzp commented Aug 14, 2026 •

Copy link
Copy Markdown
Member
image

Related: #108326
Related: #114645

A window function plan sorts its input partitioned by the window PARTITION BY columns: every row is reshuffled across streams by ScatterByPartitionTransform (a hash pass over the PARTITION BY columns plus a repack of every column of every row through a full cross-stream Resize), so that whole window partitions land in single streams before the per-stream sort and WindowTransform. If the partition expression of the MergeTree table is a deterministic function of the window PARTITION BY columns, the reading will now emit each partition through a single port instead: every stream already carries whole window partitions, so the scatter is skipped entirely and the read, sort, and window all stay within per-partition streams.

CREATE TABLE test_16 (a UInt64, b UInt64) ENGINE = MergeTree ORDER BY tuple() PARTITION BY sipHash64(a) % 16;
INSERT INTO test_16 SELECT number % 100000, number FROM numbers_mt(30000000);

OPTIMIZE TABLE test_16 FINAL;

EXPLAIN PIPELINE
SELECT a, sum(b) OVER (PARTITION BY a ORDER BY b) FROM test_16
SETTINGS allow_window_partitions_independently = 1, max_threads = 16;
(Expression)
ExpressionTransform × 16
  (Window)
  Resize 16 → 16
    WindowTransform × 16
      (Sorting)
      MergeSortingTransform × 16
        LimitsCheckingTransform × 16
          PartialSortingTransform × 16   <- was: fed through Resize 16 → 1 + ScatterByPartitionTransform 1 → 16, reshuffling every row across streams
            (Expression)
            ExpressionTransform × 16
              (ReadFromMergeTree)
              MergeTreeSelect(pool: ReadPoolInOrder, algorithm: InOrder) × 16 0 → 1   <- per-partition reading (16 partitions → 16 streams)

On test_str_64 (a UInt64, b UInt64, s String) with 30M rows, 100k window partitions over 64 balanced table partitions (PARTITION BY sipHash64(a) % 64), and a 100-byte random string in s, at max_threads = 16:

query off on speedup
SELECT a, s, count(b) OVER (PARTITION BY a) FROM test_str_64 1.014s 0.554s 1.83×
SELECT a, s, sum(b) OVER (PARTITION BY a ORDER BY b) FROM test_str_64 1.492s 0.956s 1.56×

The scatter repacks every column of every row, so the win grows with the row width.

Changelog category (leave one):

  • Performance Improvement

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

Speed up window functions on partitioned MergeTree tables by reading each partition through its own stream and evaluating the windows per partition, skipping the hash scatter that ordinarily reshuffles every row across threads before the window sort. This applies when the table partition expression is a deterministic function of the window PARTITION BY columns and is gated by the same cost heuristic as per-partition GROUP BY / DISTINCT (enough partitions relative to max_threads, no dominant partition). Controlled by the new settings allow_window_partitions_independently (enabled by default), force_window_partitions_independently, and max_number_of_partitions_for_independent_window.


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

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [db4b7e7]

Summary: ✅


AI Review

Summary

This PR adds a new default-on optimization that keeps PARTITION BY windows local to each MergeTree partition when the table partition expression can be derived from the window keys, and it also propagates the resulting stream-disjointness through stacked windows and downstream per-partition operators. I re-checked the current diff against the existing discussion: the ARRAY JOIN regressions, the sort-limit behavior change, the distributed-fragment serialization concern, and the single-stream OVER () propagation issue are addressed, but one correctness blocker remains in the reused injectivity proof.

Findings

❌ Blockers

  • [dismissed by author -- https://github.com/Speed up window functions by evaluating each MergeTree partition independently #114783#discussion_r3838418661] src/Processors/QueryPlan/Optimizations/useDataParallelAggregation.cpp:82-117 still relies on removeInjectiveFunctionsFromResultsRecursively, and src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp:553-563 still treats plus / minus with a constant argument as injective. That is false for calendar arithmetic such as d + INTERVAL 1 MONTH, where distinct source dates can collapse to the same result. In this PR that pre-existing helper bug becomes a new default-on wrong-results path for window functions: the planner can now request per-partition reading and skip the window scatter even though one logical window partition spans multiple table partitions, so window aggregates/counts are computed independently per stream instead of globally. I still consider this a blocker because the PR expands an existing helper bug into a new user-visible correctness regression. Suggested fix: reject non-bijective date/time plus / minus transforms in this proof (or tighten the shared injectivity helper before reusing it here) and add the repro from the discussion as a focused stateless test.
Final Verdict

❌ Not ready to merge: the current code can still return wrong window results for non-bijective calendar arithmetic in PARTITION BY, and this optimization is enabled by default.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.10% 87.10% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 194/209 (92.82%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing db4b7e7a4 with master 9df951089 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 705.79 MiB 702.78 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 8143160d-d95e-4684-9b0b-08f6d959e374
  • MIRAI run: 131aa190-71e1-428f-bf19-ba5c84f281ce
  • PR check IDs:
    • clickbench_93816_1787509314
    • clickbench_93827_1787509314
    • clickbench_93834_1787509314
    • tpch_adapted_1_official_93847_1787509314
    • tpch_adapted_1_official_93872_1787509314
    • tpch_adapted_1_official_93886_1787509314

@yariks5s yariks5s self-assigned this Aug 17, 2026
Comment thread tests/performance/window_partitions.xml Resolved

@yariks5s yariks5s left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

isInjectiveFunction treats plus/minus/negate with a constant argument as injective so d + INTERVAL 1 MONTH reduces to d and the partition key looks determined by the window keys but it isn't

Repro:

CREATE TABLE t2 (d Date, x UInt32) ENGINE = MergeTree ORDER BY d PARTITION BY d;
INSERT INTO t2 SELECT toDate(concat(toString(2001 + intDiv(number, 3000)), '-01-', toString(29 + (intDiv(number, 1000) % 3)))) AS d, number
FROM numbers(66000) WHERE toYear(d) NOT IN (2004, 2008, 2012, 2016, 2020);

SELECT DISTINCT c FROM (SELECT count() OVER (PARTITION BY d + INTERVAL 1 MONTH) AS c FROM t2);
-- 1000   wrong
SELECT DISTINCT c FROM (SELECT count() OVER (PARTITION BY d + INTERVAL 1 MONTH) AS c FROM t2)
SETTINGS allow_window_partitions_independently = 0;
-- 3000   correct

Stacked windows are wrong the same way (100 instead of 400 per partition on a 4-partition table)

But this is not a defect this PR introduces. On a master build same expression already breaks existing consumers of the same helper

SELECT count() FROM (SELECT DISTINCT d + INTERVAL 1 MONTH AS k FROM t2);
-- 51   <-- wrong, DEFAULT SETTINGS, master today
SELECT count() FROM (SELECT DISTINCT d + INTERVAL 1 MONTH AS k FROM t2)
SETTINGS allow_distinct_partitions_independently = 0;
-- 17   <-- correct

SELECT count(), min(c), max(c) FROM (SELECT d + INTERVAL 1 MONTH AS k, count() c FROM t2 GROUP BY k)
SETTINGS force_aggregate_partitions_independently = 1, optimize_use_implicit_projections = 0;
-- 51 1000 1000   <-- wrong (17 3000 3000 expected)

SO I would not name it as a blocker here, but the PR introduces another breakage point, so it would be perfect if we had it fixed in another PR.


fullSortStreams installs LimitsCheckingTransform with LIMITS_CURRENT per stream so skipping the scatter changes which stream sees how many rows

-- 4 partitions x 4 parts, 400k rows, max_threads = 16
SELECT sum(c) FROM (SELECT count() OVER (PARTITION BY p, q ORDER BY x) AS c FROM s)
SETTINGS max_rows_to_sort = 40000, max_threads = 16;
-- 19739200
SELECT sum(c) FROM (SELECT count() OVER (PARTITION BY p, q ORDER BY x) AS c FROM s)
SETTINGS max_rows_to_sort = 40000, force_window_partitions_independently = 1, max_threads = 16;
-- Code: 396. Limit for result exceeded, max rows: 40.00 thousand, current rows: 50.00 thousand

Same with max_bytes_to_sort = 1500000 (succeeds -> 1.53 MiB exceeded)

Not a blocker but worth fixing probably.


EXPLAIN PIPELINE
SELECT c1, g, count() OVER (PARTITION BY p, q ORDER BY x DESC) AS c2
FROM (SELECT p, q, x, count() OVER (PARTITION BY p, q ORDER BY x) AS c1, sum(x) OVER () AS g FROM s)
SETTINGS query_plan_enable_multithreading_after_window_functions = 0, max_threads = 16;

With force_window_partitions_independently = 1 top WindowTransform has no × N, it runs
single-threaded, with the optimization off it is WindowTransform × 16 behind aScatterByPartitionTransform 1 → 16. WindowStep::transformPipeline does pipeline.resize(1) for an
empty full_sort_description, and applyStreamDisjointness still returns the property. One stream is disjoint, so results are fine but upper window never gets its width back

Def not a blocker for me.

if (!reading->willOutputEachPartitionThroughSeparatePort()
&& isPartitionKeyFunctionOfKeys(reading->getStorageMetadata()->getPartitionKey(), *dag, key_names))
{
reading->requestOutputEachPartitionThroughSeparatePortForWindow();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

isPartitionKeyFunctionOfKeys here still relies on removeInjectiveFunctionsFromResultsRecursively(), and that helper strips plus/minus with a constant argument as if they were globally injective. That is false for calendar arithmetic: on a table PARTITION BY d, the window key d + INTERVAL 1 MONTH can map 2001-01-29, 2001-01-30, and 2001-01-31 to the same value. This branch will then request per-partition reading, split one logical window across streams, and return wrong window aggregates/counts with allow_window_partitions_independently = 1. Please either hard-reject these non-bijective date/time transforms here, or tighten the shared injectivity helper before reusing it for windows.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This will be fixed in a subsequent PR.

@nihalzp

nihalzp commented Aug 23, 2026 •

Copy link
Copy Markdown
Member Author
isInjectiveFunction treats plus/minus/negate with a constant argument as injective so d + INTERVAL 1 MONTH reduces to d and the partition key looks determined by the window keys but it isn't

Repro:

CREATE TABLE t2 (d Date, x UInt32) ENGINE = MergeTree ORDER BY d PARTITION BY d;
INSERT INTO t2 SELECT toDate(concat(toString(2001 + intDiv(number, 3000)), '-01-', toString(29 + (intDiv(number, 1000) % 3)))) AS d, number
FROM numbers(66000) WHERE toYear(d) NOT IN (2004, 2008, 2012, 2016, 2020);

SELECT DISTINCT c FROM (SELECT count() OVER (PARTITION BY d + INTERVAL 1 MONTH) AS c FROM t2);
-- 1000   wrong
SELECT DISTINCT c FROM (SELECT count() OVER (PARTITION BY d + INTERVAL 1 MONTH) AS c FROM t2)
SETTINGS allow_window_partitions_independently = 0;
-- 3000   correct
Stacked windows are wrong the same way (100 instead of 400 per partition on a 4-partition table)

But this is not a defect this PR introduces. On a master build same expression already breaks existing consumers of the same helper

SELECT count() FROM (SELECT DISTINCT d + INTERVAL 1 MONTH AS k FROM t2);
-- 51   <-- wrong, DEFAULT SETTINGS, master today
SELECT count() FROM (SELECT DISTINCT d + INTERVAL 1 MONTH AS k FROM t2)
SETTINGS allow_distinct_partitions_independently = 0;
-- 17   <-- correct

SELECT count(), min(c), max(c) FROM (SELECT d + INTERVAL 1 MONTH AS k, count() c FROM t2 GROUP BY k)
SETTINGS force_aggregate_partitions_independently = 1, optimize_use_implicit_projections = 0;
-- 51 1000 1000   <-- wrong (17 3000 3000 expected)
SO I would not name it as a blocker here, but the PR introduces another breakage point, so it would be perfect if we had it fixed in another PR.

@groeneai Let's fix this.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed, and thanks for the precise repro. I reproduced the master-today half on a debug build of b1383f4, no changes from this PR applied:

SELECT count(), min(c), max(c) FROM (SELECT d + INTERVAL 1 MONTH AS k, count() c FROM t2 GROUP BY k)
SETTINGS force_aggregate_partitions_independently = 1, optimize_use_implicit_projections = 0;
-- 51 1000 1000     (expected 17 3000 3000)

SELECT count() FROM (SELECT DISTINCT d + INTERVAL 1 MONTH AS k FROM t2) SETTINGS max_threads = 64;
-- 51               (expected 17; allow_distinct_partitions_independently is 1 by default)

The DISTINCT one needs enough threads for the split to actually happen, hence the explicit max_threads. It is also 51 with force_distinct_partitions_independently = 1.

Site is the hardcoded whitelist in isInjectiveFunction, src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp:562:

static const std::vector<String> injective = {"plus", "minus", "negate", "tuple"};

plus with one constant argument is injective only when adding that constant is injective on the argument domain. That holds for integer offsets, and does not hold for calendar intervals, where month and year addition collapses end-of-month days.

Controls on the same build and table, all correct today, so the fix has to keep them correct rather than just disabling the optimization:

  • GROUP BY d (the partition key itself), forced: 51 groups of 1000
  • GROUP BY toYear(d), forced: 17 groups of 3000 (toYear is not whitelisted, so the optimization declines)
  • GROUP BY x + 1, forced: 51000 groups of 1 (integer plus, legitimately injective)

I will fix it in a separate PR and link it here. Not touching this branch.

@nihalzp

nihalzp commented Aug 24, 2026

Copy link
Copy Markdown
Member Author

@groeneai Investigate the CI failure.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Neither red is caused by this PR.

1. Stress test (arm_release) on the current head db4b7e7a - pre-existing trunk defect.

The failing query is in 01281_join_with_prewhere_fix, after the AST fuzzer rewrote the table to a merge():

SELECT 2 FROM merge(currentDatabase(), 't') AS l INNER JOIN t AS r ON l.id = r.id WHERE r.x

No window function, so none of your code runs. The stack is ReadFromMerge::createChildrenPlans -> StorageDistributed::read -> collectTableExpressionData -> ColumnNode::getColumnSource: the Merge set happened to include a Distributed table (sharded_table, left over from 02985_shard_query_start_time in the same test_5 database), and pushing the WHERE down into that child leaves a dangling column source.

Root cause is removeExpressionsThatDoNotDependOnTableIdentifiers (src/Analyzer/Utils.cpp:1294), reached from StorageMerge.cpp:1272. It early-returns on anything that is not a FunctionNode, so a bare column predicate like WHERE r.x is left in place even though its source is the join's right side and not the Merge child.

I reproduced it on pristine master b1383f4e with none of your code present, and it is a SIGABRT with your exact message and stack:

Logical error: 'Column x UInt8 query tree node does not have valid source node'
src/Analyzer/ColumnNode.cpp:42 DB::ColumnNode::getColumnSource()
src/Planner/CollectTableExpressionData.cpp:67
src/Storages/StorageDistributed.cpp:1024
src/Storages/StorageMerge.cpp:1154 DB::ReadFromMerge::createChildrenPlans()

Dropping the Distributed table from the Merge set makes it pass, so the Distributed child is required.

Fixing PR: #111327 (open). I applied its one-hunk change to master, rebuilt, and re-ran the same query: base aborts at the Distributed child, the fixed build gets past it (2 children planned, 0 aborts) and then only fails on the deliberately absent second shard. So #111327 covers this shape too, not just the USING shape its own tests use.

Breadth: 12 hits of this family across 12 distinct PRs in 60 days, 0 on master, this exact sub-signature 1 hit in 45 days on an unrelated PR (#105004). Stress test (arm_release) itself ran 2343 times on master in the last 14 days, so the zero is a real measurement and not missing coverage.

There is also a plan-ordering argument: your optimizeWindowPerPartition call sits in the traverseQueryPlan block at the end of optimizeTreeSecondPass, while this abort happens in optimizePrimaryKeyConditionAndLimit (optimizeTree.cpp:235), which runs earlier in the same function. Your code cannot have run yet.

2. Stress test (amd_tsan) - stale, and also not yours.

That red is on 02364fad, which db4b7e7a superseded. Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID 2508-348f), aborting in findEqualRangeEndAssumeSorted.h:89 via SortCursor.h:776. It is a known trunk family; the sub-signature seen here is owned by #113242 (open). amd_tsan is green on your current head.

Net: 1 failure on head, both reds trunk defects with in-flight fixes (#111327, #113242). Nothing to change on this PR; a rerun of Stress test (arm_release) should go green since the fuzzer needs to hit that specific rewrite again.

@nihalzp
nihalzp added this pull request to the merge queue Aug 24, 2026
Merged via the queue into ClickHouse:master with commit c85e797 Aug 24, 2026
522 of 524 checks passed
@nihalzp
nihalzp deleted the window-partitions-independently branch August 24, 2026 07:11
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@nihalzp @yariks5s — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator

#117137.

Beyond your Date plus INTERVAL 1 MONTH case the same name list was wrong for three more operand
classes, all measured: DateTime plus INTERVAL 1 DAY across a DST transition (Europe/Moscow,
6 distinct timestamps to 4), Float64 + 1.0 near 1e16 (3 to 2), and a narrowing or rescaling
constant, x + toDate(0) and x + toDecimal32(0, 1) (both 6 to 1).

So neither a special case for INTERVAL nor deleting the two names would do: the first misses the
float and constant cases, the second costs the integer cases your controls pinned.
FunctionBinaryArithmeticWithConstants::isInjective now answers by operand type and the list is
gone. allow_window_partitions_independently is covered, and so is
optimize_distributed_group_by_sharding_key, which was separately returning a collapsed group key
once per shard.

@ylw510 ylw510 mentioned this pull request Sep 3, 2026
47 of 72 tasks
rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Sep 14, 2026
allow_window_partitions_independently arrived after this branch was written, in
ClickHouse#114783 (ec46c0e), so the window consumer of isPartitionKeyFunctionOfKeys
had no arm of its own. It has one now, in the test file that already covers the
aggregation, DISTINCT, LIMIT BY, set-building and sharding-key consumers.

The carrier is Date + INTERVAL 1 MONTH rather than the float shape issue ClickHouse#116268
reports, because a floating point partition key is rejected outright (Code: 36),
so a float carrier has to reach its partition through an integer valued
indirection such as toInt64(x * 1e21), and that shape never satisfies
isPartitionKeyFunctionOfKeys. Measured on a pre-fix build, every line of the
float window arm is identical with and without this change, including a bare
column control, so it would have asserted nothing. A Date is a legal partition
key and needs no indirection. The float half of that issue is a GROUP BY, does
reproduce, and is covered by the existing t_float arms.

Measured on a pre-fix build of master, the forced arm and the arm that sets
nothing at all both return three distinct window counts where one is correct, and
both plan tokens the optimization prints read 1; with this change all three value
arms return a single count and both tokens read 0. The arm that sets no setting
matters most: the cost heuristic accepts these 39 partitions at the max_threads
the file already pins, so the wrong answer needs no opt in. The integer control
next to it is unchanged in every arm, which is what attributes the section to the
operand type rather than to the fixture or the window shape. Both plan tokens are
asserted because the change has to decline at both decision sites, the
per-partition read request and the scatter skip above it.

The reference line for the empty key arm is no longer red. It asserted the value
that needs the guard from ClickHouse#114981, which merged as ab9ebb0 and arrives
here through a master merge, so the whole file now passes as committed, 50 runs
out of 50, with no reference edited.

For the record, the precedent for deleting a name based injectivity list in this
helper is 9aa0341 (Nikolai Kochetov), which did exactly this for
materialize.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants