Skip to content

Fix rank and dense_rank ignoring ORDER BY peers with a ROWS frame - #113079

Closed
groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112665-rank-dense-rank-rows-frame-peers
Closed

groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112665-rank-dense-rank-rows-frame-peers

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixes rank and dense_rank returning distinct ranks for rows that compare equal by ORDER BY when the window has an explicit ROWS frame, which made them behave like row_number. These functions are defined on the ORDER BY peer group and are not affected by the frame.

Description

Closes: #112665
Related: #113399

With any explicit ROWS frame, rank and dense_rank gave tied ORDER BY peers distinct ranks:

SELECT groupArray(r) FROM (
  SELECT RANK() OVER (ORDER BY v ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS r
  FROM (SELECT arrayJoin(['a', 'a', 'b']) AS v));
-- was [1,2,3], now [1,1,3]

dense_rank likewise 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 ROWS frame every row is its own peer group: SlidingIndexes numbers
the rows one by one in peer_group_indexes, and rank/dense_rank return the row and group index
of the current peer group, so they degenerate into row_number.

The change. For a ROWS frame with a function that requires peers (only rank and
dense_rank accept a ROWS frame; WindowTransformParams::separate_order_by_peer_groups),
SlidingIndexes also computes order_by_peer_group_starts with the same per-block equal-range scan
RANGE/GROUPS already use (comparing adjacent rows under the collation when an ORDER BY key has
COLLATE, since collation-equal values can differ in bytes). WindowTransform keeps it per block and sets
peers_start and peer_group_index from it once per batch, so the per-row loop is unchanged; for
every other frame type these still come from Peers, so frame boundaries and RANGE/GROUPS
results are unchanged. percent_rank and cume_dist require a RANGE frame,
and ntile reads no peer-group state.
RANGE/GROUPS peers under COLLATE are fixed separately in #113399.

Validation. New stateless tests 04720_*: the main one differs on 28 lines against the unfixed
binary, the COLLATE one on 10; both pass 50/50 under CI randomization; the other window-function stateless tests
have no local failure that does not also fail on master. An arm
window_functions_streaming slowdown on earlier heads came from a larger SlidingBlock (a slower std::deque index on every row); its size is now master's.


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

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.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 3 findings, $14.94) - click to expand

I put this change through two rounds of independent review before opening the PR: a cold read of
the resulting code, then an independent second model reviewing the full diff against the PR
contract. Round 1 bounced the change back for a fix; round 2 is clean. Recording the outcome for
transparency.

Round 1

❌ blocker (accepted, fixed) - every ROWS-frame query paid the new cost, not just ranking ones.

The first version gated the new ORDER BY peer-group check on the frame type alone, but only rank
and dense_rank read the resulting counters. So a query like
sum(number) OVER (ORDER BY number ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) paid one
IColumn::compareAt per ORDER BY key per row, and retained one extra input block, for nothing.
Two in-tree performance queries hit this (tests/performance/window_transform.xml,
tests/performance/window_functions.xml), measured at about 33%.

Fixed by resolving the requirement once per transform through a new
IWindowFunction::needsOrderByPeerGroup, overridden only by the two ranking functions, and gating
both the per-row check and the block retention on it. Verified in both directions: forcing the
flag on keeps the new test green (the gate is a no-op for readers), neutering it reddens the test
on 24 lines, and only the ROWS lines break while no frame and RANGE frame stay green. The
non-ranking ROWS workload is now 1579 to 1609 ms on 20M rows, within noise.

⚠️ blocker (declined, with evidence) - ORDER BY ... COLLATE is not honoured by the peer comparison.

The scenario is real: with ORDER BY v COLLATE 'en-u-ks-level1' over ['a','A','b'], rank
returns 1,2,3 although the two values are adjacent peers under that ordering. I declined it
because it is not this PR's contract, on two grounds.

First, it is pre-existing and frame-independent. The moved comparison is byte-identical to the
RANGE branch it came from, and WindowTransform contains no reference to a collator anywhere,
including the RANGE frame-end peer scan. A collated query returns the same ranks before this PR,
after it, under RANGE, and with no frame at all. What this PR establishes is frame parity for the
peer group, and that holds under collation exactly as it does without it.

Second, the suggested remedy is unsafe at this scope. arePeers now delegates to the new
predicate, so making it collator-aware would move RANGE peer groups, and therefore RANGE ... CURRENT ROW frame starts and cume_dist, while the frame-end path stayed collation-blind for want
of a collation-aware getEqualRangeEndAssumeSorted. That is a separate root cause and a separate
change.

Round 2

💡 nit (noted, not changed) - under RANGE the new counters are updated even when no function
reads them.

Correct as stated: the RANGE update is two increments on peer-boundary rows, inside a branch that
is already taken, and it is deliberately left ungated so the RANGE path gains no per-row work.
The measured RANGE ranking arm that executes exactly these writes is 1717 to 1740 ms on 20M rows,
within noise. Gating it would also leave the counters stale but publicly readable, which is a more
fragile invariant than keeping them always consistent. The same reasoning covers the mirror case I
found myself, where the block retention is gated on the capability flag without also requiring a
ROWS frame: it can only widen retention, by at most one block.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro Yes, 100%: clickhouse local running the two issue queries. No randomization needed.
b Root cause explained WindowTransform::arePeers short-circuits to false for distinct rows when the frame type is ROWS; it also drives peer-group tracking in the row loop, and peer_group_start_row_number / peer_group_number are what rank / dense_rank return. So every row became its own peer group.
c Fix matches root cause The ORDER BY-equality half of arePeers becomes a frame-independent haveEqualOrderByValues; two new counters track the ORDER BY peer group for ranking. No widened bounds, no no-random-* tag, no defensive check. The frame-relative peer state is untouched. A ctor-resolved IWindowFunction::needsOrderByPeerGroup, overridden only by the two ranking functions, keeps queries that never read the peer group on their previous cost.
d Test intent preserved, tests added No existing test weakened or removed. New stateless test 04720 (57 assertion lines), no no-parallel, no no-random-settings.
e Fails without fix, passes with it Yes: the new test's output differs from its reference on 28 lines against the pre-fix binary and matches exactly after. Build IDs confirmed different. Two further mutations prove the moving parts are load-bearing rather than assumed: weakening the retry guard to current_row_number > 1 reddens 3 lines, and forcing needsOrderByPeerGroup off reddens 24 lines while leaving the no-frame and RANGE lines green. Forcing it on leaves the test green, so the gate is a pure cost gate.
f General across code paths All peer-group readers enumerated. rank and dense_rank fixed; denseRank / DENSE_RANK aliases fixed transitively and asserted; percent_rank, cume_dist and ntile already reject ROWS frames (Code: 36, measured) and keep reading the old variable, where old and new counters are provably equal; row_number is correct by definition. arePeers keeps identical semantics at both call sites. The needsOrderByPeerGroup override is added to exactly the two counter readers: both are final and each is built at a single factory site, so there is no second rank implementation to miss.
g Generalizes across inputs Test matrix: Nullable, LowCardinality, multi-key ORDER BY, DESC, no ORDER BY, PARTITION BY, five ROWS frame shapes plus RANGE counterparts, max_block_size 1/2/3/default, and peer groups spanning block boundaries. ClickHouse NULL ordering was re-derived locally rather than copied from another engine; the asserted invariant is that tied NULLs share a rank.
h Backward compatible Wrong-results fix, not a semantic choice: SQLite 3.45.1 agrees with the reporter on every shape measured, and frame-boundary behaviour is unchanged (sum(1) controls match in both engines). No setting added, so no SettingsChangesHistory.cpp entry.
i Invariants and contracts preserved chassert(frame.type == RANGE) stays in the frame-aware arePeers and is deliberately absent from haveEqualOrderByValues, which is called for ROWS too, so a future GROUPS implementation still trips it. Both new counters reset at partition start. Retry idempotence holds by two mechanisms: the RANGE update sits inside the already-idempotent if (!arePeers(...)) body, and the ROWS update is guarded by a state-transition witness. Block liveness: the previous row's block joins the std::min for first_used_block, which can only lower the bound, so every block alive before stays alive; that widening is skipped when no function reads the peer group, in which case nothing reads the previous row and the bound is exactly the pre-change one.

Existing suites: 01568_window_functions_distributed, 04669_distributed_plan_window_end_preceding_frame, 01591_window_functions, 01592_window_functions, 01592_long_window_functions1, 04136_window_functions_frame_bounds, 03037_precent_rank, 03213_denseRank_percentRank_alias, 04209_rank_dense_rank_no_arguments_49526, 04202_percent_rank_invalid_frame, 02478_window_frame_type_groups, 01571_window_functions, 02884_parallel_window_functions_bug all pass. 50 runs of the new test under full CI randomization: 50 passed, 0 skipped.

Performance on 20M rows, best of 8 interleaved rounds per shape, pre-fix arm built from the merge base: sum(number) OVER (... ROWS ...) with no ranking function 1579 -> 1609 ms and rank under RANGE 1717 -> 1740 ms, both within noise; rank under ROWS 1353 -> 1800 ms, which is the one ORDER BY comparison per row it previously skipped.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @Algunenano, could you review this? arePeers short-circuits to false for distinct rows under a ROWS frame, and the same predicate drives peer-group tracking in the row loop, so rank and dense_rank returned the row number instead of the peer rank. The ORDER BY-equality half is extracted into a frame-independent predicate with its own counters, gated by a per-transform capability flag so queries that never read the peer group keep their previous cost.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@nihalzp this should be easy for you to review?

@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bbdbc69]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3e4f) FAIL cidb
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3e4f) FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
05453_webterminal_close_at_binary_format_question FAIL cidb
Some queries hung FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (amd_illumos) DROPPED

AI Review

Summary

The PR fixes rank and dense_rank with explicit ROWS frames by tracking ORDER BY peer groups independently of frame boundaries. Reviewed head bbdbc694f850042a74ad5f05b669e23cd1f76681: no actionable findings remain, and the previous COLLATE finding is addressed.

Missing context / blind spots
  • ⚠️ Current-head targeted sanitizer tests, bugfix validation, and arm performance comparisons are still pending. Their completed CI reports would close the remaining runtime validation gap. The main regression passed Fast test; the collation regression is excluded from that build.
Final Verdict

✅ Approve — no code changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
@nihalzp nihalzp self-assigned this Aug 3, 2026
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

The collated-ORDER BY gap is real, and this round I measured it instead of arguing it. Taking the second option you offered: an explicit carve-out, plus one correction to what I said before.

The gap is pre-existing and not specific to ranking. WindowTransform contains no collator reference at all (grep -c -i collat = 0), so the frame-end peer scan in advanceFrameEndCurrentRow is collation-blind too. Concretely, ORDER BY v COLLATE 'ru' over ['\0', BOM, '\0'] aborts a debug build in getEqualRangeEndAssumeSorted with Equal values are not contiguous within the range assumed to be sorted: \0 and U+FEFF are collation-ignorable, so the collated sort may interleave them while the scan re-checks with raw compareAt. Measured on the pristine master snapshot CD03879E7C3590DD (no part of this PR present): 13/40 runs abort. On this PR's build 81D9228A20282D29E50D4A66EF93D1295712522E: 11/40. The query has no ranking function, so needs_order_by_peer_group is false and every line of this diff is inert on that path. Without COLLATE: 0/20 on both.

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 [1,2,3,4,5,6,9,9,9] and [1,2,3,4,5,8,8,8,9] on unmodified master). I filed it as its own task with the repro and the API problem behind it: there is IColumn::compareAtWithCollation, but no collation-aware getEqualRangeEndAssumeSorted, so closing it means adding column API and moving RANGE frame starts and ends together. That does not belong in a wrong-results fix for rank/dense_rank.

What this PR does contract for is frame parity, and that holds under collation. RANK() over ['a','A','b','B','b'] with COLLATE 'en', before and after:

master this PR
no frame [1,2,3,3,5] [1,2,3,3,5]
RANGE frame [1,2,3,3,5] [1,2,3,3,5]
ROWS frame [1,2,3,4,5] [1,2,3,3,5]

Master disagrees with itself depending on the frame; this PR makes the ROWS answer equal the no-frame answer. Whatever a collated peer group ought to be, ROWS now returns the same thing RANGE and no-frame do, so it no longer degenerates into ROW_NUMBER.

One correction to my earlier reply. I wrote that haveEqualOrderByValues is byte-identical to the pre-PR arePeers RANGE tail. I verified that this round and it is exact (21 lines, diff clean), so the comparison semantics are unchanged by the move, but I had asserted it before checking, which was wrong of me.

Your literal example does not currently reproduce, for what it is worth: COLLATE 'en-u-ks-level1' over ['a','A','b'] gives [1,2,3] on master and on this PR, with and without a frame, so ks-level1 is not reaching a primary-strength comparison here. The ['a','A','b','B','b'] case above is the one that shows the frame divergence.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1fa1618

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.

175 check-runs, all completed. 3 failures.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Equal values are not contiguous within the range assumed to be sorted (STID 2508-46a9) pre-existing collation gap in the window RANGE frame-end peer scan, reproduced 13/40 on the pristine master snapshot with no ranking function in the query (so this diff is inert on that path); 0/20 without COLLATE a fix task is created (investigating at full effort, fixing-PR link to follow here)
AST fuzzer (amd_debug, targeted) / Invalid number of columns in chunk pushed to OutputPort (STID 2270-3258) trunk bug, RemoteSource::prepare stack with no window frame involved a fix task is already open and investigating (fixing-PR link to follow here)
Integration tests (arm_binary, distributed plan, 4/4) / test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write JetStream subscription closed by the broker, not reached by this diff fixing PR #112828 (mine, open)

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

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the first ledger line (STID 2508-46a9, Equal values are not contiguous within the range assumed to be sorted): #113399.

Root cause confirmed as the pre-existing collation gap: 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 look unequal. That cuts the peer group short (wrong results) and violates the equal-range scan's contiguity precondition, hence the logical error in debug and sanitizer builds. Independent of this PR's diff, as the A/B above showed.

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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bbdbc694f with master 96589eaf8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 7fc4e86ed; 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

14 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.
The matched translation units cost +1.9 s (+7%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6f06654

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
AST fuzzer (amd_debug, targeted) / Logical error: Invalid number of columns in chunk pushed to OutputPort (STID 2270-3258) pre-existing fuzzer family, 4 master hits and 79 distinct PRs in 30d #111401 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / same signature (STID 2270-3258) same family as above #111401 (mine, open)
Sync - CH Inc sync (private, not actionable)

Neither is caused by this PR's diff: the family predates it and fires on master and on many
unrelated PRs, and the failing fuzzer queries do not use a window function.

Session id: cron:our-pr-ci-monitor:20260814-180000

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

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.

@nihalzp nihalzp self-assigned this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-window-functions Window function execution + frame handling (ROW_NUMBER/RANK/LAG/LEAD, frames, partitions, order). label Sep 4, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 494af2f

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
AST fuzzer (amd_debug, targeted) / Logical error: Invalid number of columns in chunk pushed to OutputPort (STID 2270-3258) trunk bug, not from this diff: the same STID has 15 other carrier PRs and 4 true-master rows in the last 30 days #108045 (mine, open)

PR is the rollup of the row above, not a separate failure.

Session id: cron:our-pr-ci-monitor:20260905-060038

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1309aed

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
AST fuzzer (amd_debug, targeted) / Logical error: Invalid number of columns in chunk pushed to OutputPort (STID 2270-3258) trunk bug, not from this diff: a window function over remoteSecure(view(...)) with no referenced column. 129 rows / 79 distinct carrier PRs / 2 true-master rows in the last 30 days #113469 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Invalid number of columns in chunk pushed to OutputPort (STID 2270-3258) same trunk signature, clusterAllReplicas(view(...)) flavour of the same empty-header divergence #113469 (mine, open), merge-ordered behind #113955 (mine, open)

PR is the rollup of the two rows above, not a separate failure.

Session id: cron:our-pr-ci-monitor:20260909-043117

@nihalzp

nihalzp commented Oct 2, 2026

Copy link
Copy Markdown
Member

@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]>
@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Done, merged master in 9386eec.

The master refactor moved the peer comparison into WindowTransformParams and rank/dense_rank into src/WindowFunctions/, so I ported the fix onto that layout with the same logic: haveEqualOrderByValues now sits next to WindowTransformParams::arePeers. 04720 passes 50/50 with randomized settings, and the existing window-function stateless tests pass locally (two need CI-only server config and were not runnable here).

@qoega

qoega commented Oct 8, 2026

Copy link
Copy Markdown
Member

@nihalzp all green. Can you review? That one will help me with correctness validation

@qoega

qoega commented Oct 8, 2026

Copy link
Copy Markdown
Member

@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]>
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Done, merged master in 58cabab.

#123737 moved peer-group tracking into the per-block SlidingIndexes, which still marks every row as a peer group start under ROWS, so I re-ported the fix onto it: for a ROWS frame with rank/dense_rank the index also computes the ORDER BY peer group starts, and both functions read those. The runtime previous-row comparison and its block retention are gone. 04720 passes 50/50 under CI randomization and the window-function tests pass locally; the PR description is updated to match.

…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]>
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e28b1b9

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
AST fuzzer (amd_debug, targeted) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3e4f) not from this PR's change: RANK() OVER (ORDER BY v COLLATE 'en-u-ks-level2' GROUPS BETWEEN 3 PRECEDING AND CURRENT ROW). A GROUPS frame under COLLATE reaches the raw peer scan of SlidingIndexes::markPeerGroupStarts, which this PR leaves as on master (it changes only the ROWS frame index). The same abort reproduces on a master build and hit 2 other PRs in 30 days #113399 (mine, open): makes the RANGE/GROUPS peer scan honour COLLATE
AST fuzzer (amd_debug, targeted, old_compatibility) / same STID 2508-3e4f the same GROUPS + COLLATE path, with DENSE_RANK() and GROUPS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING #113399 (mine, open)
PR rollup, red only because of the rows above #113399 (mine, open)

All 152 check runs completed, Finish Workflow, Mergeable Check and CH Inc sync are green, and CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261008-180012

groeneai and others added 2 commits October 14, 2026 12:40
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 323ec28

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
AST fuzzer (amd_debug, targeted) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3e4f) not from this PR: RANK() OVER (ORDER BY v COLLATE 'en-u-ks-level2') uses the default RANGE frame and aborts in the main peer-group index (SlidingIndexes.cpp:154 -> :108), which compares raw values exactly as master does; same STID on 53 other PRs and on master in the last 30 days #113399 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / same STID 2508-3e4f same path, DENSE_RANK() OVER (ORDER BY v COLLATE 'en-u-ks-level2' WITH FILL), default RANGE frame #113399 (mine, open)

PR is the rollup of these two rows. The ROWS + COLLATE path this PR adds does not appear in either stack.

Session id: cron:our-pr-ci-monitor:20261014-170013

groeneai and others added 3 commits October 29, 2026 12:08
…-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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bbdbc69

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
AST fuzzer (amd_debug, targeted) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3e4f) not from this PR: DENSE_RANK() OVER (ORDER BY v COLLATE 'en-u-ks-level2' GROUPS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) aborts in the main peer-group index (SlidingIndexes.cpp:155 -> :108), which compares raw values exactly as master does #113399 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / same STID 2508-3e4f same path, RANK() OVER (ORDER BY v DESC COLLATE 'en-u-ks-level2', k WITH FILL), default RANGE frame #113399 (mine, open)
Stateless tests (arm_binary, parallel) / 05453_webterminal_close_at_binary_format_question flaky, not from this PR (51/51 reruns pass): the query stays in system.processes after the web terminal closes, because 05394_executable_pool_does_not_keep_closed_connection_open ran at the same time and its process inherited the terminal; failed on 8 other PRs since 2026-10-28 #126995 (mine, open)
Stateless tests (arm_binary, parallel) / Some queries hung the hung query is the 05453 query above (elapsed 620 s) #126995 (mine, open)
Finish Workflow / new_tests_check.py Bugfix validation did not run: all 74 dropped jobs were dropped after the arm_binary, parallel failure above #126995 (mine, open)

Mergeable Check and PR are rollups of these rows. The dropped jobs include both functional Bugfix validation jobs and every Performance Comparison shard, so this head has no bug-fix validation or performance result yet.

Session id: cron:our-pr-ci-monitor:20261030-010012

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

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.

@Michicosun Michicosun self-assigned this Nov 6, 2026

@Michicosun Michicosun 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.

will fix #129783

@Michicosun Michicosun closed this Nov 6, 2026
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. One thing I measured on the CI amd_debug build of #129783 (a0bcca0c): with the ROWS shortcut removed from assignPeerGroupIndexes, ROWS frames over a collated ORDER BY now reach the chassert in checkEqualRangeEndAssumeSorted ("Equal values are not contiguous within the range assumed to be sorted"), even for a plain aggregate:

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 (c9e18d01727e) returns 1, 3, 5, 7; #129783 aborts in SlidingIndexes.cpp:61. RANGE and GROUPS already abort this way on master, because the peer index compares keys without the collator (#124348, STID 2508-3e4f in the AST fuzzer). #113399 makes that index use the collator.

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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RANK() / DENSE_RANK() with an explicit ROWS frame silently degenerate into ROW_NUMBER()

5 participants