Repository navigation
Conversation
With any explicit ROWS frame, rank and dense_rank gave tied ORDER BY peers distinct ranks, so they behaved like row_number: over ['a','a','b'], rank returned [1,2,3] instead of [1,1,3] and dense_rank returned [1,2,3] instead of [1,1,2]. The same queries with no frame were already correct. SQLite 3.45.1 agrees with the corrected results on every shape tested. These functions are defined on the ORDER BY peer group and the frame is irrelevant to them. WindowTransform::arePeers short-circuits to false for distinct rows when the frame type is ROWS. That predicate also drives peer-group tracking in appendChunk's row loop, and peer_group_start_row_number / peer_group_number are exactly what the two functions return, so under a ROWS frame every row started a new peer group. Move the ORDER BY equality half of arePeers into a new frame-independent haveEqualOrderByValues, and track the ORDER BY peer group in two separate counters that rank and dense_rank read. The frame-relative peer state and every line that assigns it are left untouched, so frame boundaries, percent_rank and cume_dist are unaffected, and arePeers keeps identical semantics at both of its call sites. Under RANGE the new counters ride the existing peer-group transition, which makes the change a no-op for RANGE queries and keeps the hot path at one ORDER BY comparison per row; only ROWS, where arePeers compares nothing, performs the previous-row comparison it currently skips. That comparison is guarded by a state-transition witness because the row loop can return without advancing current_row and re-run for the same row, and the previous row's block joins the first_used_block minimum so it stays alive. rank and dense_rank are the only functions affected: percent_rank, cume_dist and ntile override checkWindowFrameType and reject ROWS frames before reaching the transform, and GROUPS frames are not implemented in either planner. Perf on 20M rows: RANGE is unchanged within noise, a ROWS rank query costs about 33% more because of the added comparison, and memory for a streaming ROWS query is flat. Closes ClickHouse#112665
The previous commit's peer-group boundary check ran for every row under a ROWS frame, but `WindowFunctionRank` and `WindowFunctionDenseRank` are its only readers. A ROWS-frame query with no ranking function, such as `sum(x) OVER (ORDER BY y ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`, therefore paid one `IColumn::compareAt` per ORDER BY key per row and retained one extra input block for nothing. Resolve the requirement once in the constructor through a new `IWindowFunction::needsOrderByPeerGroup`, which only the two ranking functions override, and gate both the boundary check and the block retention on it. The RANGE update stays ungated: it rides the existing peer-group transition, so it costs two increments on boundary rows only.
Internal second-model review (2 rounds, 3 findings, $14.94) - click to expandI put this change through two rounds of independent review before opening the PR: a cold read of Round 1❌ blocker (accepted, fixed) - every The first version gated the new ORDER BY peer-group check on the frame type alone, but only Fixed by resolving the requirement once per transform through a new
The scenario is real: with First, it is pre-existing and frame-independent. The moved comparison is byte-identical to the Second, the suggested remedy is unsafe at this scope. Round 2💡 nit (noted, not changed) - under Correct as stated: the |
Pre-PR validation gate
Existing suites: Performance on 20M rows, best of 8 interleaved rounds per shape, pre-fix arm built from the merge base: |
|
cc @KochetovNicolai @Algunenano, could you review this? |
|
@nihalzp this should be easy for you to review? |
|
Workflow [PR], commit [bbdbc69] Summary: ❌
AI ReviewSummaryThe PR fixes Missing context / blind spots
Final Verdict✅ Approve — no code changes requested. |
|
The collated- The gap is pre-existing and not specific to ranking. So collation correctness here is a separate, older defect, and a more severe one than wrong ranks: it also produces wrong results in release builds (that same query returned both What this PR does contract for is frame parity, and that holds under collation.
Master disagrees with itself depending on the frame; this PR makes the One correction to my earlier reply. I wrote that Your literal example does not currently reproduce, for what it is worth: |
CI finish ledger - 1fa1618Every 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 175 check-runs, all completed. 3 failures.
On the first line: keyed on the stack rather than the error phrase, that failure had exactly one occurrence in 90 days, this one, which made it look PR-caused. I A/B'd it against a pristine master build rather than assume either way, and it is pre-existing. Details and the reduced repro are in the reply above. Session id: cron:clickhouse-maint-slot-16:20260803-152600 |
|
Fixing PR for the first ledger line (STID 2508-46a9, Root cause confirmed as the pre-existing collation gap: the window input is sorted with the ORDER BY collator, but |
Master gained GROUPS frame support in WindowTransform (43bbda3 and follow-ups) while this branch was open, which conflicts in three places. arePeers: master replaced the RANGE-only tail with a switch that treats RANGE and GROUPS alike, so the branch's chassert that the frame type is RANGE would now fire on every GROUPS query. Dropped the assertion, kept master's switch and the extraction of the ORDER BY comparison into haveEqualOrderByValues. Partition reset and block retention: kept both sides. The ORDER BY peer group counters reset alongside master's frame_start_group_number/frame_end_group_number, and the previous-row retention is layered on top of master's peer_group_start.block term rather than replacing it. The ORDER BY peer group tracking now also covers GROUPS: under GROUPS arePeers is ORDER BY equality, so the existing transition is already the peer boundary and the non-ROWS branch handles it with no extra comparison.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units14 translation units recompiled, 28 s compile time in total, 14 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
CI finish ledger - 6f06654Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Neither is caused by this PR's diff: the family predates it and fires on master and on many Session id: cron:our-pr-ci-monitor:20260814-180000 |
|
Dear @nihalzp, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
CI finish ledger - 494af2fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260905-060038 |
CI finish ledger - 1309aedEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260909-043117 |
|
@groeneai Fix conflicts. |
Master moved the window functions into src/WindowFunctions/ and the peer comparison into WindowTransformParams. Port the fix onto that layout: haveEqualOrderByValues now lives in WindowTransformParams next to arePeers, and the rank/dense_rank overrides moved with their functions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done, merged master in 9386eec. The master refactor moved the peer comparison into |
|
@nihalzp all green. Can you review? That one will help me with correctness validation |
|
@groeneai fix conflicts |
Master's window refactor (ClickHouse#123737) replaced the runtime arePeers transition in computeReadyRows with a per-block SlidingIndex::peer_group_starts, which still marks every row as a peer group start under ROWS, so rank/dense_rank still degenerate into row_number there. Port the fix onto that model instead of the runtime prev-row comparison: - SlidingIndexes computes order_by_peer_group_starts with the same equal-range scan RANGE/GROUPS use (crossing blocks via last_order_key), only when WindowTransformParams::separate_order_by_peer_groups is set, i.e. a ROWS frame with rank or dense_rank. - WindowTransform tracks order_by_peer_group_start from that index; orderByPeerGroupStart() returns it, or peer_group_start otherwise, and rank/dense_rank read it. - No block needs to be kept alive for the check any more, and haveEqualOrderByValues is gone. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done, merged master in 58cabab. #123737 moved peer-group tracking into the per-block |
…th a ROWS frame The ROWS-frame ORDER BY peer index ran the equal-range scan over raw values. With `ORDER BY ... COLLATE`, rows equal under the collation can differ in bytes and interleave in the sorted block, so equal raw values are not contiguous: debug builds abort with "Equal values are not contiguous within the range assumed to be sorted" (found by the AST fuzzer on this PR), and release builds could split peer groups. When an ORDER BY key has a collator, mark the ROWS-frame peer group starts by comparing adjacent rows with compareAtWithCollation, the comparison the sort used. Queries without COLLATE keep the scan. RANGE and GROUPS peer marking is unchanged here. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - e28b1b9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 152 check runs completed, Session id: cron:our-pr-ci-monitor:20261008-180012 |
ClickHouse#124175 replaced the per-row peer group start flags in SlidingIndex with peer group indexes, so the separate ORDER BY index used by rank and dense_rank under a ROWS frame is now an index too. It is computed by master's assignPeerGroupIndexes with the frame type and the collation comparison passed in, instead of a second copy of that logic, and the transform moves order_by_peer_group_start when the index changes, the same way master moves peer_group_start. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… a ROWS frame A second 64-bit peer group index per buffered row costs 8 bytes per row while the partition is held: a full-partition ROWS frame over 10M rows peaked at 677 MB instead of 598 MB. The transform only needs to know where the groups start, so the index is reduced to one bit per row and the transform counts the groups, as it did before the master merge. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 323ec28Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261014-170013 |
…-rank-dense-rank-rows-frame-peers Master's ClickHouse#125749 (Peers) and ClickHouse#127389 (general window functions batch execution) removed IWindowFunction.h and made rank() and dense_rank() read bounds.peers_start and bounds.peer_group_index. Port of the same fix onto that interface: - needsSeparateOrderByPeerGroups uses the function's getRequirements().peers (under ROWS only rank() and dense_rank() can require peers, cume_dist() and percent_rank() reject any frame but RANGE over the whole partition), so the needsOrderByPeerGroup virtual is dropped. - The ORDER BY peer group start is tracked in WindowTransform as before and appendCurrentRow passes it as peers_start / peer_group_index, so the rank and dense_rank sources are master's again. - SlidingIndexes is unchanged on master and merged cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The ORDER BY peer group tracking for rank() and dense_rank() under a ROWS frame added a branch to computeReadyRows() and two selects to appendCurrentRow() that every window query executed for every row. The arm performance comparison flagged `window_functions_streaming ClickHouse#1` (`count() OVER (ROWS UNBOUNDED PRECEDING)`, +17.8%) and showed most window queries slower (median +1.7%, 85 of 93); a local x86 release A/B measured +1.9% median over that test and +4.3% on query ClickHouse#1. flushBatch() now overwrites peers_start and peer_group_index for the batch from SlidingIndex::order_by_peer_group_starts, only when separate_order_by_peer_groups is set. computeReadyRows(), appendCurrentRow() and startNextPartition() are identical to master again (same machine code except member offsets); the A/B is neutral (-0.1% median over the 14 queries). Co-Authored-By: Claude Opus 5.5 <[email protected]>
The per-block ORDER BY peer group starts used by `rank` and `dense_rank` under a ROWS frame were a third vector in `SlidingIndex`, which grew `SlidingBlock` from 136 to 160 bytes. `SlidingBlocks` keeps its blocks in a `std::deque`, whose chunk size is 4096 / sizeof(T): it went from 30 to 25 elements, so every `blockAt` call divides by 25 instead of 30. On aarch64 the division by 25 needs a two-instruction fixup (`sub` + `add ..., lsr`) after the `umulh`, on the dependency chain of every per-row `blockAt` call (`Partition::advance`, `Peers::advanceCurrentRow`, `Frame::advance`, `SlidingBlocks::next`). Disassembling the CI arm_release binaries of this PR and of the master reference shows exactly these constants (160/25 vs 136/30) as the only per-row instruction difference, which explains `window_functions_streaming ClickHouse#1` being +18% slower on arm on both 99df6ae and bd5c1d6 while the x86 A/B stayed within noise. The starts now live in a `WindowTransform`-owned deque with one entry per block in `blocks`, pushed in `addInputBlock` and popped together with the block in `releaseUnusedBlocks`. sizeof(`SlidingBlock`) is 136 again (same as master), and an aarch64 cross-compile of SlidingBlocks.cpp is instruction-identical to master's. Also write function names in the PR's comments as `f` rather than `f()`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - bbdbc69Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261030-010012 |
|
Dear @nihalzp, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Thanks. One thing I measured on the CI SELECT sum(k) OVER (ORDER BY v COLLATE 'en-u-ks-level1', k ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
FROM values('v String, k UInt8', ('a', 1), ('A', 2), ('a', 3), ('b', 4));Master ( |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
rankanddense_rankreturning distinct ranks for rows that compare equal byORDER BYwhen the window has an explicitROWSframe, which made them behave likerow_number. These functions are defined on theORDER BYpeer group and are not affected by the frame.Description
Closes: #112665
Related: #113399
With any explicit
ROWSframe,rankanddense_rankgave tiedORDER BYpeers distinct ranks:dense_ranklikewise returned[1,2,3]instead of[1,1,2]. Without a frame both were correct,and SQLite agrees with the new results on every shape I tested.
Root cause. Under a
ROWSframe every row is its own peer group:SlidingIndexesnumbersthe rows one by one in
peer_group_indexes, andrank/dense_rankreturn the row and group indexof the current peer group, so they degenerate into
row_number.The change. For a
ROWSframe with a function that requires peers (onlyrankanddense_rankaccept aROWSframe;WindowTransformParams::separate_order_by_peer_groups),SlidingIndexesalso computesorder_by_peer_group_startswith the same per-block equal-range scanRANGE/GROUPSalready use (comparing adjacent rows under the collation when anORDER BYkey hasCOLLATE, since collation-equal values can differ in bytes).WindowTransformkeeps it per block and setspeers_startandpeer_group_indexfrom it once per batch, so the per-row loop is unchanged; forevery other frame type these still come from
Peers, so frame boundaries andRANGE/GROUPSresults are unchanged.
percent_rankandcume_distrequire aRANGEframe,and
ntilereads no peer-group state.RANGE/GROUPSpeers underCOLLATEare fixed separately in #113399.Validation. New stateless tests
04720_*: the main one differs on 28 lines against the unfixedbinary, the
COLLATEone on 10; both pass 50/50 under CI randomization; the other window-function stateless testshave no local failure that does not also fail on master. An arm
window_functions_streamingslowdown on earlier heads came from a largerSlidingBlock(a slowerstd::dequeindex on every row); its size is now master's.Workflow [PR]
Sync PR [sync-upstream/pr/113079]