Skip to content

Fix crash in KeyCondition with LowCardinality column in CAST key expression - #101220

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/lc-cast-key-condition-crash
Apr 7, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/lc-cast-key-condition-crash

Conversation

@groeneai

@groeneai groeneai commented Mar 30, 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 to CHANGELOG.md):

Fix server crash (LOGICAL_ERROR: Bad cast from ColumnVector to ColumnLowCardinality) when querying a MergeTree table with ORDER BY CAST(lc_column, 'Type') where lc_column has a LowCardinality type.

What this PR fixes

When a MergeTree table uses ORDER BY CAST(lc_col, 'Type') where lc_col is a LowCardinality column, the key expression's monotonic function chain contains a FunctionCast that was built with LowCardinality argument types.

In applyFunctionChainToColumn(), the input constant column is stripped of LowCardinality at the top via convertToFullIfNeeded() (line 1030). However, the FunctionCast in the chain has useDefaultImplementationForLowCardinalityColumns() = false, meaning it handles LC internally through a wrapper that was prepared expecting ColumnLowCardinality input. When the stripped (plain ColumnVector) column is passed to this function, the wrapper's typeid_cast<const ColumnLowCardinality &> fails, crashing the server.

Root cause: The FunctionCast wrapper captures from_low_cardinality at preparation time (when types include LC), but receives a non-LC column at execution time because applyFunctionChainToColumn strips LC from the input.

Fix: Before executing each function in the chain, check if the function expects LowCardinality input but the column is not LowCardinality. If so, re-wrap the column in ColumnLowCardinality to match the function's expectation. The output is already stripped of LC after execution (existing code at line 1138).

Reproduction query:

SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE t (val LowCardinality(UInt32)) ENGINE = MergeTree() ORDER BY CAST(val, 'UInt64');
INSERT INTO t SELECT number % 100 FROM numbers(1000);
SELECT count() FROM t WHERE val = 42; -- crashes before fix

This crash was observed in CI stress tests and AST fuzzer (STID: 4054-600e) across 7 occurrences in 90 days.

Version info

  • Merged into: 26.4.1.609

…ession

When a MergeTree table has ORDER BY CAST(lc_col, 'Type') where lc_col is
LowCardinality, the monotonic function chain contains a FunctionCast built
with LowCardinality argument types. In applyFunctionChainToColumn(), the
input column is stripped of LowCardinality at the top (convertToFullIfNeeded),
but the FunctionCast wrapper still expects a ColumnLowCardinality input
(because useDefaultImplementationForLowCardinalityColumns returns false for
CAST). This mismatch causes a "Bad cast from ColumnVector to
ColumnLowCardinality" crash.

Fix: before executing each function in the chain, check if the function
expects LowCardinality input but the column is not LowCardinality.
If so, wrap the column in LowCardinality to match the function's expectation.
The output is already stripped of LowCardinality after execution (line 1138).

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (session: cron:clickhouse-ci-task-worker:20260330-131500)

a) Deterministic repro? ✅

SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE t (val LowCardinality(UInt32)) ENGINE = MergeTree() ORDER BY CAST(val, 'UInt64');
INSERT INTO t SELECT number % 100 FROM numbers(1000);
SELECT count() FROM t WHERE val = 42; -- crashes 100% of the time before fix

b) Root cause explained? ✅
The key expression CAST(val, 'UInt64') where val is LowCardinality(UInt32) creates a monotonic function chain containing a FunctionCast built with from_type = LowCardinality(UInt32). The wrapper in prepareUnpackDictionaries captures from_low_cardinality = non-null. In applyFunctionChainToColumn, the input constant column is stripped of LC at line 1030 via convertToFullIfNeeded(). When the stripped ColumnVector<UInt32> reaches the FunctionCast wrapper at execution (line 1137), the wrapper's typeid_cast<const ColumnLowCardinality &> fails because the column is not LC.

c) Fix matches root cause? ✅
The fix re-wraps the column in ColumnLowCardinality before executing a function that expects LC input (original_argument_type->lowCardinality()). This ensures the FunctionCast wrapper receives the LC column it expects. The output is already stripped at line 1138.

d) Test intent preserved / New test added? ✅
New regression test 04073_lc_cast_key_condition_crash added that exercises the exact crash path. No existing tests are modified.

e) Demonstrated in both directions? ✅

  • Without fix: SELECT count() FROM t WHERE val = 42 crashes with Logical error: 'Bad cast from type DB::ColumnVector<unsigned int> to DB::ColumnLowCardinality' — 100% crash rate
  • With fix: 50/50 passes with full randomization

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai — could you review this? It fixes a server crash (LOGICAL_ERROR) in KeyCondition::applyFunctionChainToColumn when the key expression contains a CAST on a LowCardinality column. The fix is a targeted 10-line change that re-wraps the column in LC before passing it to FunctionCast, which handles LC internally.

@pufit pufit added the can be tested Allows running workflows for external contributors label Mar 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [99b66ec]

Summary: ✅


AI Review

Summary

This PR fixes an exception in KeyCondition when a MergeTree key expression includes CAST over a LowCardinality column. The fix re-wraps the runtime column to ColumnLowCardinality only when the function’s declared argument type requires it, matching FunctionCast expectations. Added stateless regression coverage reproduces the failure and verifies correct query results. I did not find correctness, safety, concurrency, performance, or compatibility regressions in the patch.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
Final Verdict
  • Status: ✅ Approve

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

clickhouse-gh Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 92.31% (12/13) | lost baseline coverage: 6 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov 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.

Weird but okay.

@alexey-milovidov alexey-milovidov self-assigned this Apr 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 7, 2026
Merged via the queue into ClickHouse:master with commit 617ac6f Apr 7, 2026
161 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to release branches 26.3, 26.2, 26.1, 25.12, 25.11, 25.10, 25.9, 25.8, but no backport label was found.

Why: This fixes a LOGICAL_ERROR crash on a valid SQL query (CAST on LowCardinality column in ORDER BY). The affected code in applyFunctionChainToColumn has existed since LowCardinality + monotonic function chain support was added, which predates all active release branches.

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 7, 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 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.

5 participants