Repository navigation
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260705-003700 |
|
cc @KochetovNicolai @vdimir — could you review this? |
|
Workflow [PR], commit [92094ae] Summary: ✅
AI ReviewSummaryThis PR has been narrowed to the SQL-reproducible Tests
Final Verdict✅ No new review findings on the current revision. LLVM Coverage ReportMeasured on commit 92094ae.
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
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]>
c967026 to
e24e86d
Compare
…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]>
| }); | ||
|
|
||
| if (!any_changed) | ||
| return full; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:
-
The clean choke-point is not safe. Folding the recursion into
recursiveRemoveSparse/removeSpecialRepresentations(so they recurse throughNullable/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).recursiveRemoveSparsealso deliberately re-wraps a nestedColumnReplicated(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. -
The family is broader than these five. The same top-level-only
removeSpecialColumnRepresentations(chunk)feeds cross-chunkcompareAtinColumnGathererTransform,IntersectOrExceptTransform,MergeJoinTransformandDistinctTransformas well, plus every dictionary key path. This is really a generalIColumn::compareAtcontract issue (a densethiscannot compare against a sparse/replicatedrhs), not aFinishSortingTransformissue.
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]>
|
Fixed the The gate failed because this is a Removed the non-reproducing |
CI finish ledger — c19d2d2Every 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
Session id: cron:our-pr-ci-monitor:20260706-033000 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 254/257 (98.83%) · Uncovered code |
|
@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 I checked this against a current-master debug binary ( 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 CI agrees independently on this head: 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 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. |
CI finish ledger - 1da35c2Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-120000 |
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 10 s compile time in total, 7 of them have a recent master baseline. |
…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]>
…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.
CI finish ledger - ab2f37bEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Neither row is reachable from this PR's diff, which changes sort-key materialization in Session id: cron:our-pr-ci-monitor:20260920-230126 |
|
The fixing PR for the |
| @@ -0,0 +1,638 @@ | |||
| #include <gtest/gtest.h> | |||
There was a problem hiding this comment.
This test is too much, consider adding only a small, minimal sql test that reproduces the issue.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
We can avoid merging this 450-line PR since it does not fix any visible behavior, please consider closing it.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Add this to testcases, remove gtests, keep whole patch small
There was a problem hiding this comment.
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]>
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes wrong rows returned by
ORDER BY ... LIMITover aMergeTreetable read in the order of a function of its sorting key (for exampleORDER BY toStartOfMonth(date) DESC, i) when the sorting key column uses sparse serialization. Debug and sanitizer builds throw aLOGICAL_ERRORBad cast from type DB::ColumnSparseinstead.Description
Closes: #105920
Related: #106566
On 26.8.2.7 the last query returns
4750, 4900, 4901, 4902, 4903instead of4750to4754(24.8.14.39, 25.3.14.14 and 26.3.33.24 return wrong rows too), and a debug build of master throwsBad cast from type DB::ColumnSparse to DB::ColumnVector<unsigned short>atFinishSortingTransform.cpp:94(STID 1499-2393):dateis sparse in the single part, andtoStartOfMonthreturns a full column for a chunk without default rows and a sparse one otherwise, so the descending read in order passesFinishSortingTransform::consumea full chunk followed by a sparse one.consumebinary-searches the stored chunk withless, which callsColumnVector::compareAtwith theColumnSparserhs:assert_castthrows in debug and sanitizer builds, and a release build reads the column as the wrong type.consumeexpanded onlyColumnReplicatedsort keys (#106566). It now callsIColumn::convertToFullIfWrapped, which expandsColumnSparseas well, recursively.The new test
05291_finish_sorting_sparse_sort_keyfails 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
26.10.1.971-master(included in26.10and later)