Skip to content

Fix Bad cast ColumnSparse to ColumnString in groupConcat over Tuple with sparse subcolumn - #108790

Merged
nickitat merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-groupconcat-tuple-sparse-subcolumn
Jun 29, 2026
Merged

nickitat merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-groupconcat-tuple-sparse-subcolumn

Conversation

@groeneai

@groeneai groeneai commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #108722

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 a Bad cast from type DB::ColumnSparse to DB::ColumnString logical error (server abort in debug and sanitizer builds) when groupConcat is applied to a Tuple whose String element is stored sparse.

Description

The Aggregator's prepareAggregateInstructions only stripped top-level sparsity from aggregate arguments: it kept a column as-is when isSparse() was true (for the addBatchSparse fast path) and otherwise called recursiveRemoveSparse. A ColumnTuple is never top-level sparse, so a Tuple with a sparse subcolumn (e.g. Tuple(String) where the inner String is sparse-serialized) was left un-materialized and took the regular add() path. groupConcat text-serializes its argument there, and SerializationString::serializeTextQuoted does assert_cast<const ColumnString &>, which aborts:

Logical error: 'Bad cast from type DB::ColumnSparse to DB::ColumnString'.
  ... assert_cast.h:43
  ... SerializationString::serializeTextQuoted
  ... SerializationTuple::serializeText (SerializationTuple.cpp:199)
  ... GroupConcatData::insert (AggregateFunctionGroupConcat.cpp:56)
  ... Aggregator::executeWithoutKeyImpl (Aggregator.cpp:1405)

The code already removes LowCardinality recursively (recursiveRemoveLowCardinality descends into Tuple), but the symmetric recursive sparse removal was missing.

Fix: keep the column sparse only when it is a genuine top-level ColumnSparse (the only form addBatchSparse consumes); otherwise materialize it with recursiveRemoveSparse, which descends into Tuple and is a no-op when nothing is sparse. The dense and top-level-sparse paths are unchanged.

Among the single-argument aggregate functions tested over Tuple(sparse String) (any, anyLast, min, max, argMax, groupArray, uniqExact, count, topK, groupUniqArray), only groupConcat aborted, because it is the only one that uses text serialization with a dense assert_cast; the fix at the Aggregator level covers any future text-serializing consumer of the regular add() path. Verified that the result on a sparse-serialized table matches the result on a never-sparse table.

Found by the AST fuzzer (CIDB STID 3336-3d40, check AST fuzzer (arm_asan_ubsan)):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108722&sha=3286c6cd675541995b290a1faafb8f0be49b3740&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29

No related open issue found.

Added a regression test 04416_groupconcat_tuple_sparse_subcolumn that aborts the server on the unfixed binary and passes with the fix.

Version info

  • Merged into: 26.7.1.250 (included in 26.7 and later)
  • Backported to: 26.3.30.10

…ith sparse subcolumn

The Aggregator only stripped top-level sparsity from aggregate arguments. A
column that is dense at the top level but holds sparse subcolumns (e.g. a Tuple
with a sparse String element) was left un-materialized and took the regular
add() path. groupConcat text-serializes its argument there, and
SerializationString::serializeTextQuoted does assert_cast<const ColumnString&>,
which aborts with 'Bad cast from type DB::ColumnSparse to DB::ColumnString'.

Materialize an argument with recursiveRemoveSparse() unless it is a genuine
top-level ColumnSparse (the only form the addBatchSparse fast-path consumes).
recursiveRemoveSparse() recurses into Tuple and is a no-op when nothing is
sparse, so the dense and top-level-sparse paths are unchanged.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t(id UInt64, t Tuple(s String)) ENGINE=MergeTree ORDER BY id SETTINGS ratio_of_defaults_for_sparse_serialization=0.0, min_bytes_for_full_part_storage=0; INSERT ... 20 default rows + 1 non-default; SELECT groupConcat(t) aborts every time on the unfixed binary. system.parts_columns confirms the inner String is Sparse-serialized.
b Root cause explained? Aggregator prepareAggregateInstructions only strips TOP-LEVEL sparsity (isSparse()). A ColumnTuple is never top-level sparse, so a Tuple with a sparse subcolumn is left un-materialized and takes the regular add() path; groupConcat text-serializes it and SerializationString::serializeTextQuoted does assert_cast<const ColumnString&> on a ColumnSparse → abort. (The code already strips LowCardinality recursively; recursive sparse removal was missing — the same asymmetry.)
c Fix matches root cause? Yes. Materialize the argument with recursiveRemoveSparse unless it is a genuine top-level ColumnSparse; recursiveRemoveSparse descends into Tuple. Targets the exact mechanism in (b), at the Aggregator (the column's source), not a per-row guard in groupConcat.
d Test intent preserved / new tests added? New regression test 04416_groupconcat_tuple_sparse_subcolumn added. Asserts no abort + result equals the never-sparse table + nested-tuple + limit variant. No existing test weakened.
e Demonstrated both directions? Yes. Unfixed binary (Build 6F5F11...): server aborts (SIGABRT, exit 134). Fixed binary: 50/50 passes via clickhouse-test with randomization ON.
f Fix is general, not a narrow patch? Fixed at the Aggregator (root), so it covers ALL aggregate functions, not just groupConcat. Empirically, among any/anyLast/min/max/argMax/groupArray/uniqExact/count/topK/groupUniqArray/groupConcat over Tuple(sparse String), only groupConcat aborted (only one using text serialization with a dense assert_cast); the Aggregator fix protects any future text-serializing consumer of the regular add() path.
g Generalizes across inputs/wrappers? Verified plain sparse String, Array, Map, Nullable were already safe (top-level sparse handled). Verified Tuple(String), Tuple(LowCardinality(UInt64), String), nested Tuple(Tuple(String)), Array(Tuple(String)), GROUP BY key path, and the groupConcat(delim, limit) variant all pass. recursiveRemoveSparse recurses into Tuple; correctness vs a never-sparse table is identical.
h Backward compatible? Yes. No setting, on-disk, wire, or metadata change. Pure in-memory materialization that only affects a previously-aborting path; dense and top-level-sparse fast paths are byte-for-byte unchanged (verified sum/count/groupConcat over a top-level sparse column unchanged).
i Invariants/contracts preserved? Yes. recursiveRemoveSparse preserves column size and values (it is the canonical "materialize for a dense-leaf consumer" helper, already used by NativeWriter, HashJoin, MergeTreeDataWriter). The addBatchSparse fast-path contract (literal top-level ColumnSparse) is preserved by the && isSparse() guard.

Session id: cron:clickhouse-worker-slot-1:20260629-041000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @nickitat — could you review this? The Aggregator only stripped top-level sparsity from aggregate arguments, so a Tuple with a sparse subcolumn reached the regular add() path un-materialized and groupConcat aborted in serializeText with a ColumnSparse -> ColumnString bad cast. Fix keeps the top-level-sparse addBatchSparse fast path but otherwise materializes via recursiveRemoveSparse (which descends into Tuple).

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

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [73dbf25]

Summary: ✅


AI Review

Summary

This PR fixes aggregate argument preparation so a top-level-dense Tuple with sparse subcolumns is materialized before it reaches regular aggregate add paths such as groupConcat text serialization, while preserving the literal top-level ColumnSparse fast path. The added stateless regression test exercises the sparse tuple, dense comparison, nested tuple, and limit variant. I did not find any new blocking or major issues in the patch.

Missing context / blind spots
  • ⚠️ I could not run the new stateless test locally because this checkout has no build directory or clickhouse binary. The direct Praktika PR report showed no failures when queried, but the full GitHub check rollup still had functional/build jobs in progress at review time.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 5/5 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 8 line(s) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 73dbf25

CI fully finished on this head (Finish Workflow pass; no checks queued/in_progress; >20-min ingestion buffer). This PR's own fix (the Aggregator.cpp sparse-subcolumn materialization for groupConcat over a Tuple with a sparse String leaf, STID 3336-3d40) works: that LOGICAL_ERROR does not reproduce on this head. Every red below is a pre-existing trunk/infra failure unrelated to this PR's diff, and each has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Segmentation fault (STID 2684-288b) chronic trunk crash — HashJoin additional-filter path (buildAdditionalFilter -> joinRightColumnsWithAdditionalFilter -> ColumnString::insertFrom), release-build twin of debug STID 2508-30f6; unrelated to this PR's Aggregator.cpp change fixing PR #107957 (ours, open)
Performance Comparison (arm_release, master_head, 3/6) host-OOM — report-build step MergeSortingTransform exceeds the 53.44 GiB perf-host cap (Code 241); the perf comparison itself is clean (408 queries, 0 not-OK / 0 changed / 0 unstable); chronic across 10 unrelated PRs in 7d a fix task is created (investigating at full effort — fixing-PR link to follow here)
Mergeable Check / PR aggregators reflecting the two reds above (resolved via the two owners above)

Session id: cron:our-pr-ci-monitor:20260629-090000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release) report-build MEMORY_LIMIT_EXCEEDED host-OOM created: #108804

@nickitat nickitat self-assigned this Jun 29, 2026
@nickitat
nickitat enabled auto-merge June 29, 2026 15:05
@nickitat
nickitat added this pull request to the merge queue Jun 29, 2026
Merged via the queue into ClickHouse:master with commit 20481eb Jun 29, 2026
511 of 514 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 29, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.2, 26.3, 26.4, 26.5. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@groeneai

Copy link
Copy Markdown
Collaborator Author

26.3 and 26.6 never received this fix, and that is now blocking the #115705 backports.

Aggregator::prepareAggregateInstructions still has the pre-fix ternary on both branches: 26.3 at Aggregator.cpp:1706 and 26.6 at :1540 read allow_sparse_arguments ? getPtr() : recursiveRemoveSparse(...), while 26.7:1567, 26.8:2151 and master:2156 have the (allow_sparse_arguments && ...->isSparse()) form. This PR merged on 2026-06-29 with pr-bugfix ("not backported by default"), i.e. after the 26.6 cut and before the 26.7 one, so both branches still hand a Tuple with a sparse element to a single-argument aggregate un-materialized.

The test #115705 adds, 05025_group_concat_window_sparse_tuple.sql, runs a plain groupConcat aggregation before its window query, so the 26.3 backport #117073 aborts on that first query rather than on the window path it fixes:

(query: SELECT length(groupConcat(t)) FROM t_group_concat_sparse_tuple;) Received signal Aborted (6)
Logical error: 'Bad cast from type DB::ColumnSparse to DB::ColumnString'
assert_cast.h:43 <- SerializationString::serializeTextQuoted <- SerializationTuple::serializeText
  <- GroupConcatData::insert <- Aggregator::executeWithoutKeyImpl <- AggregatingTransform::consume

Server died in the same run, and Stress test (amd_tsan) carries the same payload (report). Over 30 days that message has exactly one head_ref in CIDB, backport/26.3/115705. #117060 (26.7) and #117061 (26.8) are green because they carry this fix; I expect #117076 (26.6) to fail the same way once its stateless job runs, since its builds are still pending.

@alexey-milovidov could you apply v26.3-must-backport here, so the robot produces the missing backports? I am not hand-authoring release-branch changes. Of the branches @ clickgapai listed above in June, only 26.3 is still supported; 26.6 predates this fix as well and needs it too, while 26.7 and 26.8 already carry it. Outside CI it is reachable on both with default table settings, since ratio_of_defaults_for_sparse_serialization defaults to 0.9375. All four settings the new test uses already exist on both branches, so I do not expect a follow-on blocker.

One note for whoever merges #117073: the window half of that cherry-pick looks like a correct adaptation, since 26.3 calls the helper convertToFullIfNeeded, which is what master later renamed to convertToFullIfWrapped. It was not exercised in the failing run because the server aborted on the preceding query.

alexey-milovidov added a commit that referenced this pull request Aug 31, 2026


The backported test crashed on `26.3` with
`Bad cast from type DB::ColumnSparse to DB::ColumnString` already in the plain
`SELECT groupConcat(t)` query, before reaching the window function that this
backport is about.

`Aggregator::prepareAggregateInstructions` on `26.3` only strips top-level
sparsity from aggregate arguments. A column that is dense at the top level but
holds sparse subcolumns - exactly a `Tuple` with a sparse element - was left
un-materialized and took the regular `add` path, where
`SerializationString::serializeTextQuoted` does
`assert_cast<const ColumnString &>` and aborts.

Cherry-pick the one-line condition (and its test) from
#108790, which is on `master` but
was never backported: keep the argument sparse only when it is a genuine
top-level `ColumnSparse`, which is the only form the `addBatchSparse` fast path
consumes. `recursiveRemoveSparse` is a no-op when there is nothing sparse to
strip, so the dense and top-level-sparse paths are unchanged.

Verified against the `26.3` CI binary of this pull request: the reference output
of `04416_groupconcat_tuple_sparse_subcolumn` matches, and the query aborts
without this fix.

Related: #108790
alexey-milovidov added a commit that referenced this pull request Sep 1, 2026
The backported test `05025_group_concat_window_sparse_tuple` also runs a plain
`SELECT length(groupConcat(t))`, which aborts on `26.6` because
`Aggregator::prepareAggregateInstructions` only strips *top-level* sparsity: a
`Tuple` that is dense at the top level but holds a sparse `String` element reaches
`SerializationString::serializeTextQuoted` as a `ColumnSparse`.

That is fixed on `master` by 73dbf25 (from
#108790), which was never backported.
Cherry-pick its one-line change and its test
`04416_groupconcat_tuple_sparse_subcolumn` so that this backport is self-contained.

Reproduced on `26.6` with the PR's own CI binary: the plain `groupConcat` over the
sparse `Tuple` aborts, and the `['Sparse','Sparse','Sparse']` reference line is
identical to `master`.
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 1, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 1, 2026
nickitat added a commit that referenced this pull request Sep 3, 2026
Backport #108790 to 26.3: Fix Bad cast ColumnSparse to ColumnString in groupConcat over Tuple with sparse subcolumn
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
…mnString in groupConcat over Tuple with sparse subcolumn
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…concat-tuple-sparse-subcolumn

Fix Bad cast ColumnSparse to ColumnString in groupConcat over Tuple with sparse subcolumn
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
AGG: window function over a Tuple with a sparse element -> crash.
Effect in the production build a394e92: wrong/failing (the upstream test fails on it and passes on official 26.8.8.8; evidence/fix_ci_20260925/upstream_repro/residual/115705.PROD263.txt).
Upstream patch unchanged, with its test(s): 04416_groupconcat_tuple_sparse_subcolumn, 05025_group_concat_window_sparse_tuple.
It also contains the fix of ClickHouse#108790 (groupConcat over a Tuple with a sparse String, 26.3 backport ClickHouse#117568, reproduced on the production build: evidence/fix_ci_20260925/upstream_repro/residual/108790.PROD263.txt): the 26.3 backport ClickHouse#117073 carries the identical Aggregator.cpp change and test 04416, so ClickHouse#108790 needs no separate commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants