Repository navigation
Fix wrong row order for a multi-column ORDER BY over a LowCardinality float key - #116870
Conversation
…together ColumnLowCardinality::updatePermutation decided row equality by dictionary index identity, while ColumnLowCardinality::compareAt decides it by value. Those agree only if distinct dictionary entries always hold distinct values. For a floating-point inner type they do not: -0.0 and +0.0, and the different NaN bit patterns, have distinct bit patterns yet compare equal, and a dictionary is not canonicalized (ColumnUnique::uniqueInsert unifies NaN only, and -0.0 reaches uniqueInsertData whose default-entry check compares bytes). IColumn::updatePermutationImpl re-splits each range with the equality predicate and the next sort key only sees rows that predicate grouped together. An equality stricter than compareAt therefore drops the remaining sort keys for such a pair, and its order is left to the current key's comparator. In a debug build checkSortedWithPermutation catches the disagreement and aborts; in a release build the mis-ordered permutation is applied and the user gets wrong row order. Measured on release 26.8.1.2021: ORDER BY k ASC, v ASC over a LowCardinality(Float64) holding -0.0 and +0.0 returns 20, 40, 10, 30 where the answer is 10, 20, 30, 40. Rank the sorted dictionary once, incrementing only where the value changes, and key both the comparator and the equality off the rank. Boundaries use the same getDictionary().compareAt(..., nan_direction_hint) call compareAtImpl makes, so rank equality and compareAt == 0 cannot diverge; ranks stay monotone in value order, so the comparator's ordering is unchanged and rank equals position wherever no value-equal entries exist. Gated on a floating-point inner type by the predicate getEqualRangeEndAssumeSorted already uses for this same hazard (c90c40d "Skip the optimization for unsafe types"), so other dictionaries keep the previous code path and cost. When enabled the pass is O(dict) on top of the O(dict log dict) the dictionary permutation already costs. getPermutationImpl buckets rows by dictionary index too, and was left unchanged on purpose: it is only reachable with a stable single-key permutation, whose callers are all MergeTree-family writes, and every write path folds -0.0 onto the dictionary's default entry through ColumnUnique::uniqueInsertRangeFrom, so no written block can carry two value-equal float entries. Rank bucketing there was measured to be an unbacked behaviour change and is left out rather than shipped without a test that can fail. RowOrderOptimizer, which clusters equal values for compression, is improved by the same change since it no longer splits a -0.0/+0.0 run. The regression test drives clickhouse-local because that is the only surface where such a dictionary survives: a server converts the inserted block and maps -0.0 onto the default entry. It asserts the arming precondition (two bit patterns, one value) so it cannot pass vacuously, and asserts row order rather than the mere absence of an abort, since the abort is debug-only while the wrong order is what a release build returns.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold pass
Checked and not raised: my own carrier sweep of every Residuals disclosed, not addressed here: Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260828-093900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260828-052000 |
|
Workflow [PR], commit [8486cfa] Summary: ✅
AI ReviewSummaryThis PR fixes Missing context / blind spots
Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 8486cfa.
Changed lines: Changed C/C++ lines covered: 67/75 (89.33%) · Uncovered code |
|
cc @Avogar @KochetovNicolai, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes7 object files changed (+56.16 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units571 translation units recompiled, 5246 s compile time in total, 571 of them have a recent master baseline. |
…ardinality sort
`ColumnLowCardinality::getPermutationImpl` replicated the sorted dictionary
permutation by emitting the rows of one dictionary entry at a time. A float
dictionary is not canonicalized, so `-0.0` and `+0.0`, and distinct NaN
payloads, occupy separate entries while comparing equal. Rows of such entries
came out as several runs instead of one equal range in row order, which breaks
the stable-sort contract that `MergeTreeDataWriter`, `SSTIndexWriter`,
`EmbeddedRocksDBBulkSink` and `PreparedSets` depend on.
The MergeTree writer stable-sorts every inserted block, so the wrong order was
persisted into the part, and serialization then folded the duplicate entry away
so nothing was left to explain it. With `ReplacingMergeTree` and no version
column the surviving row differed from the one a plain `Float64` key keeps:
CREATE TABLE rmt (k LowCardinality(Float64), v UInt64)
ENGINE = ReplacingMergeTree ORDER BY k;
INSERT INTO rmt VALUES (5.0, 10), (-0.0, 20), (0.0, 30);
SELECT k, v FROM rmt FINAL; -- returned 0,20 where a Float64 key returns 0,30
A run of value-equal entries is now emitted as one group, with its rows merged
back into row order. This is the same equality the multi-column path derives
from a dictionary rank in `updatePermutation`. Detecting a run costs one
`compareAt` per dictionary entry and only under a stable sort over a float
dictionary, and the merge only runs for a group larger than one entry, so every
other type and sort keeps both its previous permutation and its previous cost.
Such a dictionary is only built by single-value insertion, which
`ColumnUnique::uniqueInsertData` reaches by comparing bytes against the default
entry, while the bulk path `ColumnUnique::uniqueInsertRangeFrom` folds it by
value. The regression arm therefore uses `clickhouse-local`, like the existing
ones in that test.
CI finish ledger - c009fa1Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Neither failure is caused by this PR. This PR changes
Same-tree negative controls: 8 of the 10 Session id: cron:our-pr-ci-monitor:20260828-193000 |
|
Fixing PR for the Root cause is unbounded mutual recursion between |
|
Fixing PR for the Root cause is unbounded mutual recursion between |
Avogar
left a comment
There was a problem hiding this comment.
The fix looks right to me and the root-cause analysis matches what I see in the code. One thing worth recording before this closes: the invariant this PR establishes -- value equality rather than dictionary-index identity -- still does not hold outside the sorting paths. On a current master build, with this PR's own fixture:
| query | LowCardinality(Float64) |
Float64 |
|---|---|---|
count() FROM (SELECT DISTINCT k) |
2 | 1 |
count() FROM (SELECT k GROUP BY k) |
2 | 1 |
uniqExact(k) |
2 | 1 |
and SELECT k FROM t GROUP BY k returns both 0 and -0. Plain float hash keys normalize signed zero, but the LowCardinality aggregation path keys on the dictionary entry's bytes, so LowCardinality(Float64) and Float64 disagree. Same family as this PR (a non-canonicalized float dictionary plus index-identity keying), different mechanism, and I agree it does not belong in this PR.
Could you open a follow-up issue for the aggregation and DISTINCT side and add Related: <link> to the description here? Otherwise the next reader of ColumnLowCardinality will reasonably conclude that the value-equal-entries problem was settled by this PR.
One note for whoever picks it up: canonicalizing the dictionary in ColumnUnique is not the fix, because it would drop the sign of zero from SELECT k, which plain Float64 preserves.
…ORDER BY directions updatePermutationImpl calls the equality predicate once per row per sort column, so the rank lookup added for value-equal float dictionary entries was paid by every LowCardinality sort. When no two entries compare equal the rank array is a bijection of dictionary positions, so the rank test cannot change the answer: that holds for every non-float dictionary, and for a float dictionary that was not built by single-value insertion. updatePermutation now reports whether ranking merged anything, and updatePermutationWithIndexType selects between the original single index comparison and the rank-based one. The predicate used when nothing merged is master's, unchanged. Forcing the flag to false makes the regression test abort again, so the flag is what selects the fixed path. The test pins the three remaining ORDER BY direction combinations, one of them under a LIMIT: that takes the separate limit branch of IColumn::updatePermutationImpl, which runs a partial sort and then reaches the equality predicate a second time to extend the last equal range past the limit. All three abort on a master-base debug build. Requested by @ Avogar in review: ClickHouse#116870 (comment) ClickHouse#116870 (comment)
|
Filed as #119503, and the description now carries it in One correction, found while measuring the issue text before filing: I cannot reproduce the
They do disagree, but on NaN and in the other direction: The issue also notes one shape reachable for plain |
…float-value-equal-dictionary-order
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong row order when sorting a
LowCardinalitycolumn of a floating-point type whose dictionary holds two entries that compare equal, such as-0.0and+0.0. A multi-columnORDER BYdid not apply the remaining keys to those rows, and theMergeTreewriter's stable sort did not keep them in insertion order, changing which rowReplacingMergeTreekeeps.Description
Both permutation paths of
ColumnLowCardinalitydecided row equality by dictionary index identity, whilecompareAtdecides it by value. Those agree only if distinct entries hold distinct values, and a float dictionary is not canonicalized:-0.0and+0.0, and different NaN payloads, compare equal with distinct bit patterns. Two effects:ORDER BY(updatePermutation): value-equal rows never shared an equal range, so the remaining keys were never applied. A debug build aborts atsortBlock.cpp:310,Rows are not sorted with permutation, as anAST fuzzer (amd_debug)report did; that instance is not reproducible, so I do not claim this PR fixes it.getPermutationImpl): rows of value-equal entries came out one entry at a time instead of in row order, breaking the stable sortMergeTreeDataWriteruses.MergeTreepersists that order into the part, so withReplacingMergeTreeand no version column the surviving row differed from the one a plainFloat64key keeps.Reachability is narrow: every bulk insert folds
-0.0onto the dictionary default (ColumnUnique::uniqueInsertRangeFromcompares by value), so the pair survives only where single-value insertion built it, inclickhouse-local, or in a dictionary deserialized from older data. On release 26.8.1.2021:The fix makes value-equal entries share one rank and keys equality off it, gated on a float inner type by the predicate
getEqualRangeEndAssumeSortedalready uses (c90c40d94e8c005), and on a stable sort for the single-key path. The rank comparison is selected only when ranking merged two entries, so every other dictionary keeps master's single index comparison in the per-row hot path.Nothing asks for a stable collated permutation, so the collated path, which can hold collation-equal entries, is untouched. Outside sorting the invariant still does not hold:
DISTINCT,GROUP BYanduniqExactkey on the dictionary entry, recorded in #119503.Related: #106588, #119503
Workflow [PR]
Sync PR [sync-upstream/pr/116870]
Version info
26.9.1.1291(included in26.9and later)