Repository navigation
Conversation
The window input is sorted by full_sort_description, whose ORDER BY entries carry the collator, but WindowTransform re-derived peer groups with the raw IColumn::compareAt. Rows that are equal under the collation but differ in bytes therefore looked unequal, so the RANGE peer group was cut short: the frame end, and through peer_group_start the frame start, landed on the wrong row and the query returned wrong results. The collated sort may also interleave such rows, which violates the "equal values are contiguous within a sorted range" precondition of the equal-range scan, so debug and sanitizer builds raised the logical error "Equal values are not contiguous within the range assumed to be sorted". Compare ORDER BY keys the same way the input was sorted, at the three sites that decide peer membership: arePeers and the reference check plus the equal-range scan in advanceFrameEndCurrentRow. The guard shape (collator && isCollationSupported()) matches the five existing sites in LimitTransform, FractionalLimitTransform, NegativeLimitTransform, FillingTransform and SortCursor. findEqualRangeEndAssumeSorted is a free template over an arbitrary equality predicate, so no new IColumn method is needed. PARTITION BY sites are left alone because PARTITION BY cannot carry a collator. A collatable type cannot reach the RANGE OFFSET comparisons, which reject a String ORDER BY column. Uncollated queries are bit-for-bit unchanged: a constructor flag keeps the existing per-column equal-range scan, with its memcmp and vector fast paths, whenever no ORDER BY key has a collator. Found by the AST fuzzer on an unrelated PR (STID 2508-46a9) and confirmed pre-existing on pristine master with queries containing no ranking function. Only affects enable_analyzer = 1: the old analyzer drops COLLATE from a window ORDER BY, so its sort and comparison are both raw and self-consistent.
Internal second-model review (independent cold review + adversarial gate, 0 blockers)Two independent reviews of this change: a cold code review (reviewer never saw the author's
Verified independently during review, not taken from the author's notes:
Session id: cron:clickhouse-review-slot-11:20260804-234100 |
Pre-PR validation gate (a-i)
Additional validation: 50 of 50 randomized runs of the new test pass. The existing window and collation suite passes, including |
|
cc @novikd @yariks5s, could you review this? The window input is sorted with the ORDER BY collator, but WindowTransform re-derived RANGE peer groups with the raw IColumn::compareAt, so collation-equal rows that differ byte-wise were treated as separate peers: the frame is cut short (wrong results) and the equal-range scan's contiguity precondition is violated, which raises a logical error in debug and sanitizer builds. |
|
Workflow [PR], commit [24effc4] Summary: ✅
AI ReviewSummaryPR #113399 makes window peer-group comparisons honor Missing context / blind spots
Final VerdictStatus: ✅ Approve. No code changes requested; normal CI validation remains pending. |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger — 69fde84Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
None is PR-caused. This PR changes RANGE-frame peer comparison in Session id: cron:our-pr-ci-monitor:20260805-060000 |
CI finish ledger correction — 69fde84Two owner-column wordings in my previous ledger were imprecise. The owners are unchanged; the
Both lines were listed as "a fix task is created". The task in question was already open and is For the record, the attribution behind those two rows was re-derived rather than inherited: both The Session id: cron:our-pr-ci-monitor:20260805-060000 |
|
Fixing PR for the I had a fix for this on a local branch, but @alexey-milovidov opened #113415 with the identical |
|
Fixing PR for the two The locus is the planner header derivation, above the transport: |
Master added GROUPS frame support to WindowTransform, which rewrote arePeers' frame-type dispatch into a switch that now also routes GROUPS to the ORDER BY comparison. The conflict is in that dispatch: - Dropped this branch's chassert(frame.type == RANGE): GROUPS legitimately reaches the comparison now, so the assertion would fire on a valid frame. - Dropped master's `const size_t n = order_by_indices.size()`: the peer comparison moved into orderByEqualAt(), which iterates the indices itself, so the count is unused here. The collation-aware comparison at the three ORDER BY peer sites is unchanged and still applies.
Master's GROUPS frame support added findPeerGroupEnd(), a second peer-group scan that compares ORDER BY keys with the raw per-column equal-range helper. arePeers() now routes GROUPS through the collated comparison, so the two disagreed about what a peer group is: a collated GROUPS offset frame counted collation-equal rows as separate groups, and tripped the equal-range sortedness check in debug builds. Both scans now go through orderByEqualRangeEnd(), which picks the collated or the raw probe once, so RANGE and GROUPS cannot diverge. Also extends the regression test with the two cases it could not reach: - cross_block: every collated case used a single-row arrayJoin source, which cannot span blocks, so the comparison against a reference row in another block was never exercised. A numbers() source with max_block_size = 1 does span blocks. - groups: covers the scan above. Reverting only findPeerGroupEnd() to the raw helper reddens this case and leaves cross_block passing.
|
Merged master to resolve the conflict, and extended the fix to cover a site master added in the meantime. The conflict was in That turned up a real gap. SET enable_analyzer = 1;
SELECT count() OVER (ORDER BY v COLLATE 'en-u-kn-true' GROUPS BETWEEN CURRENT ROW AND 1 FOLLOWING)
FROM (SELECT arrayJoin(['1', '01', '1', '01']) AS v);All four rows are one collated peer group, so each must report Two test cases added, each pinned by reverting one part of the fix:
Master's own |
CI finish ledger - e0b8fd7Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
None is PR-caused. This PR changes only RANGE-frame peer comparison in Session id: cron:our-pr-ci-monitor:20260814-200000 |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Routing every ORDER BY peer comparison through one collation-aware helper made `arePeers` too costly to inline into the per-row loop (inline cost 305 vs threshold 250; master was 230) and left the equal-range scan out of line (cost 925), so every row of every RANGE/GROUPS window paid two extra calls, with or without COLLATE. The PR's arm perf check measured it: window_function_with_order ClickHouse#2/ClickHouse#3 +19%/+16%, window_transform ClickHouse#8 +17%. The collated comparisons now live in NO_INLINE `...WithCollation` helpers taking `RowNumber` by value, reached through an `unlikely` branch, so the raw path is master's loop again and `inputAt()` is only evaluated inside it (evaluating it up front cost 1-row partitions ~15%). `arePeers` and `orderByEqualAt` are ALWAYS_INLINE because any collation-aware version pays the cold call's inline penalty, which master's 20-point margin cannot absorb. Codegen checked on the CI arm64 binaries and on local x86 ThinLTO builds: `work()` again makes no calls to the peer helpers on the uncollated path. Local x86 A/B (15 interleaved rounds): the PR head was 7-18% slower on the window perf queries, this change is within noise of master on all of them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Params peer check Master's window refactor (ClickHouse#122762, ClickHouse#123260, ClickHouse#123737) moved the peer comparison into WindowTransformParams::arePeers and added SlidingIndexes, which marks peer-group starts for every RANGE and GROUPS frame with raw compareAt / getEqualRangeEndAssumeSorted. The input is sorted with the ORDER BY collator, so collation-equal values that differ in bytes (for example 'a' and 'A' under 'en-u-ks-level2') are interleaved, and the raw scan either cuts a peer group short or trips the debug check "Equal values are not contiguous within the range assumed to be sorted". Since ClickHouse#123737 this aborts deterministically for an ordinary collated rank(): SELECT rank() OVER (ORDER BY x COLLATE 'en-u-ks-level2') FROM (SELECT if(number % 2, 'a', 'A') AS x FROM numbers(1000)) The previous version of this fix lived in WindowTransform methods that the refactor removed, so it is re-done on the new structure. WindowTransformParams gets the collation flag and two helpers, haveEqualOrderByValues and getOrderByEqualRangeEnd, and every ORDER BY peer comparison goes through them: arePeers (cume_dist and the GROUPS cross-block check), the SlidingIndexes block boundary and in-block scan, the RANGE frame-end check and scan, and the GROUPS peer-group scan. PARTITION BY keys stay raw, as PARTITION BY cannot carry COLLATE. The helpers are inline in the header with the collated comparison in out-of-line cold functions, so an uncollated window keeps the inlined raw comparison of master: the earlier out-of-line version of these calls cost 15-19% on window_function_with_order in the arm performance check. The test gains the deterministic 1000-row case above (also for GROUPS), a cume_dist case and a one-row-per-block rank() case, so each of the six comparison sites has an assertion that fails when only that site compares raw. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-collate-range-peers Master reworked `WindowTransform`: peer groups are now computed only in `assignPeerGroupIndexes` in `SlidingIndexes.cpp`, and the old `arePeers`, `advanceFrameEndCurrentRow` and `findPeerGroupEnd` code paths are gone. Took master's versions of the conflicted files and re-applied the fix there: `WindowTransformParams` gets `has_order_by_collation`, `haveEqualOrderByValues` and `getOrderByEqualRangeEnd`, and both ORDER BY peer comparisons in `assignPeerGroupIndexes` (the block boundary check and the in-block scan) use them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I will fix it myself |
Related: #113079
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results and a logical error in window functions when the window
ORDER BYusesCOLLATE. The input is sorted with the collator, but peer groups were computed with a raw byte comparison, so values equal under the collation were treated as different peers. This gave wrongrank,dense_rank,percent_rankandcume_distvalues and wrongRANGEandGROUPSframes, and in debug and sanitizer builds raisedEqual values are not contiguous within the range assumed to be sorted. Closes #124348.Description
Reachable from ordinary SQL:
Under case-insensitive collation
'a'and'A'are equal, so every row must have rank1;ORDER BY x COLLATE 'en-u-ks-level2' LIMIT 1 WITH TIESagrees and returns all 1000 rows. On 26.8.18.2 the ranks are1to1000; on master a debug build aborts on every run, found again by the AST fuzzer (STID 2508-3e4f).Root cause: the window code re-derives peer groups with raw
compareAtandgetEqualRangeEndAssumeSorted, while the collated sort interleaves rows that are collation-equal but byte-different. That also breaks the contiguity precondition of the equal-range scan, hence the logical error.The fix adds
haveEqualOrderByValuesandgetOrderByEqualRangeEndtoWindowTransformParams, comparingORDER BYkeys the way the input was sorted, with thecollator && isCollationSupported()guard ofLimitTransform,FillingTransformandSortCursor.assignPeerGroupIndexesinSlidingIndexes.cppuses them for the block-boundary check and the in-block scan; theRANGEandGROUPSframes and the peer-dependent functions all read that index.PARTITION BYcannot carry a collator and is untouched. Uncollated windows keep the inlined raw comparison; only the collated path is out of line.Verified in both directions on current master: the test and the AST fuzzer query from #113045 abort on master and pass with the fix.
Workflow [PR]
Sync PR [sync-upstream/pr/113399]