Skip to content

Fix wrong row order for a multi-column ORDER BY over a LowCardinality float key - #116870

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-lowcardinality-float-value-equal-dictionary-order
Sep 12, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-lowcardinality-float-value-equal-dictionary-order

Conversation

@groeneai

@groeneai groeneai commented Aug 28, 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):

Fix wrong row order when sorting a LowCardinality column of a floating-point type whose dictionary holds two entries that compare equal, such as -0.0 and +0.0. A multi-column ORDER BY did not apply the remaining keys to those rows, and the MergeTree writer's stable sort did not keep them in insertion order, changing which row ReplacingMergeTree keeps.

Description

Both permutation paths of ColumnLowCardinality decided row equality by dictionary index identity, while compareAt decides it by value. Those agree only if distinct entries hold distinct values, and a float dictionary is not canonicalized: -0.0 and +0.0, and different NaN payloads, compare equal with distinct bit patterns. Two effects:

  • Multi-column ORDER BY (updatePermutation): value-equal rows never shared an equal range, so the remaining keys were never applied. A debug build aborts at sortBlock.cpp:310, Rows are not sorted with permutation, as an AST fuzzer (amd_debug) report did; that instance is not reproducible, so I do not claim this PR fixes it.
  • One sorting key (getPermutationImpl): rows of value-equal entries came out one entry at a time instead of in row order, breaking the stable sort MergeTreeDataWriter uses. MergeTree persists that order into the part, so with ReplacingMergeTree and no version column the surviving row differed from the one a plain Float64 key keeps.

Reachability is narrow: every bulk insert folds -0.0 onto the dictionary default (ColumnUnique::uniqueInsertRangeFrom compares by value), so the pair survives only where single-value insertion built it, in clickhouse-local, or in a dictionary deserialized from older data. On release 26.8.1.2021:

SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE m (k LowCardinality(Float64), v UInt64) ENGINE = Memory;
INSERT INTO m VALUES (-0.0, 10), (0.0, 20), (-0.0, 30), (0.0, 40);
SELECT v FROM m ORDER BY k ASC, v ASC;  -- 20,40,10,30; expected 10,20,30,40

The fix makes value-equal entries share one rank and keys equality off it, gated on a float inner type by the predicate getEqualRangeEndAssumeSorted already 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 BY and uniqExact key on the dictionary entry, recorded in #119503.

Related: #106588, #119503


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

Version info

  • Merged into: 26.9.1.1291 (included in 26.9 and later)

…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 28, 2026
@groeneai

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) plus my own cold pass
before it (8 items). No blocker, one major, three nits.

# Sev Finding Verdict Evidence / action
1 ⚠️ The description's repro named no execution surface, so it does not reproduce as written AGREE, fixed in the description before publishing ColumnUnique::uniqueInsertRangeFrom (ColumnUnique.h:729-731) folds -0.0 onto the dictionary's default entry by value on every bulk insert, so that SQL returns the correct answer against a server. The description now says clickhouse-local and states the measured boundary
2 💡 05045_...order.sh:24 says the dictionary holds no value-equal entries, but line 27 inserts both -0.0 and 0.0 AGREE, not fixed in this push The comment is wrong, the arm is not. It is the many-distinct-values arm: it pins rank monotonicity around the value-equal zero group and is the only arm that catches a mutant which never increments the rank. Reference lines 7-12 show the zero group ordered by the second key
3 💡 The arming assertion proves one value via SELECT DISTINCT toFloat64(k); min(k) = max(k) would use the same comparator as the fix AGREE, noted $CLICKHOUSE_LOCAL does not inherit CLICKHOUSE_CLIENT_OPT (tests/queries/shell_config.sh:48-50), so the settings randomizer cannot move it; both analyzers were driven explicitly and it held 50/50

Checked and not raised: my own carrier sweep of every updatePermutationImpl supplier in
src/Columns found no other column whose equality predicate is stricter than its own compareAt;
the widened equality short-circuits on index identity inside a run, so its extra loads happen only
at a run boundary and the LowCardinality(String) path keeps its cost.

Residuals disclosed, not addressed here: estimateCardinalityInPermutedRange and hasEqualValues
are index-keyed too but only conservative, and getPermutationImpl buckets rows by dictionary index
as well. That last one is reachable only with a stable single-key permutation, whose callers are all
MergeTree-family writes, and every write path folds -0.0 onto the default entry, so it cannot carry
a value-equal pair. The commit message records why it was left alone rather than changed without a
test that can fail.

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

Session id: cron:clickhouse-review-slot-9:20260828-093900

@clickhouse-gh clickhouse-gh Bot closed this Aug 28, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. INSERT INTO m (k LowCardinality(Float64), v) VALUES (-0.0,10),(0.0,20),(-0.0,30),(0.0,40); SELECT v FROM m ORDER BY k ASC, v ASC in clickhouse-local. Aborts on base in all four ASC/DESC combinations; 5/5 through clickhouse-test.
b Root cause explained? Yes. ColumnLowCardinality::updatePermutation's equality was dictionary-index identity while compareAt is value-based. A float dictionary is not canonicalized, so -0.0 and +0.0 occupy separate entries; the pair never shared an equal range, so the remaining ORDER BY columns were never applied to it.
c Fix matches root cause? Yes. The two predicates are made consistent at the only place owning both, by ranking the sorted dictionary so value-equal entries share a rank. No widened bound, no relaxed assertion, no no-random-* tag.
d Test intent preserved / new tests added? New regression test 05045_low_cardinality_float_value_equal_dictionary_entries_order.sh, 5 arms, each proven load-bearing by a mutant that reddens only it. No existing test weakened or removed.
e Both directions demonstrated? Yes. Base aborts / fix returns 10,20,30,40, on Build-ID-verified binaries (ed91ffaf804ba15c vs 14185e4471d142be). Through clickhouse-test: base 5/5 FAIL, fix 50/50 OK.
f Fix is general across code paths? Every updatePermutation/getPermutation carrier enumerated. updatePermutationWithCollation is already consistent (comparator and equality both use compareAtWithCollation), ColumnTuple/ColumnMap/ColumnSparse forward to children and are covered, ColumnVector<Float*> shares CompareHelper between both predicates. getPermutationImpl is index-keyed too but measured unreachable: every write path folds -0.0 onto the dictionary default, so it is disclosed, not changed.
g Fix generalizes across inputs (params/datatypes/wrappers)? Float64, Float32, BFloat16, Nullable(Float64), inside Tuple; ASC/DESC; NULLS FIRST/LAST; float key 1st of 2, 2nd of 3, and last; 1 and 4 distinct values; NaN payloads; LowCardinality(String) control unchanged. Dictionary sizes 0 and 1 handled by the loop bounds; the pre-existing size check is untouched.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default change, no serialization or on-disk format change, so no SettingsChangesHistory.cpp entry. Behaviour changes only where the result is currently wrong.
i Invariants and contracts preserved? Ranks are monotone in the dictionary's own sort order, so ordering is unchanged and rank == position wherever no value-equal entries exist. Equality is now exactly compareAt == 0 because both use the same call. No allocation on an error path, no lock or concurrency contract involved, nothing persisted.

Session id: cron:clickhouse-impl-slot-5:20260828-052000

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8486cfa]

Summary: ✅


AI Review

Summary

This PR fixes ColumnLowCardinality sorting for float dictionaries that can contain distinct entries with equal values, making both the multi-key updatePermutation path and the stable single-key getPermutation path consistent with compareAt. I did not find a remaining correctness issue in the current diff; the added regression covers the user-visible misordering and the stable MergeTree write path that previously preserved the wrong row order.

Missing context / blind spots
  • ⚠️ Build (arm_tidy) and the aggregate PR check were still pending at review time, so this verdict is based on code inspection plus the already-green Fast test and Style check.
Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 8486cfa.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 67/75 (89.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @KochetovNicolai, could you review this? ColumnLowCardinality::updatePermutation decided row equality by dictionary index while compareAt decides it by value, so for a float dictionary holding -0.0 and +0.0 the pair never shared an equal range and the remaining ORDER BY keys were dropped. The fix ranks the sorted dictionary once so value-equal entries share a rank, gated on a float inner type by the predicate getEqualRangeEndAssumeSorted already uses.

Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8486cfa1b with master d2fe0254e (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Object file sizes

7 object files changed (+56.16 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Columns/ColumnLowCardinality.cpp.o 610.17 KiB 666.34 KiB +56.17 KiB (+9.21%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c009fa1

Every failure below has an owner: a fixing PR (ours 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
Stress test (amd_msan) / A data stream row of AlignStreams has no matching metadata stream row (STID 0250-16db) logical error, trunk regression, not caused by this PR #116909 (external, merged 2026-08-28 15:47Z), which reverts #116128. This build predates the revert, so the next push picks it up
Stress test (arm_asan_ubsan) / Segmentation fault (STID 3773-32b0) crash, trunk regression in analyzer set collection, not caused by this PR a fix task is in progress (investigating at full effort, fixing-PR link to follow on this PR)

Neither failure is caused by this PR. This PR changes ColumnLowCardinality permutation and one
regression test, so it touches no streaming, planner or analyzer code.

AlignStreams (STID 0250-16db): the file holding that message,
src/Storages/MergeTree/Streaming/ReadingPlan/AlignStreams.cpp, was added by #116128 (merged
2026-08-26 08:46Z) and removed again by the revert #116909 (merged 2026-08-28 15:47Z). The first
sighting anywhere is 2026-08-26 10:46Z, two hours after #116128 merged, and it reached 42 rows
across 39 unrelated PRs plus 3 master runs in the two days the code was on master. The workflow
run for this commit started 2026-08-28 13:38Z, before the revert, so the message was still
reachable in the tested build. It is unreachable on current master.

Segmentation fault (STID 3773-32b0): 3 rows across 3 unrelated PRs, 0 on master, all between
2026-08-28 16:03Z and 16:54Z. The fault is DB::collectSets (src/Planner/CollectSets.cpp)
against InDepthQueryTreeVisitorWithContext::visit
(src/Analyzer/InDepthQueryTreeVisitor.h:138) mutual recursion on a
CREATE TABLE test_very_long_chain ( statement.

Same-tree negative controls: 8 of the 10 Stress test arms passed on this exact commit,
including Stress test (arm_asan_ubsan, s3), so both failures are state and timing dependent
rather than tree dependent.

Session id: cron:our-pr-ci-monitor:20260828-193000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_asan_ubsan) Segmentation fault row (STID 3773-32b0) in the finish ledger above: #116978.

Root cause is unbounded mutual recursion between DB::collectSets and CollectSetsVisitor::enterImpl down a ConstantNode source-expression chain, which a long chain of DEFAULT column expressions drives one level per column. Reproduced on the official 26.8 release build with every setting at its default, so it is a trunk defect and not caused by this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_asan_ubsan) segfault (STID 3773-32b0) is now open: #116978.

Root cause is unbounded mutual recursion between collectSets and CollectSetsVisitor::enterImpl, which re-enters on a constant node source expression that is not a tree child, so nothing bounds the depth. Reproduced on the official 26.8 release build (SIGSEGV from a chain of 3500, all settings default), fixed by flattening that dimension into a worklist.

@Avogar Avogar self-assigned this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). label Sep 4, 2026

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

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.

Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved

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

See comments above

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

Copy link
Copy Markdown
Collaborator Author

Filed as #119503, and the description now carries it in Related:.

One correction, found while measuring the issue text before filing: I cannot reproduce the Float64 column of your table. On master 26.9.1.1 (debug build of c108e273b6087), clickhouse-local, your fixture:

query LowCardinality(Float64) Float64
count() FROM (SELECT DISTINCT k) 2 2
count() FROM (SELECT k GROUP BY k) 2 2
uniqExact(k) 2 2

SELECT k FROM f GROUP BY k returns both 0 and -0 for the plain Float64 column as well, and uniq/uniqCombined also report 2 on both types. So signed zero is normalized by neither, and here the two types agree.

They do disagree, but on NaN and in the other direction: ColumnUnique::uniqueInsert canonicalizes NaN payloads, so two distinct NaN bit patterns are one value for LowCardinality(Float64) and two for Float64 (DISTINCT, GROUP BY, uniqExact all 1 vs 2, and hex(reinterpretAsUInt64(k)) shows 7FF8000000000000 twice in the dictionary against ...0001 / ...0002 in the plain column). That is what the issue records, along with your point that canonicalizing in ColumnUnique is the wrong direction, since it would drop the sign of zero from SELECT k. Reshape or retitle it as you prefer.

The issue also notes one shape reachable for plain Float64 that neither this PR nor that mechanism covers: WHERE k IN (0.0) matches one of the two signed-zero rows while WHERE k = 0.0 matches both.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit b8798d6 Sep 12, 2026
175 checks passed
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-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants