Skip to content

Fix wrong results of window functions with different PARTITION BY planned for one thread - #129641

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-window-partition-split-single-thread-plan
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-window-partition-split-single-thread-plan

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126627
Related: #125085
Related: #125946

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed wrong results of window functions with different PARTITION BY, such as sum(x) OVER (PARTITION BY a ORDER BY b) with min(x) OVER (PARTITION BY a, b ORDER BY c), when the windows were planned for one thread but the data was read by several, for example with max_threads = 1 over a subquery with a larger max_threads, or with the automatic max_threads lowered by the fair share of CPU slots. One partition could be split in two.

Description

02962_parallel_window_functions_different_partitioning returned a wrong result in Stateless tests (amd_debug, distributed plan, s3 storage, parallel) on #126627, and the same diff on #126386: one PARTITION BY depname partition summed to 14400 instead of 43800.

On 26.10.2.103 (also 26.3.60.2, 26.8 and 26.9), two windows where the second one's sort is a prefix of the first one's but its PARTITION BY is shorter return wrong results when the windows are planned for one thread while the source is read by several. A deterministic example: SETTINGS max_threads = 1 over (SELECT * FROM empsalary SETTINGS max_threads = 2), as in the new test query.

addWindowSteps skips the second sort when getEffectiveMaxThreads returns 1, assuming a single stream, but the first window's sort scatters by the pipeline's thread count, which comes from the read's own sample. Since #125085 that value was the live fair share of CPU slots, sampled at each call (2 for the read, 1 for the windows in the failing run). #125946 now takes it once per query; the subquery example still returns 14400 on master.

Now, when a window reuses a sort with another partitioning, the window sorts of that query level merge their streams into one sorted stream instead of scattering, as windows with keys that break hash sharding already do. A real one-thread pipeline runs the same processors, and plans for more threads do not change.

Validation: the new query fails 50/50 on master and passes 50/50 with the fix (random settings). Under CPU-slot contention the original query was wrong in 438 of 9000 runs on master and in none with the fix. The other 302 window tests give the same results on both binaries, also with max_threads = 1.

🤖 Generated with Claude Code


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

groeneai and others added 3 commits November 5, 2026 22:40
`addWindowSteps` does not sort a window again when its sort description is a
prefix of the previous window's, and when `getEffectiveMaxThreads` returns 1 it
skips the sort even if the `PARTITION BY` differs (ClickHouse#58739), assuming the
pipeline has a single stream. The previous window's `SortingStep` scatters by
the pipeline's thread count, which is `QueryPlan::max_threads` set by the read
from its own sample. When the read sees several threads and the window planning
sees one, the first window scatters by the longer key and the second window
runs one `WindowTransform` per stream, so one of its partitions is split in two.

This happens with an outer `SETTINGS max_threads = 1` over a subquery with a
larger `max_threads`, and, since ClickHouse#125085 made `getEffectiveMaxThreads` return
the live fair share of CPU slots for each call, with the default automatic
`max_threads` under load. That is the wrong result of
`02962_parallel_window_functions_different_partitioning` in CI (the read got 2
threads, the windows 1).

When a window reuses a sorting with another partitioning, the window sortings
of the call are now planned without scatter partitions, so each of them merges
its streams into one sorted stream, the same way windows whose keys break hash
sharding are handled. A pipeline that really has one thread gets the same
processors as before, and plans for more than one thread are unchanged. The
effective `max_threads` is sampled once per call so both decisions agree.

The test gets the deterministic subquery variant as a third query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sure

An explicit `max_threads = 2` is still lowered by the free-memory limiter
(`max_threads_min_free_memory_per_thread`, 1 GiB by default), so with less
than 2 GiB free under `max_server_memory_usage` the subquery is read with one
thread, nothing is scattered, and the query cannot fail without the fix.
Pin the limit to 0 in the subquery.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the sentence restating the lambda name; state why the thread count is sampled once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 5, 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; 1 finding; 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test query could pass without two read streams: the free-memory limiter can lower the subquery's max_threads = 2 to 1 AGREE, fixed @ 6dd516f Subquery pins max_threads_min_free_memory_per_thread = 0; without the pin and with a 1 TB per-thread limit the unfixed binary returns correct rows, with the pin it returns the 14400 rows. 50/50 runs fail without the fix, 50/50 pass with it.
2 ⚠️ Also assert the plan shape with EXPLAIN PIPELINE DISAGREE The result check already fails 50/50 without the fix; a processor-count assertion would also fail other correct fixes (re-sorting instead of merging).

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

Session id: cron:clickhouse-review-slot-10:20261105-231900

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test query (SETTINGS max_threads = 1 over a subquery with max_threads = 2) returns the CI diff (three sales 14400 4800 rows) 5/5 on master and 50/50 via clickhouse-test --test-runs 50 with random settings.
b Root cause explained? addWindowSteps skips the second sort when getEffectiveMaxThreads is 1, but the first window's sort scatters by the pipeline thread count, which comes from the read's own sample (since #125085 the live fair share of CPU slots). Read 2, windows 1: the (depname, empno) scatter splits the depname partition.
c Fix matches root cause? Yes. When a window reuses a sort with another partitioning, the window sorts merge their streams instead of scattering, so the single-stream assumption no longer depends on a thread count sampled elsewhere.
d Test intent preserved / new tests added? Yes. 02962 is extended with one query that fails on master; its existing queries and reference lines are unchanged. The subquery pins max_threads_min_free_memory_per_thread = 0, so the free-memory limiter cannot drop its read to one thread (with a 1 TB per-thread limit the unfixed query returns correct rows).
e Both directions demonstrated? Yes. Same tree, base vs fix: 0/50 vs 50/50 with random settings. Under CPU-slot contention (concurrent_threads_soft_limit_num = 4) the original query was wrong in 438/9000 runs on master and 0/9000 with the fix.
f Fix is general across code paths? Yes. The only other copy of the predicate is InterpreterSelectQuery::executeWindow, unreachable since the old analyzer was removed (#126658 deletes it). Chains of three windows and OVER () are covered by the same flag.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Matrix of LowCardinality(String), String, Nullable(String), UInt64 keys x 4 window shapes: 12/16 cells wrong on master, 0/16 with the fix; equal partitioning was and stays correct.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change. Plans for more than one thread are unchanged; a real one-thread pipeline runs the same processors (EXPLAIN PIPELINE identical).
i Invariants and contracts preserved? Yes. Every partition of a partitioned window lands in one stream at any pipeline thread count: own sort scatters by its own keys, equal partitioning reuses the same scatter, different partitioning now gets one merged stream. 303 window tests give the same results on both binaries apart from 02962.

Session id: cron:clickhouse-impl-slot-40:20261105-221100

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai, could you review this and add the can be tested label so CI runs? addWindowSteps skipped the re-sort of a window whose sort is a prefix of the previous one with a different PARTITION BY when it planned for one thread, but the previous sort scattered by the read's own thread count, so one partition could be split; such window sorts now merge into one stream instead of scattering.

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a0cafd0]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Cannot run the mutation entries left behind by the killed mutations (see undrained_mutation_errors.txt) FAIL cidb
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

PR #129641, reviewed at a0cafd06957beae685b0a9ee15eb324cb560a671, fixes incorrect window results when the source uses more threads than the window planner expects. When windows reuse an ordering across different partition keys, their sorts now merge into one stream. The regression query exercises this mismatch and disables the memory limiter that could otherwise conceal it. No substantive findings remain after reviewing the diff, affected code, and all prior discussion. Validation relied on source review and the reported before/after regression results; no local ClickHouse binary was available.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-window-functions Window function execution + frame handling (ROW_NUMBER/RANK/LAG/LEAD, frames, partitions, order). labels Nov 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a0cafd069 with master b6ed65a67 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 4cbc68b27; 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.

Compile time of recompiled translation units

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

Job report

…n-split-single-thread-plan

Resolve the conflict in src/Planner/Planner.cpp: master moved addWindowSteps to
src/Planner/PlannerSteps.cpp, so the change is re-applied there, with master's
getEffectiveMaxThreads(*query_context). The comment about sampling the value once
is dropped: since ClickHouse#125946 the value comes from a per-query snapshot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a0cafd0

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
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) not from this PR (it only changes how window functions are planned): after the upgrade test_1.t_replace_cover_rep, the table of 05259_replace_partition_covers_outdated_parts_replicated left behind by the stress phase, attaches read-only with Code 231 TOO_MANY_UNEXPECTED_DATA_PARTS. The same row failed on 4 other PRs in the last 14 days #127843 (mine, open)
Upgrade check (amd_release) / Cannot run the mutation entries left behind by the killed mutations (see undrained_mutation_errors.txt) not from this PR: the same read-only test_1.t_replace_cover_rep fails the drain step's check The replica is missing or read-only after SYSTEM RESTART REPLICA. 2 other PRs in the last 14 days, 0 on master a fix task is created (investigating at full effort, fixing-PR link to follow here)
PR praktika rollup of the rows above #127843 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

Mergeable Check is red only because of the rows above; there are no other CIDB FAIL rows on this head.

Session id: cron:our-pr-ci-monitor:20261120-170043

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Upgrade check (amd_release) row Cannot run the mutation entries left behind by the killed mutations in the ledger above: #133320

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-window-functions Window function execution + frame handling (ROW_NUMBER/RANK/LAG/LEAD, frames, partitions, order). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant