Skip to content

Materialize sparse sort-key columns in FinishSortingTransform - #109424

Merged
vdimir merged 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-1499-2393-finishsorting-columnsparse
Sep 29, 2026
Merged

vdimir merged 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-1499-2393-finishsorting-columnsparse

Conversation

@groeneai

@groeneai groeneai commented Jul 5, 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 wrong rows returned by ORDER BY ... LIMIT over a MergeTree table read in the order of a function of its sorting key (for example ORDER BY toStartOfMonth(date) DESC, i) when the sorting key column uses sparse serialization. Debug and sanitizer builds throw a LOGICAL_ERROR Bad cast from type DB::ColumnSparse instead.

Description

Closes: #105920
Related: #106566

On 26.8.2.7 the last query returns 4750, 4900, 4901, 4902, 4903 instead of 4750 to 4754 (24.8.14.39, 25.3.14.14 and 26.3.33.24 return wrong rows too), and a debug build of master throws Bad cast from type DB::ColumnSparse to DB::ColumnVector<unsigned short> at FinishSortingTransform.cpp:94 (STID 1499-2393):

CREATE TABLE t (date Date, i UInt64) ENGINE = MergeTree ORDER BY (date, i) SETTINGS index_granularity = 100;
INSERT INTO t SELECT if(number < 4750, toDate(0), toDate('2020-10-10')), number FROM numbers(5000);
SELECT toStartOfMonth(date) AS d, i FROM t ORDER BY d DESC, i LIMIT 5;

date is sparse in the single part, and toStartOfMonth returns a full column for a chunk without default rows and a sparse one otherwise, so the descending read in order passes FinishSortingTransform::consume a full chunk followed by a sparse one. consume binary-searches the stored chunk with less, which calls ColumnVector::compareAt with the ColumnSparse rhs: assert_cast throws in debug and sanitizer builds, and a release build reads the column as the wrong type.

consume expanded only ColumnReplicated sort keys (#106566). It now calls IColumn::convertToFullIfWrapped, which expands ColumnSparse as well, recursively.

The new test 05291_finish_sorting_sparse_sort_key fails with the error above on debug and ASan builds of master and passes with this change, including 80 runs with randomized settings.


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

Version info

  • Merged into: 26.10.1.971-master (included in 26.10 and later)

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. src/Processors/tests/gtest_finish_sorting_sparse.cpp feeds FinishSortingTransform a dense UInt16 chunk then a ColumnSparse(UInt16) chunk with the same key value; it aborts on demand with Bad cast from type DB::ColumnSparse to DB::ColumnVector<unsigned short>.
b Root cause explained? consume() binary-searches the stored chunk with less() (raw IColumn::compareAt). It materialized only ColumnReplicated sort-key columns. When a stored chunk's sort key is dense ColumnVector<UInt16> and the next chunk's is ColumnSparse, ColumnVector::doCompareAt assert_casts the sparse rhs to its own dense type and aborts.
c Fix matches root cause? Yes. The sort-key materialization loop now does convertToFullColumnIfSparse()->convertToFullColumnIfReplicated(), mirroring IMergingAlgorithm::removeConstAndSparse and the base SortingTransform (which already materializes sparse/const/replicated before building cursors).
d Test intent preserved / new tests added? 02149_read_in_order_fixed_prefix output is byte-for-byte identical to its reference (zero regression). New: the gtest above + a name-anchored stateless test 04365_stid_1499_2393_finishsorting_columnsparse.
e Both directions demonstrated? Yes. The gtest SIGABRTs without the change and PASSES with it (verified on a Build-ID-changed binary).
f Fix is general across code paths? Audited every less() / cross-column compareAt sort consumer: FinishAggregatingInOrderAlgorithm and all merge algorithms already call removeConstAndSparse; PartialSortingTransform uses compareColumn (sparse-safe) against thresholds built via removeSpecialRepresentations (dense). AggregatingInOrderTransform::less materializes keys only with convertToFullColumnIfConst (a theoretical sparse sibling), but it did not reproduce (aggregation-in-order over a sparse key ran clean), so per the no-speculative-changes rule it is noted, not touched here.
g Fix generalizes across inputs (params/datatypes/wrappers)? The materialization is type-generic (convertToFullColumnIfSparse on any IColumn); the reported case is Date/UInt16 but the fix covers every sparse-serializable sort-key type.
h Backward compatible? Yes. No setting, on-disk, or wire format change; a pure runtime column materialization that yields a semantically identical dense column.
i Invariants and contracts preserved? Yes. Materialization produces a full column equal in value to the sparse one; block structure (columns/types/row count) is unchanged; the subsequent compactReplicatedColumns and less() operate on full columns exactly as the base SortingTransform intends.

Session id: cron:clickhouse-worker-slot-2:20260705-003700

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @vdimir — could you review this? FinishSortingTransform::consume() materialized only ColumnReplicated sort-key columns before its cross-chunk less() compare, so a dense sort key in one chunk and the same key as ColumnSparse in the next (from read-in-order over parts with mixed serialization) hit ColumnVector::doCompareAt's assert_cast on a sparse column (STID 1499-2393). The fix adds convertToFullColumnIfSparse, mirroring removeConstAndSparse and the base SortingTransform. It's the ColumnSparse sibling of #106024, but reproduces deterministically (new gtest fails without the change, passes with it).

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [92094ae]

Summary: ✅


AI Review

Summary

This PR has been narrowed to the SQL-reproducible FinishSortingTransform::consume bug plus a stateless regression test. In that final 3-file form, the fix matches the failure mode described in the PR, the test pins both the sparse serialization and the FinishSortingTransform path, and I did not find a remaining correctness or metadata issue in the current revision.

Tests
  • Not rerun locally in this workspace; review is based on the current diff, prior thread history, and the added stateless test.
Final Verdict

✅ No new review findings on the current revision.

LLVM Coverage Report

Measured on commit 92094ae.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 5, 2026
FinishSortingTransform::consume() accumulates chunks and, for each new
chunk, binary-searches the previously stored chunk with less() (a raw
IColumn::compareAt). It materialized only ColumnReplicated sort-key
columns, unlike the base SortingTransform, which materializes sparse,
const and replicated columns before building cursors.

When read-in-order reads parts with mixed serialization, one chunk can
carry a dense sort-key column and the next the same key as ColumnSparse.
The cross-chunk compare then does ColumnVector<T>::doCompareAt with a
ColumnSparse rhs, whose assert_cast aborts in debug/sanitizer builds
(release silently reads wrong memory):

  Logical error: Bad cast from type DB::ColumnSparse to
  DB::ColumnVector<unsigned short>

Captured by the AST fuzzer on 02149_read_in_order_fixed_prefix over
amd_msan (STID 1499-2393); the sort prefix was toStartOfMonth(date),
a Date (UInt16).

Materialize sort-key columns with removeSpecialRepresentations, which
expands the replicated wrapper first and then recursively strips sparse
(including Replicated(Sparse), which convertToFullColumnIfReplicated
leaves as a plain ColumnSparse, and tuple-wrapped sparse subcolumns).
Mirrors IMergingAlgorithm::removeConstAndSparse and the base
SortingTransform.

Adds a deterministic unit test (gtest_finish_sorting_sparse) covering
both a plain ColumnSparse and a Replicated(Sparse) sort-key column: each
aborts without this change and passes with it. Also adds a name-anchored
stateless test for the fuzzed query shape.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-stid-1499-2393-finishsorting-columnsparse branch from c967026 to e24e86d Compare July 5, 2026 11:34
…tingTransform

Review on ClickHouse#109424 pointed out that removeSpecialRepresentations only expands
the top-level replicated wrapper, so a replicated (or sparse) child of a tuple
sort key stayed wrapped: Tuple(Replicated(k)) reached the cross-chunk less()
where ColumnTuple::compareAt delegates to the child and
ColumnVector::compareAt(..., ColumnReplicated) bad-cast one level deeper.

Replace it with a local recursive materializer that expands the replicated and
sparse wrappers and recurses into ColumnTuple children, so Tuple(Replicated),
Tuple(Sparse) and Replicated(Sparse) all become dense. LowCardinality and const
are left as-is, matching the base SortingTransform cursor preparation (and
avoiding a sort-key type change vs the output header).

Extends the gtest with a Tuple(Replicated) sort-key case that aborts with
'Bad cast from type DB::ColumnReplicated to DB::ColumnVector<unsigned short>'
without the fix and passes with it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ansform

Follow-up to review on PR ClickHouse#109424: verify a Nullable(UInt16) sort key that
is dense in one buffered chunk and sparse in the next does not bad-cast in
the cross-chunk less() of consume().

A sparse nullable column is ColumnSparse(ColumnNullable(...)) -- the sparse
kind is applied outermost by IDataType::createColumn, and ColumnNullable
rejects a sparse nested column because ColumnSparse::canBeInsideNullable()
is false. So the top-level convertToFullColumnIfSparse in materializeSortKeyColumn
already densifies it before less(). The reverse nesting ColumnNullable(ColumnSparse)
raised in review is unconstructible.

Tests:
- NullableSparseSortKeyDoesNotBadCast: dense vs ColumnSparse(ColumnNullable);
  aborts with the CI Bad cast without the sparse strip, passes with it.
- NullableCannotWrapSparse: pins the ColumnNullable(sparse) rejection invariant
  so a future change enabling sparse-inside-nullable fails here loudly.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…n FinishSortingTransform

The previous helper only expanded a top-level replicated wrapper and recursed
into ColumnTuple, so a sparse or replicated column nested under ColumnNullable
(e.g. Nullable(Tuple(Sparse(UInt16)))) still reached the raw compareAt in
less(). ColumnNullable, ColumnArray and ColumnMap compareAt all delegate to
their children, so the bad cast (ColumnSparse/ColumnReplicated to ColumnVector)
was reachable one level deeper. Replace the hand-enumerated recursion with a
generic forEachSubcolumn walk that strips replicated+sparse at every level
(mirroring IColumn::convertToFullIfNeeded) while leaving LowCardinality intact,
since it is a distinct data type in the block header. Add regression coverage
for Nullable(Tuple(Sparse)) and Nullable(Tuple(Replicated)) sort keys.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The generic materializeSortKeyColumn helper that FinishSortingTransform uses
to densify sort-key columns before the raw compareAt in less() is now shared
with MergeSorter (the ordinary merge-sort path used by MergeSortingTransform).

Previously MergeSorter only peeled a top-level ColumnReplicated wrapper per
sort column, so a replicated column nested inside a composite sort key (e.g.
Tuple(Replicated(k)), reachable via ORDER BY tuple(join_col) with
enable_lazy_columns_replication=1) survived to the merging cursors, where
ColumnTuple::compareAt delegated to ColumnVector::compareAt(..., ColumnReplicated)
and hit the same Bad cast the read-in-order FinishSortingTransform path was
already fixed for.

The helper is moved to SortingTransform.{h,cpp} and applied at both sort sites.
It recurses through tuple/nullable/array/map children, expanding replicated and
stripping sparse at every level, while leaving LowCardinality intact (a distinct
data type that is part of the block header, and which the cursors handle).

Adds a MergeSorter gtest (Tuple(Replicated) sort key) that aborts with the exact
Bad cast without the change and passes with it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The bad-cast fix for FinishSortingTransform / MergeSorter used only a
top-level replicated/sparse strip for two more raw-compareAt sort sites,
so a composite sort key still reached compareAt with one side dense and
the other wrapped, bad-casting one level deeper:

- IMergingAlgorithm::removeReplicatedFromSortingColumns (used by
  MergingSortedAlgorithm, AggregatingSortedAlgorithm,
  SummingSortedAlgorithm, FinishAggregatingInOrderAlgorithm,
  IMergingAlgorithmWithSharedChunks): a top-level
  convertToFullColumnIfReplicated plus the following removeConstAndSparse
  (recursiveRemoveSparse recurses only through Replicated/Tuple) left a
  child like Tuple(Replicated) or Nullable(Tuple(Sparse)) intact before
  SortCursorImpl.

- PartialSortingTransform saved threshold row: normalized with
  removeSpecialRepresentations, same recursion gap, so the threshold
  (rhs of compareWithThreshold / getFilterMask against the dense live
  keys) kept a sparse/replicated child under Nullable/Array/Map.

Both now reuse the recursive materializeSortKeyColumn, which is moved
from SortingTransform to Columns/ColumnSparse so the lower-level merge
header can use it. Live partial-sort keys are left as-is: they are
always the lhs of the comparison, and a wrapped lhs handles a dense rhs;
the existing convertToFullColumnIfReplicationNotUseful preserves the
lazy-replication optimization for large keys.

Fixes STID 1499-2393.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Columns/ColumnSparse.cpp Outdated
});

if (!any_changed)
return full;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

materializeSortKeyColumn closes the sort / merge sites touched here, but the same dense-vs-wrapped boundary compare is still reachable in the stateful key-comparison transforms that keep normalizing with removeSpecialRepresentations. That helper still only expands a top-level ColumnReplicated (src/Columns/ColumnSparse.cpp:1004-1010), so keys like Tuple(Replicated(k)) or Nullable(Tuple(Sparse(k))) still survive into AggregatingInOrderTransform (src/Processors/Transforms/AggregatingInOrderTransform.cpp:159-163), CheckSortedTransform (src/Processors/Transforms/CheckSortedTransform.cpp:61-81), DistinctSortedStreamTransform (src/Processors/Transforms/DistinctSortedStreamTransform.cpp:107-143), and the sorted LIMIT BY variants (src/Processors/Transforms/LimitByTransform.cpp:340-398, src/Processors/Transforms/NegativeLimitByTransform.cpp:360-487).

Those sites still funnel into ColumnTuple::compareAt (src/Columns/ColumnTuple.cpp:630-640), so when one chunk stores a dense key and the next stores the same key with a replicated / sparse child, the dense lhs will bad-cast on the wrapped rhs exactly like the original failure. I think these boundary keys need to reuse materializeSortKeyColumn before this family of bugs is actually closed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: all five sites (AggregatingInOrderTransform, CheckSortedTransform, DistinctSortedStreamTransform, LimitByTransform, NegativeLimitByTransform) normalize keys with the top-level-only removeSpecialColumnRepresentations / removeSpecialRepresentations and then compare across chunks with raw compareAt, so a composite key such as Tuple(Replicated) or Nullable(Tuple(Sparse)) stored dense in one chunk and wrapped in the next reaches the same bad cast one level deeper (ColumnTuple / ColumnNullable compareAt delegate straight to their children; ColumnVector::doCompareAt then static_casts the wrapped rhs). The mechanism is real.

I don't think growing this crash-fix PR site by site is the right shape, though, for two concrete reasons:

  1. The clean choke-point is not safe. Folding the recursion into recursiveRemoveSparse / removeSpecialRepresentations (so they recurse through Nullable / Array / Map) would fix every site at once, but those two helpers have ~40 callers well outside sorting (Dictionaries, HashJoin, Squashing, NativeWriter, Aggregator, patch parts). recursiveRemoveSparse also deliberately re-wraps a nested ColumnReplicated (ColumnSparse.cpp:967) to keep the lazy-replication optimization; forcing full densification there would regress those hot non-sort paths. So the recursive materializer has to stay opt-in per raw-sort-key site, not baked into the shared normalizer.

  2. The family is broader than these five. The same top-level-only removeSpecialColumnRepresentations(chunk) feeds cross-chunk compareAt in ColumnGathererTransform, IntersectOrExceptTransform, MergeJoinTransform and DistinctTransform as well, plus every dictionary key path. This is really a general IColumn::compareAt contract issue (a dense this cannot compare against a sparse/replicated rhs), not a FinishSortingTransform issue.

So I'd prefer to keep this PR scoped to the reported crash (STID 1499-2393 in FinishSortingTransform) plus the two directly-adjacent raw sort-cursor paths already covered here: the IMergingAlgorithm merge algorithms and the PartialSortingTransform saved threshold, which share the exact SortCursorImpl / threshold comparison. The remaining stateful-transform and dictionary siblings are better handled as a dedicated follow-up whose approach a maintainer can pick: either a mechanical sweep applying the shared materializeSortKeyColumn at each raw-compareAt normalization site, or a base-level fix making compareAt handle a sparse/replicated rhs symmetrically. I'm happy to do either once the approach is decided, rather than expanding this bug-fix PR unboundedly one nesting level per round.

… proof

STID 1499-2393 is a debug/sanitizer-only assert_cast abort that needs a
dense-vs-wrapped sort key across two sort-cursor chunks. That asymmetry is
not reachable from SQL: the standard read-in-order pipeline densifies both
merged chunks symmetrically, so the 04365 stateless test never aborted on
master HEAD. The Bugfix-validation merge gate (new_tests_check.py) then
saw a Bug-Fix PR adding a functional test that no per-arch job could
validate, and blocked the merge.

Remove the 04365 stateless test and rely on gtest_finish_sorting_sparse.cpp,
which constructs the exact dense/sparse and dense/replicated cross-chunk
state directly and is a deterministic fail-without / pass-with proof. Fold
the read-in-order fuzzer query context into the gtest's discoverability
comment so no provenance is lost.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the Finish Workflow / new_tests_check.py merge gate @ c19d2d2.

The gate failed because this is a pr-bugfix PR that added a functional test (04365_stid_1499_2393_finishsorting_columnsparse.sql), and the hook requires at least one per-arch Bugfix Validation job to validate it (bug reproduces on master HEAD, fixed on the PR). All four per-arch jobs reported SKIPPED ("bug does not reproduce on this arch") because STID 1499-2393 is not reachable from SQL: it needs a dense sort-key column in one sort-cursor chunk and the same key wrapped (ColumnSparse/ColumnReplicated) in the next, and the standard read-in-order pipeline densifies both merged chunks symmetrically, so the stateless test never aborted on master HEAD.

Removed the non-reproducing 04365 stateless test and rely on src/Processors/tests/gtest_finish_sorting_sparse.cpp, which constructs that dense-vs-wrapped cross-chunk state directly and is a deterministic fail-without / pass-with proof (8 cases: plain sparse, Replicated(Sparse), Tuple(Replicated), Nullable(Sparse), Nullable(Tuple(Sparse|Replicated)), and the MergeSorter sibling). The read-in-order fuzzer query context is folded into the gtest's discoverability comment so no provenance is lost. With no new functional test, the hook takes its has_unit branch and passes.

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c19d2d2

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
Stateless tests (amd_asan_ubsan, distributed plan, parallel, 2/2) / 03532_window_function_and_null_source_max_threads flaky (query_plan_optimize_join_order_randomize collapses the crazy-max_threads EXPLAIN PIPELINE so error 290 is not raised; 30+ unrelated PRs + 4 master hits in 30d; the same test fails identically on unrelated PRs incl. a docs-only PR, so not caused by this FinishSortingTransform change) #109330 (external, open)
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260706-033000

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

Does it reproduce in SQL?

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 254/257 (98.83%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

@vdimir No, it does not reproduce in SQL, and I could not construct a query that reaches it. Sorry for the slow reply.

The reason is structural: for Type::FinishSorting, SortingStep::transformPipeline calls mergingSorted immediately before finishSorting (src/Processors/QueryPlan/SortingStep.cpp:570 and :575), and read-in-order adds its own preliminary MergingSortedTransform on top when there is more than one stream. Every merge densifies the sort-key columns via IMergingAlgorithm::removeConstAndSparse (convertToFullIfConst + convertToFullIfSparse, IMergingAlgorithm.h:55-59), so whatever reaches FinishSortingTransform::consume has already been made dense. The bad cast needs the opposite: one chunk dense and the next one still ColumnSparse for the same key, which is what the cross-chunk less() binary search at FinishSortingTransform.cpp:94 compares.

I checked this against a current-master debug binary (9b24abd99cc683, unfixed, Build ID ef52c5f831df), not just by reading the code. I can get the on-disk asymmetry easily: with ratio_of_defaults_for_sparse_serialization = 0.5 and min_bytes_for_wide_part = 0, a part whose k is all-default serializes k as Sparse while a second part serializes it as Default, confirmed in system.parts_columns. But every plan I could build put a merge in between, so nothing aborted. The most direct attempt was a single part with a uniformly sparse key and max_block_size = 1024, which does reach FinishSortingTransform with no merge at all (EXPLAIN PIPELINE shows FinishSortingTransform -> PartialSortingTransform -> ExpressionTransform -> MergeTreeSelect, no MergingSortedTransform) and still does not abort, because a single part is uniformly sparse and there is no asymmetry to hit. Variants over part count, read_in_order_two_level_merge_threshold, max_streams_for_merge_tree_reading, virtual rows and block sizes all behaved the same way.

The original STID 1499-2393 came from the AST fuzzer, which is why the crash is real but has no SQL form: the assertion is a debug/sanitizer-only assert_cast, so a release build silently reads wrong memory instead of failing, and the state itself needs the two cursors to disagree.

CI agrees independently on this head: Bugfix validation (unit tests) is green while the functional and integration validators report skipped. That job builds a "before" binary from the merge base with only the PR's unit-test file overlaid and requires the new test to fail there, so a green result is a machine check that the gtest fails without the fix and passes with it. The functional validators being N/A is the same statement in the other direction, that no functional test of mine reproduces on unfixed master.

So the gtest is the regression test here, under the "unit test only when the behavior is not observable from SQL" carve-out. An earlier revision of this PR did carry a stateless test pinning the fuzzed query shape, but since it could not fail on unfixed master it made the new_tests_check.py merge gate fail, and I removed it in c19d2d2. The description still advertised it, which is probably what prompted your question; I have corrected that paragraph to state the merge-densification reason instead.

If you would rather have the FinishSorting materialization loop covered from SQL, the only way I see is a test-only hook to suppress the densifying merge, which seems worse than the gtest. Happy to go that way if you prefer it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1da35c2

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit the per-table concurrency throttle the test asserts is keyed on query id, and secondary parallel-replicas reads are sent without one, so the holder query competes against itself (3/3 reruns, deterministic) #112385 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-120000

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
No test job ever ran on the previous head. The PR workflow run for b724868 failed in Config Workflow: praktika's CI-database lookup timed out five times against play.clickhouse.com, the job was SIGTERMed at its 600 s timeout, and every dependee job was dropped (172 skipped, 0 tests executed).

That run is already at attempt 2. The hourly retry_infra_failures.yml workflow re-ran attempt 1 while the same outage was still ongoing, and it only ever considers attempt 1 inside a 6 hour cutoff, so no automated path can retry this head again.

This commit carries no content change. Its only purpose is to make GitHub fire a fresh pull_request run so the fix gets a real CI signal.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 92094aef8 with master 1e5291bf9 (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.

Compile time of recompiled translation units

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

Job report

…columnsparse

The Bugfix validation (unit tests) job could not run on the previous head. Its merge-base was the 2026-08-01 master merge, and master has since moved .gitmodules and 24 contrib submodules, so the job could not populate a before-worktree at the merge-base submodule revisions and reported the validation as inconclusive.

This PR changes no submodule state. Merging master makes the merge-base a recent master commit whose submodule pins match the checkout, which is what lets the before-binary be built.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Columns/ColumnSparse.cpp Resolved
…columnsparse

Resolve the two conflicts in src/Processors/Transforms/SortingTransform.cpp as a union of
both sides:

* includes: keep master's reorganized include block (ColumnReplicated.h moved below the
  std includes by 3e8a8d8) and add Columns/ColumnSparse.h next to it, needed for
  materializeSortKeyColumn.
* the comment above the MergeSorter sort-key loop: master reworded it to state that only
  keys are materialized while non-key replicated payloads keep their representation; keep
  that property and keep the reason the materialization has to be recursive (compareAt
  handles neither sparse nor replicated columns, at any nesting depth inside a composite
  key). No code change on either side of this hunk.

master pinned at da0e428.
master gained `IColumn::convertToFullIfWrapped` after this branch was cut: it
strips Const, Replicated and Sparse recursively through every subcolumn and
deliberately keeps LowCardinality, which is a semantic type rather than a
representation wrapper. That is what the `materializeSortKeyColumn` helper added
here did, so the helper was a duplicate of an existing public API. Drop it and
call the upstream one at the five sort-key normalization sites.

Removing it also takes `Columns/ColumnSparse.h` back out of
`Processors/Merges/Algorithms/IMergingAlgorithm.h`, a header with 11 in-tree
includers, and leaves `ColumnSparse.{h,cpp}` untouched by this PR.

Verified on the merged tree (debug, ENABLE_TESTS=1): the 22 regression cases in
FinishSortingTransform / MergeSorter / MergingSortedAlgorithm /
PartialSortingTransform pass with `convertToFullIfWrapped` (Build-ID
aacf485fb554b9e57d11245a92535bbf73643241) and abort with `Bad cast from type
DB::ColumnSparse to DB::ColumnVector<unsigned short>` when the five call sites
are reduced to master's `convertToFullColumnIfReplicated` (Build-ID
05a8c41b90ac5f180e91e2b3e18dc628c9081b86). clang-tidy-22 is clean on all five
changed translation units.

Also drops the review-round narrative from the test comments (`CR1`, `CR2`,
"raised in review") and refers to functions as `f` rather than `f()`, per the
in-tree style.
`assert_cast` only checks its operand type in debug and sanitizer builds, so an
`EXPECT_NO_THROW` around each pipeline proved nothing about a release build, where
the same comparison is an unchecked `static_cast` over the wrong representation.

The four runners now return the `y` payload in output order and every case asserts
it. The three full-sort paths must emit both inputs interleaved (0, 0, 1, 1, ...
n-1, n-1, since every `x` is equal), and the two TopK cases must emit 2999 rows of
a possible 3000: the first block truncated to the LIMIT, the second filtered to the
rows strictly below its threshold row, which can only happen if the threshold
comparison ran.

`sparseNullableUInt16` now builds the representation a nullable sparse column
actually takes: slot zero, the implicit default, is `NULL`, and the non-null rows
are stored at the offsets. It previously put a non-null value in the default slot,
which no serializer emits.

Drops `NullableCannotWrapSparse`, which asserted a pre-existing `ColumnNullable`
constructor guard and so passed no matter what this PR changed. The invariant it
pinned stays documented at `sparseNullableUInt16`, which relies on it.

Verified (debug, ENABLE_TESTS=1): 21/21 pass (Build-ID 981652979cdf90a56ae2dc9f6d276222252f970e); reducing the five call
sites to master's `convertToFullColumnIfReplicated` aborts with `Bad cast from type
DB::ColumnSparse to DB::ColumnVector<unsigned short>` (Build-ID
f74277216d0ca7f1021f3c2bbdefadb2d45aaa53), and reverting only the
`FinishSortingTransform` site aborts the nullable case on its own with `Bad cast
from type DB::ColumnSparse to DB::ColumnNullable` (Build-ID
dfe0ba4bf1e3d6d4b843cb641a476b742a8649f4). Perturbing the expected payload fails
exactly the nine cases that use it, so the new assertions are live rather than
vacuous (Build-ID d3d93a49ab465979cf289cd67cab674f603ac47c).
`convertToFullIfWrapped` also strips ColumnConst, which the `materializeSortKeyColumn`
helper it replaced did not, and `PartialSortingTransform` normalizes only the saved
threshold row, never the live key columns of the incoming block. So with a constant
sort key the block column stayed a ColumnConst while the threshold became dense, and
`getFilterMask` reached `ColumnConst::compareColumn` then `ColumnConst::compareAt`,
which casts its rhs to ColumnConst.

`Fast test` on c9d82eb segfaulted exactly there on `02427_column_nullable_ubsan`
(`SELECT 0 AS a, ... ORDER BY a DESC, b DESC, c ASC LIMIT 1500`), because
`assert_cast` is an unchecked `static_cast` in that build, and took the server down
after 8471 tests.

Preserving a top-level ColumnConst keeps the recursive nested materialization the rest
of this PR adds. The other four call sites are unaffected: they normalize every
input's key columns symmetrically, and `SortingTransform` / `FinishSortingTransform`
already drop const columns before that loop.

Verified (debug, ENABLE_TESTS=1): the new const-threshold gtest case aborts on the
unfixed tree with `Bad cast from type DB::ColumnVector<unsigned short> to
DB::ColumnConst` at `PartialSortingTransform.cpp:48` (Build-ID
5a7e7af80fea4c62ee4393fb10a10d6e19f6d5a0) and 22/22 pass with the fix (Build-ID
60d7d3cee90c2c5889779614246084bc76e4125c). End to end, `02427_column_nullable_ubsan`
aborts with the same message and returns no rows on the pristine head (Build-ID
de781b4e69daf066b853634ff1c5f12b1245e848) and returns its reference output with the
fix (Build-ID 63938f093be3f36b24927ba5fb74fb115f03d77c). Eight ORDER BY / LIMIT
queries over const, nullable, LowCardinality and tuple sort keys return results
byte-identical to a master build.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ab2f37b

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
Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1 performance-dashboard confirmed_regression (+16.5%, 15.8 to 18.4 ms) that this shard's own report does not call slower; the same query swings by at least +15% on 70 of 313 true-master arm runs in 10 days #121090 (mine, open)
Performance Comparison (arm_release, master_head, 2/6) / index_bulk_filtering #0 the same gate, but here the fixture itself is bimodal: 5-9 ms in 1555 of 2471 arm runs and 25-39 ms in 889, with the same split on the master binary as on the PR binary, so a mode flip reads as +289%. #121090 does not green this shard, because this job's own report does call the query slower a fix task is created (investigating at full effort, fixing PR link to follow here)

Mergeable Check and PR are the rollup of the two rows above and carry no separate failure.

Neither row is reachable from this PR's diff, which changes sort-key materialization in
FinishSortingTransform and PartialSortingTransform: index_bulk_filtering #0 reaches the same two
modes on true master, and order_by_read_in_order #1 swings at least as far on true master runs, in both
cases without that diff present.

Session id: cron:our-pr-ci-monitor:20260920-230126

@groeneai

Copy link
Copy Markdown
Collaborator Author

The fixing PR for the index_bulk_filtering #0 row of the ledger above is open: #121260. It pins the fixture's part layout (SYSTEM STOP MERGES per table plus max_block_size), so the two sides of a run measure the same layout and the mode flip that reddened Performance Comparison (arm_release, master_head, 2/6) on ab2f37b0 cannot occur.

@@ -0,0 +1,638 @@
#include <gtest/gtest.h>

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.

This test is too much, consider adding only a small, minimal sql test that reproduces the issue.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and I am cutting it: 638 lines of gtest for a 16-line fix is wrong. I will keep only what still fails without the change and drop the rest.

On a sql test: I tried and could not build one. consume is the only site this PR touches that has no sparse handling at all on master (MergeSorter already calls convertToFullIfSparse, SortingTransform.cpp:40), and the abort needs a dense stored chunk compared against a sparse incoming one, because ColumnSparse::compareAt accepts a dense rhs (ColumnSparse.cpp:578). serialization_kind is a per-part property and readInOrder creates one source per part (ReadFromMergeTree.cpp:964), so two differently serialized parts are always two streams, and every collapse to one stream is a MergingSortedTransform, whose initialize densifies recursively. A single-stream FinishSorting plan therefore reads exactly one part, whose sort key is uniformly sparse.

Measured on master 688ee332, debug, with system.parts_columns confirming one Sparse and one Default part on the sort key every time: the 02149_read_in_order_fixed_prefix FinishSorting query with an all-default date part; 12 combinations of read_in_order_two_level_merge_threshold and max_threads on the arrayJoin lazy-replication shape that 04304_lazy_crash_2 uses to reach this same line; query_plan_join_shard_by_pk_ranges=1, the only FinishSorting branch with no mergingSorted call, over 4 disjoint parts alternating Sparse/Default; and 9 wrapped sort keys (tuple(key), toNullable(key), [key], map('k', key), ...). None abort.

That is not a proof, since the fuzzer did reach this line with a ColumnSparse (STID 1499-2393). If you know the plan shape that gets two differently serialized parts into one stream ahead of FinishSortingTransform, I will write the .sql test and drop the gtest entirely.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 29ddff7b1a620: 638 lines and 12 cases down to 454 and 5, one per call site this PR changes, keeping the reported ColumnSparse shape plus one nested shape at consume.

Each of the 5 still aborts without the source change, with the exact bad cast it is named for (checked one at a time, since the first abort takes the whole binary down), and all 5 pass with it. The 29 tests of the four touched suites stay green.

One case went for a different reason: ConstThresholdDoesNotBadCast passed in both directions, so it pinned nothing. That shape already has SQL coverage in 02427_column_nullable_ubsan, whose SELECT 0 AS a, toNullable(number) AS b, ... ORDER BY a DESC, b DESC, c ASC LIMIT 1500 is a const sort key on the threshold path.

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.

We can avoid merging this 450-line PR since it does not fix any visible behavior, please consider closing it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found the SQL repro I was missing, and it is a wrong result on stable releases. Default settings, in clickhouse local:

CREATE TABLE t (date Date, i UInt64) ENGINE = MergeTree ORDER BY (date, i);
INSERT INTO t SELECT if(number < 950000, toDate(0), toDate('2020-10-10')), number FROM numbers(1000000);
SELECT toStartOfMonth(date) AS d, i FROM t ORDER BY d DESC, i LIMIT 5;

The right answer is 950000 to 950004. 26.8.2.7 and 25.8.34.13 return 950000, 974848, 974849, 974850, 974851, 26.3.33.24 returns 974848 to 974852 (25.3.14.14 is correct), and a debug build of master 026dca38e7d throws Bad cast from type DB::ColumnSparse to DB::ColumnVector<unsigned short> at FinishSortingTransform.cpp:94, the STID 1499-2393 stack. On 26.8.2.7 the same data in a table with ratio_of_defaults_for_sparse_serialization = 1 returns the right rows, and this PR's head returns them for the sparse table.

What I missed: one part is enough. date is Sparse in it, and toStartOfMonth returns a full column for a chunk with no default rows (IFunction.cpp:771), so the descending read yields full chunks first and sparse ones after, in one stream with nothing in between to densify them. consume then compares the stored full chunk against the incoming sparse one.

I'd like to cut this PR to the consume change plus this query as a small .sql test, dropping the gtest and the four other call sites I could not reach from SQL. If you still prefer closing it, I'll close it.

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.

Add this to testcases, remove gtests, keep whole patch small

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 7ee1581 and 92094ae: the PR is now the consume change plus 05291_finish_sorting_sparse_sort_key.sql (3 files, +32/-3), with the gtest and the other four call sites dropped. The test throws the bad cast on debug and ASan builds of master and passes with the fix.

A correction to my previous comment: with the test's data, 24.8.14.39 and 25.3.14.14 also return wrong rows, so this is not a recent regression.

The test file was 638 lines of gtest for a 16-line fix, which @vdimir flagged as
too much. It carried 12 cases over 4 call sites, several of which only restated a
sibling wrapper combination at the same site.

What survives is one case per call site this PR changes, plus the reported crash:
FinishSortingTransform gets the STID 1499-2393 shape itself (top-level
ColumnSparse) and one nested shape (Nullable(Tuple(Sparse))), which is what
motivates convertToFullIfWrapped over a single top-level strip; MergeSorter,
IMergingAlgorithm::removeReplicatedFromSortingColumns and the
PartialSortingTransform threshold each keep one nested case.

Every remaining case still aborts without the source change, each with the exact
bad cast it is named for (verified individually, SIGABRT on a debug build), and
all 5 pass with it; the 29 tests of the four touched suites stay green.

PartialSortingTransform.ConstThresholdDoesNotBadCast is dropped for a different
reason: it passed in both directions, so it pinned nothing about this diff. The
const threshold branch is already covered from SQL by
02427_column_nullable_ubsan, whose
`SELECT 0 AS a, toNullable(number) AS b, ... ORDER BY a DESC, b DESC, c ASC LIMIT 1500`
is exactly a const sort key on the threshold path.

Comments lost their fix-referential narration ("before the fix X bad-cast"),
which belongs in this message rather than in the test body; the ones stating a
non-obvious property that a reader cannot derive from the code (which wrapper
nests inside which, why the row count is a live threshold comparison) stay.

No behaviour change: source files are untouched by this commit.

Co-Authored-By: Claude Opus 5 <[email protected]>
groeneai and others added 2 commits September 28, 2026 19:33
Keep only the `FinishSortingTransform::consume` change: its sort keys are
normalized with `convertToFullIfWrapped` instead of
`convertToFullColumnIfReplicated`, so a `ColumnSparse` key is expanded too.

`toStartOfMonth` over a sparse column returns a full column for a chunk
without default rows and a sparse one otherwise, so a descending read in
order of a single part passes `consume` a full chunk followed by a sparse
one, and `less` then calls `ColumnVector::compareAt` with a `ColumnSparse`
rhs: a `LOGICAL_ERROR` in debug and sanitizer builds, wrong rows in a release
build.

Revert the `MergeSorter`, `PartialSortingTransform` and
`IMergingAlgorithm::removeReplicatedFromSortingColumns` changes, which no SQL
query was found to reach, and replace the gtest with the stateless test
`05291_finish_sorting_sparse_sort_key`, as requested in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The result rows are also correct under a full sort, so check the
pipeline too. `enable_parallel_replicas = 0` keeps the plan local in the
ParallelReplicas configuration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vdimir
vdimir added this pull request to the merge queue Sep 29, 2026
Merged via the queue into ClickHouse:master with commit 3f1c583 Sep 29, 2026
149 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 29, 2026
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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-unknown PR origin: unclassified (legacy task) 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.

[CI crash] Incorrect column comparison during sorting

5 participants