Repository navigation
Speed up window functions by evaluating each MergeTree partition independently - #114783
Conversation
|
Workflow [PR], commit [db4b7e7] Summary: ✅
AI ReviewSummaryThis PR adds a new default-on optimization that keeps Findings❌ Blockers
Final Verdict❌ Not ready to merge: the current code can still return wrong window results for non-bijective calendar arithmetic in LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 194/209 (92.82%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units193 translation units recompiled, 1771 s compile time in total, 193 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
yariks5s
left a comment
There was a problem hiding this comment.
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 correctStacked 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 thousandSame 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(); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
This will be fixed in a subsequent PR.
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. |
|
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: The DISTINCT one needs enough threads for the split to actually happen, hence the explicit Site is the hardcoded whitelist in static const std::vector<String> injective = {"plus", "minus", "negate", "tuple"};
Controls on the same build and table, all correct today, so the fix has to keep them correct rather than just disabling the optimization:
I will fix it in a separate PR and link it here. Not touching this branch. |
|
@groeneai Investigate the CI failure. |
|
Investigated. Neither red is caused by this PR. 1. The failing query is in SELECT 2 FROM merge(currentDatabase(), 't') AS l INNER JOIN t AS r ON l.id = r.id WHERE r.xNo window function, so none of your code runs. The stack is Root cause is I reproduced it on pristine master Dropping the Fixing PR: #111327 (open). I applied its one-hunk change to master, rebuilt, and re-ran the same query: base aborts at the 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). There is also a plan-ordering argument: your 2. That red is on Net: 1 failure on head, both reds trunk defects with in-flight fixes (#111327, #113242). Nothing to change on this PR; a rerun of |
c85e797
|
@nihalzp @yariks5s — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
Beyond your So neither a special case for |
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]>
Related: #108326
Related: #114645
A window function plan sorts its input partitioned by the window
PARTITION BYcolumns: every row is reshuffled across streams byScatterByPartitionTransform(a hash pass over thePARTITION BYcolumns plus a repack of every column of every row through a full cross-streamResize), so that whole window partitions land in single streams before the per-stream sort andWindowTransform. If the partition expression of theMergeTreetable is a deterministic function of the windowPARTITION BYcolumns, 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.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 ins, atmax_threads = 16:SELECT a, s, count(b) OVER (PARTITION BY a) FROM test_str_64SELECT a, s, sum(b) OVER (PARTITION BY a ORDER BY b) FROM test_str_64The scatter repacks every column of every row, so the win grows with the row width.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up window functions on partitioned
MergeTreetables 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 windowPARTITION BYcolumns and is gated by the same cost heuristic as per-partitionGROUP BY/DISTINCT(enough partitions relative tomax_threads, no dominant partition). Controlled by the new settingsallow_window_partitions_independently(enabled by default),force_window_partitions_independently, andmax_number_of_partitions_for_independent_window.Workflow [PR]
Sync PR [sync-upstream/pr/114783]