Skip to content

Fix Bad cast in KeyCondition for Variant constant with LowCardinality member - #107111

Merged
nihalzp merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-variant-lowcardinality-bad-cast
Jun 11, 2026
Merged

nihalzp merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-variant-lowcardinality-bad-cast

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix LOGICAL ERROR (Bad cast from type DB::ColumnString to DB::ColumnLowCardinality) when a Variant constant containing a LowCardinality member is compared to a key column whose key expression is a non-monotonic deterministic function (for example a minmax skip index over sipHash64(col)).

Description

Found by the server-side AST fuzzer on master (Stress test (experimental, serverfuzz, amd_tsan), STID 4054-600e).

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=02e4401eea6456ba042a6da9d32e7c2a75e85685&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20amd_tsan%29

Fuzzed query:

SELECT * FROM mergeTreeAnalyzeIndexesUUID(
    '...',
    equals(timestamp, _CAST('1704063900', 'Variant(Date32, Int256, LowCardinality(String), MultiPolygon, Ring)')),
    [...parts...]);

Minimal reproducer (a plain SELECT ... WHERE is enough; the table function is not required):

SET allow_suspicious_low_cardinality_types = 1, allow_experimental_variant_type = 1, allow_suspicious_variant_types = 1;
CREATE TABLE t (key Int, s String, INDEX i sipHash64(s) TYPE minmax GRANULARITY 1) ENGINE = MergeTree ORDER BY key;
INSERT INTO t VALUES (1, 'a'), (2, 'hello');
SELECT count() FROM t WHERE equals(s, _CAST('hello', 'Variant(Int256, LowCardinality(String))'));

Root cause: KeyCondition::applyDeterministicDagToColumn materialized the constant column with convertToFullIfNeeded(), which recurses into ColumnVariant members and strips their inner LowCardinality, while the type was stripped with recursiveRemoveLowCardinality, which keeps LowCardinality inside a Variant (it has no Variant branch). The constant column member therefore became a ColumnString while its type still said LowCardinality(String), so the Variant -> String cast wrapper performed a typeid_cast to ColumnLowCardinality on a ColumnString and aborted.

Fix: strip only outer-level wrappers (Const/Replicated/Sparse/LowCardinality) from the column and use removeLowCardinality on the type, so column and type stay symmetric (both keep LowCardinality inside containers such as Variant). This mirrors the existing fix in the sibling function applyFunctionChainToColumn (#103211), which handled the monotonic-function path; the same problem remained in the deterministic-function path that this fuzzer sighting reached.

A new stateless regression test 04329_key_condition_variant_low_cardinality is added. It crashes on master HEAD and passes with this fix.

Version info

  • Merged into: 26.6.1.632

… member

A constant whose type is a Variant containing a LowCardinality member,
compared to a key column with a non-monotonic deterministic key expression
(e.g. a minmax skip index on sipHash64(col)), aborted the server with
'Bad cast from type DB::ColumnString to DB::ColumnLowCardinality' in
KeyCondition::applyDeterministicDagToColumn.

The function materialized the constant column with convertToFullIfNeeded(),
which recurses into ColumnVariant members and strips their inner
LowCardinality, while the type was stripped with recursiveRemoveLowCardinality
which keeps LowCardinality inside Variant (it has no Variant branch). The
resulting column member was a ColumnString while its type still said
LowCardinality(String), so the Variant->String cast wrapper performed a
typeid_cast to ColumnLowCardinality on a ColumnString.

Strip only outer-level wrappers (Const/Replicated/Sparse/LowCardinality) and
use removeLowCardinality on the type, keeping column and type symmetric. This
mirrors the existing fix in applyFunctionChainToColumn.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT count() FROM t WHERE equals(s, _CAST('hello', 'Variant(Int256, LowCardinality(String))')) on a table with INDEX i sipHash64(s) TYPE minmax aborts 100% of the time on master HEAD (snapshot binary, SIGABRT 134). No randomization needed.
b Root cause explained? Yes. applyDeterministicDagToColumn materialized the constant with convertToFullIfNeeded(), which recurses into ColumnVariant members and strips their inner LowCardinality, while the type was stripped with recursiveRemoveLowCardinality, which has no Variant branch and keeps inner LowCardinality. Column member became ColumnString, type still said LowCardinality(String), so the Variant -> String cast wrapper did typeid_cast<ColumnLowCardinality&> on a ColumnString.
c Fix matches root cause? Yes. The fix restores column/type symmetry: strip only outer-level wrappers from the column and use removeLowCardinality on the type. No defensive guard; it eliminates the asymmetry at its source.
d Test intent preserved / new tests added? New regression test 04329_key_condition_variant_low_cardinality added (Variant-with-LC equals, the member-collision Variant, single-member LC Variant, the IN-set path, skip-index ON/OFF agreement, and a non-matching prune case). No existing test weakened.
e Both directions demonstrated? Yes. Test crashes (SIGABRT) on master HEAD and matches its reference with the fix. Verified skip-index ON and OFF agree (match -> 1, miss -> 0).
f Fix is general, not a narrow patch? Yes. The only two key-transform helpers that strip LC from a constant are applyFunctionChainToColumn (monotonic path, already fixed in #103211 with this exact pattern) and applyDeterministicDagToColumn (deterministic path, fixed here identically). Both applyDeterministicDagToColumn callers (equals and IN-set) benefit. After the fix the remaining convertToFullIfNeeded mentions in KeyCondition.cpp are only in explanatory comments.

Session id: cron:clickhouse-worker-slot-29:20260610-225430

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @CurtizJ — could you review this? It applies the same outer-only LowCardinality stripping you reviewed in #103211 (applyFunctionChainToColumn) to the sibling applyDeterministicDagToColumn path. A Variant constant with a LowCardinality member, compared against a non-monotonic deterministic key expression (e.g. a minmax skip index over sipHash64(col)), crashed because the constant column was fully materialized (inner LC stripped inside the Variant) while its type kept the inner LC, so the Variant->String cast wrapper typeid_cast'd a ColumnString to ColumnLowCardinality.

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

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [67f14fe]

Summary: ❌

job_name test_name status info comment
Stress test (arm_release) FAIL
Hung check failed, possible deadlock found FAIL cidb IGNORED

AI Review

Summary

This PR fixes a KeyCondition column/type normalization mismatch for constants and IN set elements whose Variant type contains nested LowCardinality, by making applyDeterministicDagToColumn strip only outer wrappers like the existing monotonic-function path. I did not find a code-level correctness issue that needs an inline comment.

PR Metadata
  • 💡 The Bug Fix category is appropriate, and the changelog entry is specific. Consider replacing "server crash" with "exception" for the LOGICAL_ERROR wording:
    Fix a LOGICAL_ERROR exception (Bad cast from type DB::ColumnString to DB::ColumnLowCardinality) when a Variant constant containing a LowCardinality member is compared to a key column whose key expression is a non-monotonic deterministic function (for example a minmax skip index over sipHash64(col)).
Missing context / blind spots
  • ⚠️ Full PR CI was still in progress at review time: Style check had passed and the Praktika report showed no failed tests, but Fast test, Bugfix validation (functional tests), Build (arm_tidy), and Code Review were still running. Completed CI would close this gap.
  • ⚠️ I could not run the new stateless test locally because this checkout has no local build artifacts.
Final Verdict

Status: ✅ Approve

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [67f14fe]

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

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.20% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 14/14 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@nihalzp

nihalzp commented Jun 11, 2026

Copy link
Copy Markdown
Member

Why not do it the other way around by striping LowCardinality from Variants for types?

@nihalzp nihalzp self-assigned this Jun 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Good question. I went this way on purpose, because stripping LowCardinality from Variant members on the type side is not generally sound and it also contradicts an existing decision in the codebase.

  1. Member squashing. DataTypeVariant's constructor de-duplicates members by name (the name_to_type map in DataTypeVariant.cpp). If we strip inner LC from the type, Variant(String, LowCardinality(String)) collapses to Variant(String): a different type with one member and different discriminators. The column still physically holds both variant sub-columns, so we would turn a 2-member column / 2-member type into a 2-member column / 1-member type, a worse mismatch than the one we are fixing. The second test case (Variant(String, LowCardinality(String))) hits exactly this.

  2. It is the opposite of the established direction. ColumnVariant::convertToFullIfNeeded() was overridden to a no-op in 3d3aad0 precisely so Variant columns do not strip their inner LC, with the comment "cannot update the corresponding DataTypeVariant, creating column/type position mismatches". The chosen invariant is to keep inner LC on both the column and the type and leave them symmetric, not to strip it on both. Stripping the type would also require rewriting the column's discriminators to drop or merge sub-columns, which is what that override exists to avoid.

  3. recursiveRemoveLowCardinality deliberately has no Variant branch (it handles Nullable/Array/Tuple/Map only). Adding one would break the same Variant(String, LowCardinality(String)) invariant.

So the fix keeps column and type symmetric by preserving inner LC on both. The actual bug was that a ColumnConst(ColumnVariant) bypasses the ColumnVariant override (the default IColumn::convertToFullIfNeeded unwraps the Const and then recurses into the raw sub-columns), so I do explicit outer-only stripping that never recurses. This mirrors the applyFunctionChainToColumn fix in #103211.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI status for 67f14fe: all required jobs green and the AI review approved. The single red check, Stress test (arm_release) -> "Hung check failed, possible deadlock found", is a known widespread flaky: 798 hits across 162 distinct PRs and 587 master runs in the last 30 days. It is unrelated to this change (a 17-line outer-only LowCardinality-stripping fix in KeyCondition cannot cause a stress-test deadlock).

@nihalzp
nihalzp added this pull request to the merge queue Jun 11, 2026
Merged via the queue into ClickHouse:master with commit abf970f Jun 11, 2026
164 of 167 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 11, 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.

4 participants