Repository navigation
Fix Bad cast in StatisticsPartPruner with LowCardinality column - #106793
hanfei1991 merged 8 commits into
Conversation
The AST fuzzer found a server crash with stack:
applyFunctionForField (KeyCondition.cpp:1367)
applyMonotonicFunctionsChainToRange (KeyCondition.cpp:4284)
KeyCondition::checkInHyperrectangle (KeyCondition.cpp:4723)
StatisticsPartPruner::checkPartCanMatch (StatisticsPartPruner.cpp:160)
MergeTreeDataSelectExecutor::filterPartsByStatistics (line 783)
Reproducer (also added as a stateless regression test):
SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE t (id Nullable(UInt32), b LowCardinality(Bool) STATISTICS(minmax))
ENGINE = MergeTree ORDER BY id
SETTINGS index_granularity = 8, allow_nullable_key = 1;
INSERT INTO t SELECT number, multiIf(number < 8, true, number < 16, false, NULL)
FROM numbers(24);
OPTIMIZE TABLE t FINAL;
SELECT count() FROM t WHERE b < toLowCardinality(toNullable(7));
The query crashes the server in a debug build with:
Logical error: Bad cast from type DB::ColumnLowCardinality
to DB::ColumnVector<char8_t>
Root cause:
`KeyCondition::extractAtomFromTree` constructs `monotonic_functions_chain`
against an `LowCardinality`-stripped key expression type (line 3524 calls
`recursiveRemoveLowCardinality(key_expr_type)` before constructing the chain
of casts via `createInternalCast`). At read time, however,
`StatisticsPartPruner::checkPartCanMatch` passes the original column type
(which can still be `LowCardinality(...)`) into
`KeyCondition::checkInHyperrectangle`. When the chain is non-empty,
`checkInHyperrectangle` forwards `data_types[key_column]` to
`applyMonotonicFunctionsChainToRange`, which calls `applyFunctionForField`
with that runtime type. The latter builds
`arg_type->createColumnConst(1, value)` over the LC type, producing a
`ColumnConst` wrapping a `ColumnLowCardinality`. The cast wrapper was prepared
against the LC-stripped type, so its outer `prepareUnpackDictionaries`
LowCardinality unwrap closure was elided (line 2291 returns the inner wrapper
directly when neither side is `LowCardinality`). The inner cast wrapper is
`createUInt8ToBoolWrapper`, which calls
`checkAndGetColumn<ColumnUInt8>(*arguments[0].column)` on the LC column and
throws `Bad cast`.
Fix:
Strip `LowCardinality` from the runtime data type when forwarding it to
`applyMonotonicFunctionsChainToRange`, matching the convention the chain was
built with. The same `recursiveRemoveLowCardinality` is already used at
KeyCondition.cpp:2239 for the symmetric set-index path.
CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106430&sha=0a1f6f4e08a576d96bfcef11818b9d1ce2b7ad23&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
PR: ClickHouse#106430
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260608-231400 |
|
cc @CurtizJ @hanfei1991: could you review this? It fixes a |
|
Workflow [PR], commit [5375986] Summary: ❌
AI ReviewSummaryThis PR fixes a Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Minimum required actions: fix the two remaining chain application paths so stored monotonic chains are always executed with columns/types matching the invariant they were built with, then keep the focused |
clickhouse-gh[bot] flagged that the previous result-only assertion does
not prove the fixed code path runs in release builds:
filterPartsByStatistics catches the exception thrown by
StatisticsPartPruner::checkPartCanMatch and keeps the part, so a
still-buggy pruner returns the same count. The test "passes" without
ever exercising the fix.
Replaced the single result assertion with two EXPLAIN indexes = 1
checks that assert the Statistics index entry appears and prunes the
expected number of parts:
- LowCardinality(Bool) + b = toLowCardinality(toNullable(true))
(the original AST fuzzer crash shape; createUInt8ToBoolWrapper)
- LowCardinality(UInt8) + v < toLowCardinality(toNullable(50))
(sibling shape; LowCardinality cannot be inside Nullable column)
Two non-overlapping single-row-value parts are now used so minmax
statistics can prune Part 2 down to 1/2 parts in both queries. The
Statistics index entry only appears in the EXPLAIN tree when pruning
succeeds (filterPartsByStatistics emits IndexStat only when
res_parts.size() < total_parts_before).
Verified locally on the same build:
with the fix: Statistics shows Parts: 1/2 in both EXPLAIN trees
without the fix: server crashes in debug with the original Logical
error 'Bad cast from type DB::ColumnLowCardinality
to DB::ColumnVector<char8_t>' on the Bool query
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed in 395aefd. The previous result-only assertion did not exercise the fix path in release builds because Verified locally on the same build:
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260609-061400 |
The CI variant `Stateless tests (amd_llvm_coverage, old analyzer, s3 storage,
DatabaseReplicated, WasmEdge, parallel)` runs with `--enable_analyzer 0`. The
old analyzer pipeline produces a different `EXPLAIN` wrapping than the new one:
new: `Expression ((Project names + Projection))`
` Filter ((WHERE + Change column names to column identifiers))`
old: `Expression ((Projection + Before ORDER BY))`
` Filter (WHERE)`
The Statistics-pruning evidence (`Parts: 1/2 Granules: 1/2`) is identical under
both pipelines (the LC-cast fix is column-type-related, not analyzer-related),
but the surrounding plan-node names differ and break the reference comparison.
Pin `enable_analyzer = 1` (new analyzer is the codebase default) plus the same
parallel-replicas / prewhere settings used by `03788_statistics_part_pruning.sql`,
so the EXPLAIN tree is stable across CI variants. `SET` overrides any CLI flag
the runner injects, including `--enable_analyzer 0`.
Verified locally:
- 30/30 with `--no-random-settings`
- With `--client-option enable_analyzer=0`: was deterministic FAIL before
this change (output mismatch matching the CI failure on `395aefda75ad`),
deterministic PASS after.
- Random-settings flakes seen locally are env-specific
(`zoneinfo/UTC` not present in local tzdata) and reproduce on sibling tests
like `03788_statistics_part_pruning.sql` too.
Also trimmed verbose preamble comments per maintainer guidance: keep
explanation in the commit / PR description, keep code comments concise.
CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106793&sha=395aefda75ad4a6f1e628dffffb3f682dda46d88&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DatabaseReplicated%2C%20WasmEdge%2C%20parallel%29
PR: ClickHouse#106793
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gateFollow-up to commit
Random-settings flakes observed locally ( Session id: cron:clickhouse-ci-task-worker:20260609-124500 |
The earlier fix stripped LowCardinality only at the chain application site (checkInHyperrectangle), which fixes the implicit-cast equals shape but introduces a mirror-image Bad cast for an explicit monotonic wrapper over a LowCardinality statistics column, e.g. CAST(b, 'Int32') >= 1 where b is LowCardinality(Bool) STATISTICS(minmax). For such a predicate the FunctionCast chain element is built inside isKeyPossiblyWrappedByMonotonicFunctions against the raw key column type taken from the sample block, which still carries LowCardinality. Stripping the type only at apply time then feeds that wrapper a dictionary-unpack column it cannot handle, hitting 'Bad cast from ColumnVector<char8_t> to ColumnLowCardinality' in prepareUnpackDictionaries. Strip LowCardinality from the key column type before building the chain so the chain is built and applied against the same LowCardinality-stripped invariant. This is reachable via statistics part pruning, whose key columns keep their raw LowCardinality type; normal MergeTree key columns are not LowCardinality, so the strip is a no-op there. Extends 04327_stid_1499_6033_statistics_lc_cast with an explicit-cast case that asserts the statistics pruner runs (EXPLAIN indexes = 1, Parts 1/2). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gateFollow-up commit
Session id: cron:clickhouse-worker-slot-30:20260610-230400 |
|
CI finished on `47609012e2c8`. All failures are infrastructure / known-chronic, none caused by this PR (which touches only `KeyCondition.cpp` + the regression test):
Both bot review threads are addressed (test-signal: EXPLAIN indexes=1 in 395aefd; source-correctness: symmetric LowCardinality strip at chain construction in 4760901). Ready for review. |
|
@groeneai, fix test |
|
Thanks @alexey-milovidov, on it. Scope note: I triaged it on #107297 and am implementing a test-side hardening fix: make the second replica provably unable to confirm quorum (stop replicated sends on the writer / detach the second replica) instead of relying on This StatisticsPartPruner PR is unaffected and stays as-is. |
|
Re 04337: it is already fixed upstream by #107760 (nickitat), approved by azat. It removes the |
| /// `LowCardinality` type here and its `FunctionCast` dictionary-unpack wrapper would hit a | ||
| /// `Bad cast` when fed the stripped column. Reachable via statistics part pruning, whose | ||
| /// key columns keep their raw `LowCardinality` type. | ||
| key_column_type = recursiveRemoveLowCardinality(key_column_type); |
There was a problem hiding this comment.
This establishes the stripped-type invariant for every stored monotonic chain, but the IN/has path still applies those chains with the raw runtime type. KeyCondition::checkInHyperrectangle calls element.set_index->checkInRange(hyperrectangle, data_types, single_point), and MergeTreeSetIndex::checkInRange forwards data_types[indexes_mapping[i].key_index] unchanged into applyMonotonicFunctionsChainToRange.
That leaves the same LowCardinality mismatch for predicates that use a set index. For example, with the test table's b LowCardinality(Bool) STATISTICS(minmax), CAST(b, 'Int32') IN (1) builds the set-index chain here against stripped Bool, but StatisticsPartPruner::checkPartCanMatch later passes LowCardinality(Bool) as the runtime type; applyFunctionForField then creates a LowCardinality const for a FunctionCast prepared for Bool, so this can still throw Bad cast instead of pruning.
Please apply the same strip when MergeTreeSetIndex::checkInRange applies indexes_mapping[i].functions (or pass an already-stripped type for those chains), and add a regression assertion such as EXPLAIN indexes = 1 ... WHERE CAST(b, 'Int32') IN (1) showing the Statistics index prunes to Parts: 1/2.
There was a problem hiding this comment.
Investigated this empirically. The data-flow observation is correct: MergeTreeSetIndex::checkInRange forwards the column's raw LowCardinality runtime type into applyMonotonicFunctionsChainToRange. But the predicted Bad cast does not occur on the set-index path.
Verified by instrumenting checkInRange: for CAST(b,'Int32') IN (1) over the test table's b LowCardinality(Bool) STATISTICS(minmax) it is invoked with chain_size=1 and runtime_type=LowCardinality(Bool) (the exact condition you describe), and it prunes (Statistics 1/2) without throwing. Same for CAST(v,...) IN (...), toInt32(v) IN (...), multi-element sets, subquery sets, NOT IN, and the old analyzer.
The asymmetry is why the two callers behave differently. The crash needs a FunctionCast built to expect a LowCardinality input but fed a stripped column:
- Scalar path (
checkInHyperrectangle) strips the type at apply time, so a chain built forLowCardinalityis applied to a stripped column ->prepareUnpackDictionariesdoestypeid_cast<ColumnLowCardinality&>on a plain column ->Bad cast. This is the original bug, and the construction-site strip fixes it. - Set path:
applyFunctionForFieldbuilds the const column from the same runtime type it applies (arg_type->createColumnConst(...)), so theFunctionCastalways receives theLowCardinalitycolumn it expects. No mismatch in either configuration.
Controlled experiment: with the construction-site strip disabled, CAST(b,'Int32') >= 1 (scalar) crashes with Bad cast, while CAST(b,'Int32') IN (1) (set-index) stays safe. So the set-index path has no reproducing crash, and per our guidance I am not adding a speculative strip there.
I did add the regression assertion you requested: EXPLAIN indexes = 1 ... WHERE CAST(b, 'Int32') IN (1) showing Statistics ... Parts: 1/2, in commit 8f8fcb3. It guards against a future regression that would strip the runtime type on only one of the two callers.
Session id: cron:clickhouse-worker-slot-0:20260619-161300
A review comment asked whether the set-index (IN/has) path can still throw "Bad cast" for an explicit monotonic wrapper over a LowCardinality statistics column, since MergeTreeSetIndex::checkInRange forwards the column's raw LowCardinality runtime type into applyMonotonicFunctionsChainToRange. Investigated empirically: instrumented MergeTreeSetIndex::checkInRange to log the chain size and runtime type, and confirmed it is invoked with a non-empty CAST chain and a LowCardinality(Bool)/(UInt8) runtime type. The set-index path does not crash and prunes correctly. A controlled experiment disabling the construction-site strip (recursiveRemoveLowCardinality in isKeyPossiblyWrappedByMonotonicFunctions) reproduced the scalar-path crash (CAST(b,'Int32') >= 1) while the set-index path (CAST(b,'Int32') IN (1)) stayed safe in both configurations. Reason: the crash requires a FunctionCast built to expect a LowCardinality input but fed a stripped column. The scalar caller strips the type at apply time, creating that mismatch. The set caller (applyFunctionForField) builds its const column from the same runtime type it applies, so the FunctionCast wrapper always receives the LowCardinality column it expects. There is no bug to fix in the set-index path, so no source change is made. Add the requested EXPLAIN indexes = 1 ... WHERE CAST(b, 'Int32') IN (1) assertion to lock in that the set-index path prunes (Statistics 1/2) instead of throwing, guarding against a future regression that strips the runtime type only on one of the two callers. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (commit 8f8fcb3)This push is test-only (adds an IN/set-index regression case to
Session id: cron:clickhouse-worker-slot-0:20260619-161300 |
| /// `LowCardinality` type here and its `FunctionCast` dictionary-unpack wrapper would hit a | ||
| /// `Bad cast` when fed the stripped column. Reachable via statistics part pruning, whose | ||
| /// key columns keep their raw `LowCardinality` type. | ||
| key_column_type = recursiveRemoveLowCardinality(key_column_type); |
There was a problem hiding this comment.
This stripped-type invariant is now applied to every KeyCondition, but primary-key pruning still applies monotonic chains to column-backed FieldRef values. When markRangesFromPKRange sees a monotonic chain it stores references to index_columns, and applyFunction then executes the stored function on (*columns)[field.column_idx] instead of on a column rebuilt from current_type. For a LowCardinality primary key those index columns are created from primary_key.data_types, so they remain ColumnLowCardinality.
That makes this a regression outside the statistics path: k LowCardinality(UInt8) ORDER BY k with a predicate such as CAST(k, 'Bool') = true now builds the FunctionCast chain against stripped UInt8, but primary-key range pruning later executes that cast on the cached ColumnLowCardinality index column. The cast wrapper no longer has the prepareUnpackDictionaries unwrap that it had when the chain was built from LowCardinality(UInt8), so it reaches createUInt8ToBoolWrapper with the wrong column kind and throws Bad cast.
Please keep construction and application aligned for column-backed ranges as well: either limit this strip to the statistics/explicit-Field path, or make the non-explicit applyFunction path materialize/use a column whose type matches the stripped current_type. Please also add a focused regression with force_primary_key = 1 over a LowCardinality primary key and an explicit cast chain that actually executes, e.g. CAST(k, 'Bool').
There was a problem hiding this comment.
Investigated empirically with a controlled toggle experiment (debug build).
The data-flow premise is correct: for a LowCardinality primary key, markRangesFromPKRange builds index_columns from primary_key.data_types[i]->createColumn() (so they stay ColumnLowCardinality), key_types stays the raw LC type, and for a column-backed FieldRef applyFunction runs the stored chain via func->execute((*columns)[field.column_idx], ...) on that raw LC column.
The predicted crash does not occur, in either configuration:
- I toggled the construction-site strip OFF (commented out
recursiveRemoveLowCardinality(key_column_type)), rebuilt, and compared against the strip ON build. PK range pruning overk LowCardinality(UInt8)andk LowCardinality(Float64),force_primary_key = 1, two non-overlapping parts, single- and multi-granule, gives identical results in both builds:CAST(k,'Float64'),CAST(k,'Float32'),CAST(k,'Int16'),CAST(k,'UInt16'),toFloat64(k),toInt32(k), andCAST(k,'Bool')overLowCardinality(Float64)all return the correct count with noBad cast.
Reason: the cast chain element is a FunctionCast, and IFunction's default LowCardinality adapter unwraps the dictionary at execute time regardless of the type the function was built against. So feeding the raw ColumnLowCardinality index column to a FunctionCast built against the stripped type goes through that adapter, not createUInt8ToBoolWrapper on a mismatched column kind.
The specific CAST(k, 'Bool') = true example also never reaches applyFunction for an integer key: functionIsIntegerCastPreservingFieldRepresentation short-circuits UInt8 -> Bool (Bool is UInt8, same width) via skip_apply, so no chain is applied. Its result is independent of the strip and of LowCardinality (a non-LC UInt8 PK behaves identically), so it is not a regression from this change.
I could not reproduce a regression to fix, so per the no-speculative-changes practice I made no source change. I added the regression guard you asked for as protection against a future one-sided strip: 04327_stid_1499_6033_statistics_lc_cast now creates a LowCardinality(Float64) primary key and asserts force_primary_key = 1 queries with executing cast chains (CAST(k,'Bool'), CAST(k,'Int64'), toFloat32(k)) run and prune correctly. Float64 source forces real chain application (integer casts short-circuit). Pushed in 5375986; robust across randomized index_granularity / part-format settings.
…Cardinality test The construction-site LowCardinality strip in KeyCondition establishes a stripped-type invariant for every stored monotonic chain. Guard that the column-backed primary-key range pruning path (markRangesFromPKRange -> applyFunction on the cached index column) still executes an LC-key cast chain without throwing, under force_primary_key. A Float64 source forces real chain application; integer->integer casts short-circuit before applyFunction. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (commit 5375986)
Session id: cron:clickhouse-worker-slot-1:20260619-211100 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 13/13 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code |
|
CI finished on
All build, functional, integration, AST-fuzzer and stateless jobs pass; Mergeable Check is green. Session id: cron:our-pr-ci-monitor:20260620-020000 |
a310713
|
Hi — this looks like a backport candidate for |
A query with a LowCardinality key column and an executing monotonic CAST chain (e.g. CAST(s, 'LowCardinality(String)') over a LowCardinality(Nullable(Int32)) primary key) aborted during primary-key range pruning with: Logical error: 'Bad cast from type DB::ColumnLowCardinality to DB::ColumnNullable' The monotonic-functions chain is built in isKeyPossiblyWrappedByMonotonicFunctions against an outer-LowCardinality-stripped initial key type, but each subsequent chain function is built against the previous function's result type. So after a step like CAST(s, 'LowCardinality(String)') the next function's declared argument type is itself LowCardinality(...). FunctionCast keeps LowCardinality dictionaries (useDefaultImplementationForLowCardinalityColumns = false) and typeid_casts its argument column to the declared shape. applyFunction (the range path used by KeyCondition::applyMonotonicFunctionsChainToRange) fed the raw cached index column to func->execute without matching that declared shape. For the first chain step the column is ColumnLowCardinality while the function expects a stripped source, so the wrapper assert_cast-ed ColumnLowCardinality to ColumnNullable and aborted. The constant path (applyFunctionChainToColumn) already coerces the column to each function's argument type; the range path did not. Coerce the cached column to the function's declared argument type in applyFunction, mirroring applyFunctionChainToColumn: re-wrap a full column into LowCardinality when the function expects LowCardinality, and strip the outer LowCardinality when it does not. This handles both the single CAST shape and a nested chain such as CAST(CAST(s, 'LowCardinality(String)'), 'String') < '5', where the second cast is built for a LowCardinality source and a blanket strip would instead hit the mirror Bad cast ColumnString to ColumnLowCardinality. The coercion is a no-op for normal non-LowCardinality key columns. This covers both the regular and the lightweight (sparse) primary-key analysis paths, since both reach applyFunction. PR ClickHouse#106793 fixed the same Bad-cast class for the non-sparse checkInHyperrectangle monotonicity argument but did not address the column fed to func->execute, so this shape still crashed on both paths. Found by the server-side AST fuzzer. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Related: #106430
The AST fuzzer crashed the server with a
Logical error: Bad cast from type DB::ColumnLowCardinality to DB::ColumnVector<char8_t>while pruning parts by statistics on aLowCardinality(Bool)column with aLowCardinality(Nullable(...))constant in the predicate.KeyCondition::extractAtomFromTreebuilds themonotonic_functions_chainagainst anLowCardinality-stripped key type, butStatisticsPartPruner::checkPartCanMatchpasses the original column type back intoKeyCondition::checkInHyperrectangleat read time. When the chain is non-empty,applyFunctionForFieldthen constructs anLowCardinalityconstant column for a cast wrapper that was prepared without the outerprepareUnpackDictionariesLC unwrap closure, socreateUInt8ToBoolWrapper'scheckAndGetColumn<ColumnUInt8>throws.The fix strips
LowCardinalityfrom the runtime data type when forwarding toapplyMonotonicFunctionsChainToRange, matching the convention the chain was built with. The samerecursiveRemoveLowCardinalityis already used at the symmetric set-index path (KeyCondition.cpp:2239).CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106430&sha=0a1f6f4e08a576d96bfcef11818b9d1ce2b7ad23&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
Bad castexception while pruning parts byMinMaxstatistics when a key column isLowCardinalityand the predicate constant isLowCardinality(Nullable(...)).Version info
26.6.1.1118