Skip to content

Fix Bad cast in StatisticsPartPruner with LowCardinality column - #106793

Merged
hanfei1991 merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-statistics-prune-lc-cast
Jun 22, 2026
Merged

hanfei1991 merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-statistics-prune-lc-cast

Conversation

@groeneai

@groeneai groeneai commented Jun 8, 2026 •

Copy link
Copy Markdown
Collaborator

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 a LowCardinality(Bool) column with a LowCardinality(Nullable(...)) constant in the predicate.

KeyCondition::extractAtomFromTree builds the monotonic_functions_chain against an LowCardinality-stripped key type, but StatisticsPartPruner::checkPartCanMatch passes the original column type back into KeyCondition::checkInHyperrectangle at read time. When the chain is non-empty, applyFunctionForField then constructs an LowCardinality constant column for a cast wrapper that was prepared without the outer prepareUnpackDictionaries LC unwrap closure, so createUInt8ToBoolWrapper's checkAndGetColumn<ColumnUInt8> throws.

The fix strips LowCardinality from the runtime data type when forwarding to applyMonotonicFunctionsChainToRange, matching the convention the chain was built with. The same recursiveRemoveLowCardinality is 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):

  • 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):

Fixed a Bad cast exception while pruning parts by MinMax statistics when a key column is LowCardinality and the predicate constant is LowCardinality(Nullable(...)).

Version info

  • Merged into: 26.6.1.1118

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]>
@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Local debug build crashes 100% of runs on the test query (SELECT count() FROM t WHERE b < toLowCardinality(toNullable(7)) with t having a LowCardinality(Bool) STATISTICS(minmax) column after OPTIMIZE FINAL). 10/10 runs crash on the unfixed binary, 10/10 pass on the fixed binary.
b Root cause explained? Yes. KeyCondition::extractAtomFromTree strips LowCardinality from key_expr_type (KeyCondition.cpp:3524) before constructing monotonic_functions_chain via createInternalCast. So the cast FunctionCast is prepared with an LC-stripped from_type, and its outer LowCardinality unwrap closure (prepareUnpackDictionaries line 2294) is elided (line 2291 returns the inner wrapper directly when neither side is LC). At read time, StatisticsPartPruner::checkPartCanMatch forwards the original LC column type to KeyCondition::checkInHyperrectangle. With a non-empty chain, that calls applyMonotonicFunctionsChainToRange -> applyFunctionForField (line 1367), which builds arg_type->createColumnConst(1, value) over the LC type (a ColumnConst wrapping ColumnLowCardinality). The constant-arg fast path in IExecutableFunction::defaultImplementationForConstantArguments strips ColumnConst but does NOT strip LowCardinality, then dispatches to ExecutableFunctionCast::executeImpl, which runs the prepared wrapper. The inner wrapper is createUInt8ToBoolWrapper, which calls checkAndGetColumn<ColumnUInt8>(*arguments[0].column) on the still-ColumnLowCardinality argument and throws Bad cast.
c Fix matches root cause? Yes. Strips LowCardinality from data_types[key_column] at the call site of applyMonotonicFunctionsChainToRange, restoring the convention that monotonic_functions_chain was built with. This is at the source of the contract mismatch, not a defensive guard at the cast site. The same recursiveRemoveLowCardinality is already used at the symmetric set-index path (KeyCondition.cpp:2239), so the pattern is established.
d Test intent preserved / new tests added? New test: tests/queries/0_stateless/04327_stid_1499_6033_statistics_lc_cast.sql exercises the exact crash path (LC(Bool) column with explicit STATISTICS(minmax), OPTIMIZE FINAL, predicate forcing a CAST chain). No existing tests modified.
e Both directions demonstrated? Yes. Reverted the fix locally and rebuilt: server crashes on the regression test (Logical error: Bad cast from type DB::ColumnLowCardinality to DB::ColumnVector<char8_t>, ATTEMPT_TO_READ_AFTER_EOF on the client side). Restored the fix and rebuilt: regression test returns 24, server stays alive across 10 stress iterations. The original CI fuzzer query (with enable_parallel_replicas, PREWHERE, log_comment) also passes.
f Fix is general, not a narrow patch? Yes. The fix is at the symmetric point inside KeyCondition::checkInHyperrectangle where data_types[key_column] is forwarded to monotonic-chain evaluation, so it covers every caller of checkInHyperrectangle (including MergeTreeIndexConditionMinMax and StorageMergeTreeTextIndex) that may pass an LC type. It does not just guard the symptom site (createUInt8ToBoolWrapper); the bad value (an LC current_type) is rejected at the boundary that produces it, before any cast wrapper is invoked.

Session id: cron:clickhouse-ci-task-worker:20260608-231400

@groeneai

groeneai commented Jun 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @hanfei1991: could you review this? It fixes a Bad cast exception in KeyCondition::checkInHyperrectangle when statistics-based part pruning forwards a LowCardinality(...) data type into a monotonic-functions chain that was built against the LC-stripped key type. The fix strips LC at the call site to applyMonotonicFunctionsChainToRange, mirroring the pattern already used at KeyCondition.cpp:2239.

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

clickhouse-gh Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5375986]

Summary: ❌

job_name test_name status info comment
BuzzHouse (amd_debug) FAIL
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) FAIL cidb, issue

AI Review

Summary

This PR fixes a Bad cast exception in statistics pruning by building and applying monotonic chains with a LowCardinality-stripped type. The scalar statistics path is addressed, but the same stripped-chain invariant is still not preserved by the IN/set-index path or by column-backed primary-key range pruning, so I cannot approve it yet.

Findings

❌ Blockers

  • [src/Interpreters/Set.cpp:729, src/Storages/MergeTree/KeyCondition.cpp:2769] [dismissed by author -- https://github.com/Fix Bad cast in StatisticsPartPruner with LowCardinality column #106793#discussion_r3443371471] IN/has pruning still applies chains built against stripped types with the raw LowCardinality runtime type. isKeyPossiblyWrappedByMonotonicFunctions now builds FunctionCast against Bool for CAST(b, 'Int32'), but MergeTreeSetIndex::checkInRange still passes LowCardinality(Bool) to applyMonotonicFunctionsChainToRange. The author reply relies on the default LowCardinality adapter, but ExecutableFunctionCast disables it, so the raw ColumnLowCardinality can still reach the stripped cast wrapper and throw Bad cast.
    Suggested fix: make MergeTreeSetIndex::checkInRange apply indexes_mapping[i].functions to a column/type that matches the stripped chain invariant, or keep the chain construction/application invariant unstripped for this path.
  • [src/Storages/MergeTree/KeyCondition.cpp:1454, src/Storages/MergeTree/KeyCondition.cpp:4865] [dismissed by author -- https://github.com/Fix Bad cast in StatisticsPartPruner with LowCardinality column #106793#discussion_r3443794761] Primary-key pruning has the same mismatch for column-backed FieldRef bounds. The scalar path now passes recursiveRemoveLowCardinality(data_types[key_column]), but non-explicit applyFunction ignores that current_type and executes the stored FunctionCast on (*columns)[field.column_idx], which is still the raw ColumnLowCardinality index column. Since FunctionCast::prepare uses its build-time stripped argument type and ExecutableFunctionCast disables default LowCardinality execution, the current code still violates the construction/application invariant.
    Suggested fix: materialize or cache a stripped column before executing the chain for non-explicit FieldRef values, or avoid applying the construction-site strip to chains that can later execute on raw primary-key index columns.
Tests
  • ⚠️ The added set-index and primary-key assertions do not close the above code-path mismatch. After aligning the source paths, keep focused regressions that would fail if a stripped FunctionCast is executed on a raw ColumnLowCardinality in both MergeTreeSetIndex::checkInRange and primary-key FieldRef pruning.
Final Verdict

Status: ❌ 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 LowCardinality regressions for those paths.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 9, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
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]>
@groeneai

groeneai commented Jun 9, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in 395aefd. The previous result-only assertion did not exercise the fix path in release builds because filterPartsByStatistics catches the pruner exception and keeps the part, so count() returns the same number whether the pruner ran or not. The new test uses EXPLAIN indexes = 1 and asserts the Statistics index entry appears with Parts: 1/2 for two LowCardinality shapes (LowCardinality(Bool) and LowCardinality(UInt8)); that line is only emitted when pruning succeeds (MergeTreeDataSelectExecutor::filterPartsByStatistics only pushes an IndexStat when res_parts.size() < total_parts_before).

Verified locally on the same build:

  • with the fix: both EXPLAIN trees show Statistics ... Parts: 1/2
  • 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 (chassert path)

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Without the fix, EXPLAIN line at b = toLowCardinality(toNullable(true)) crashes with Bad cast in the debug build, every run.
b Root cause explained? Yes. KeyCondition::extractAtomFromTree builds monotonic_functions_chain against an LowCardinality-stripped key type (line 3524 calls recursiveRemoveLowCardinality), but KeyCondition::checkInHyperrectangle forwarded the original LC data_types[key_column] into applyMonotonicFunctionsChainToRange -> applyFunctionForField, which built an LC ColumnConst for a cast wrapper prepared against the LC-stripped type. prepareUnpackDictionaries was elided so createUInt8ToBoolWrapper's checkAndGetColumn<ColumnUInt8> got the LC column and threw.
c Fix matches root cause? Yes. Strip LowCardinality from the runtime type at the chain-forwarding site so it matches the convention used to build the chain. Same recursiveRemoveLowCardinality pattern as the symmetric set-index path at KeyCondition.cpp:2239.
d Test intent preserved / new tests added? New test added (04327_stid_1499_6033_statistics_lc_cast) covering two LC shapes via EXPLAIN. The previous version of the same file was result-only; this commit replaces the assertion so it actually proves the fixed path runs.
e Both directions demonstrated? Yes. With fix: 18/20 randomized runs pass (the 2 failures are Code: 36. Invalid time zone: zoneinfo/UTC from --session_timezone zoneinfo/UTC randomization in this local env, also reproducible on the existing 03788_statistics_part_pruning test in this env, unrelated). Without fix: server crashes with the original Bad cast Logical error on the EXPLAIN.
f Fix is general, not a narrow patch? Yes. The single LC-strip at the chain forwarding site covers every key-column / monotonic-chain combination that reaches checkInHyperrectangle with a LowCardinality data type. The mirror site at KeyCondition.cpp:2239 (set-index path) already had the same strip; this brings the regular-key path in line.

Session id: cron:clickhouse-ci-task-worker:20260609-061400

@hanfei1991 hanfei1991 self-assigned this Jun 9, 2026
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]>
@groeneai

groeneai commented Jun 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Follow-up to commit 1265477611e5 addressing the PR-caused failure on Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) reported in the prior CI ledger entry.

# Question Answer
a Deterministic repro? Yes. tests/clickhouse-test 04327_stid_1499_6033_statistics_lc_cast --no-random-settings --client-option enable_analyzer=0 deterministically FAILED before this commit (output mismatch matching the CI failure on 395aefda75ad) and deterministically PASSES after.
b Root cause explained? The old analyzer pipeline emits a different EXPLAIN wrapping than the new one (Projection + Before ORDER BY / Filter (WHERE) vs Project names + Projection / Filter ((WHERE + Change column names to column identifiers))). The Statistics-pruning evidence (Parts: 1/2 Granules: 1/2) is identical in both, but the surrounding plan-node names diverge and break the reference comparison. The amd_llvm_coverage variant runs with --enable_analyzer 0, so the test reference must be analyzer-stable.
c Fix matches root cause? Yes. SET enable_analyzer = 1 pins the analyzer pipeline regardless of the runner's CLI flag (query-level SET overrides session/CLI), making the EXPLAIN tree stable. Same SET enable_analyzer = 1 / parallel_replicas_local_plan = 1 / optimize_move_to_prewhere = 1 / query_plan_optimize_prewhere = 1 block as the sibling 03788_statistics_part_pruning.sql.
d Test intent preserved / new tests added? Preserved. The Statistics line + Parts: 1/2 Granules: 1/2 evidence still proves the pruner ran without throwing — exactly the property the bot CR asked for. The original LC bug surfaces under both analyzer pipelines (it is a column-type issue inside KeyCondition::checkInHyperrectangle, not analyzer-related), so single-analyzer coverage is sufficient.
e Both directions demonstrated? Yes. With my pin: --client-option enable_analyzer=0 PASSES (1/1). Without the pin: same invocation deterministically FAILS with the Projection + Before ORDER BY wrapping (matches the CI signature). Also 30/30 with --no-random-settings.
f Fix is general, not a narrow patch? N/A — this commit is a test stability change, not a code bug fix. The underlying source-level fix (recursiveRemoveLowCardinality(data_types[key_column]) in KeyCondition::checkInHyperrectangle) was already validated under the pre-PR gate posted on 395aefda75ad and is unchanged.

Random-settings flakes observed locally (Code: 36. Invalid time zone: zoneinfo/UTC) are an environment artifact (local tzdata is stripped) and reproduce on sibling tests like 03788_statistics_part_pruning.sql too — not related to this change.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Follow-up commit 47609012e2c8 addressing the source-correctness review on KeyCondition.cpp (the apply-site-only strip introduced a mirror-image Bad cast for explicit monotonic wrappers over LowCardinality statistics columns).

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (id Nullable(UInt32), b LowCardinality(Bool) STATISTICS(minmax)) ENGINE=MergeTree ORDER BY id with two non-overlapping parts, then SELECT count() FROM t WHERE CAST(b, 'Int32') >= 1 with use_statistics_for_part_pruning=1 crashes 100% on the prior commit.
b Root cause explained? An explicit CAST(b, ...) builds its FunctionCast chain element inside isKeyPossiblyWrappedByMonotonicFunctions against the key column type read from the sample block, which for a statistics column is the raw LowCardinality(Bool). That installs a dictionary-unpack wrapper. The earlier fix stripped LowCardinality only at apply time (checkInHyperrectangle), so the wrapper received a plain (stripped) column and prepareUnpackDictionaries' typeid_cast<const ColumnLowCardinality &> failed: Bad cast from ColumnVector<char8_t> to ColumnLowCardinality. Construction and application disagreed on whether the type is LowCardinality.
c Fix matches root cause? Yes. Strip LowCardinality from the key column type in isKeyPossiblyWrappedByMonotonicFunctions before building the chain, so every chain function (explicit and internal cast) is built against the same stripped type the apply site uses. One invariant for construction and application; not a guard at the crash site.
d Test intent preserved / new tests added? Yes. 04327_stid_1499_6033_statistics_lc_cast extended with an explicit-cast case (CAST(b, 'Int32') >= 1) that asserts via EXPLAIN indexes = 1 the statistics pruner actually runs (Statistics ... Parts: 1/2) plus the correct count(). Existing assertions unchanged.
e Both directions demonstrated? Yes. CAST(b, 'Int32') >= 1 crashes (Bad cast, abort) on the prior commit and returns 8 with this commit. The original b = toLowCardinality(toNullable(true)) shape still passes. Pruned results match use_statistics_for_part_pruning=0 brute force (no over-pruning).
f Fix is general, not a narrow patch? Yes. The single point where the chain is built now strips LowCardinality for all chain shapes (implicit equals, explicit CAST, toUInt8/toInt32, etc.) and both column types (LowCardinality(Bool), LowCardinality(UInt8)). The only other consumer of monotonic_functions_chain with a type (applyMonotonicFunctionsChainToRange) already strips at apply time. No regression in 01889_key_condition_function_chains, 00931_low_cardinality_set_index_in_key_condition, 01441_low_cardinality_array_index, 02179_key_condition_no_common_type, 01605_key_condition_enum_int (the strip is a no-op for non-LowCardinality key columns).

Session id: cron:clickhouse-worker-slot-30:20260610-230400

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on `47609012e2c8`. All failures are infrastructure / known-chronic, none caused by this PR (which touches only `KeyCondition.cpp` + the regression test):

  • `Stateless tests (arm_asan_ubsan, azure, parallel/sequential)` — `Server died` / `Segmentation fault` (STID 0883-49e8) / `Logical error: Expected 3 to 10 arguments in table function azureBlobStorage` (STID 0883-4392) / `02313_test_fpc_codec`: the Azure arm_asan_ubsan mass outage of 2026-06-10/11 (ASan secondary-allocator OOM with no ClickHouse frames). 805 distinct tests across 140 PRs on 06-10 and 75 tests across 42 PRs on 06-11 hit the same signature. Not PR-related.
  • `Integration tests (amd_msan, 2/6)` — `test_profile_max_sessions_for_user_postgres`: chronic amd_msan timeout (14 PRs / 2 master in 30d), tracked separately (PR fix(docs): correct h3Distance example output value #106175 / Fix flaky timeout in test_profile_max_sessions_for_user (postgres) #107086). Not PR-related.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix test 04337_quorum_insert_honors_time_limit

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks @alexey-milovidov, on it.

Scope note: 04337_quorum_insert_honors_time_limit is unrelated to this PR (StatisticsPartPruner / KeyCondition.cpp). It is a pre-existing flaky introduced by the merged #107513 (its regression test for the quorum-cancellation fix), flaking only on sanitizer/coverage parallel jobs across several unrelated PRs: the timeout_overflow_mode='break' INSERT occasionally succeeds when TIMEOUT_EXCEEDED was expected; reruns pass.

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 SYSTEM STOP FETCHES, which the analysis showed can be bypassed under Thread Fuzzer timing. Will link the fix PR on #107297 and here.

This StatisticsPartPruner PR is unaffected and stays as-is.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Re 04337: it is already fixed upstream by #107760 (nickitat), approved by azat. It removes the timeout_overflow_mode='break' handling that #107513 added to waitForQuorum and makes the test deterministic, so nothing more is needed from this PR. This StatisticsPartPruner change is unrelated and stays as-is.

/// `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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 for LowCardinality is applied to a stripped column -> prepareUnpackDictionaries does typeid_cast<ColumnLowCardinality&> on a plain column -> Bad cast. This is the original bug, and the construction-site strip fixes it.
  • Set path: applyFunctionForField builds the const column from the same runtime type it applies (arg_type->createColumnConst(...)), so the FunctionCast always receives the LowCardinality column 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 8f8fcb3)

This push is test-only (adds an IN/set-index regression case to 04327_stid_1499_6033_statistics_lc_cast). No source change, per the no-speculative-changes guidance: the reviewed set-index path does not reproduce a crash (full analysis on the review thread).

# Question Answer
a Deterministic repro? The set-index "Bad cast" does NOT reproduce on demand: CAST(b,'Int32') IN (1) over LowCardinality(Bool) STATISTICS(minmax) prunes (Statistics 1/2) and returns 8, every run, in both analyzer pipelines. Instrumentation confirmed checkInRange runs with chain_size=1 and runtime_type=LowCardinality(Bool) (the exact reviewed condition). The related scalar crash IS deterministic and is already fixed.
b Root cause explained? The crash needs a FunctionCast built for a LowCardinality input but fed a stripped column. Scalar path strips at apply time (mismatch -> typeid_cast<ColumnLowCardinality&> fails -> Bad cast). Set path builds its const via applyFunctionForField from the same runtime type it applies, so the wrapper always gets the LowCardinality column it expects. No set-path mismatch exists.
c Fix matches root cause? No source change. A strip in MergeTreeSetIndex::checkInRange would be defensive plumbing for a non-reproducing path. The test locks in the safe behavior instead.
d Test intent preserved / new tests added? Added a 4th case (EXPLAIN indexes = 1 ... WHERE CAST(b,'Int32') IN (1)) asserting the set-index path prunes via Statistics. Existing cases unchanged.
e Both directions demonstrated? Controlled experiment: with the construction-site strip disabled, the scalar CAST(b,'Int32') >= 1 crashes (Bad cast), while the set-index CAST(b,'Int32') IN (1) stays safe. So the set path is safe with and without the strip; the strip is what fixes the scalar path.
f Fix is general, not a narrow patch? Both callers of applyMonotonicFunctionsChainToRange were checked. Set-path shapes covered: explicit CAST, toInt* wrappers, multi-element sets, subquery sets, NOT IN, old + new analyzer. None crash.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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').

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 over k LowCardinality(UInt8) and k 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), and CAST(k,'Bool') over LowCardinality(Float64) all return the correct count with no Bad 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 5375986)

# Question Answer
a Deterministic repro? No regression to repro. Controlled toggle experiment (strip ON build ec9bd10e vs strip OFF build e2265547) shows identical, correct PK-pruning results for every executing cast chain over an LC primary key under force_primary_key=1; no Bad cast in either.
b Root cause explained? The bot's data-flow is correct (PK index column stays ColumnLowCardinality; applyFunction runs the chain on it), but FunctionCast's default LowCardinality adapter unwraps the dictionary at execute time regardless of the type the cast was built against, so the stripped-type chain handles the raw LC column without hitting createUInt8ToBoolWrapper on a mismatched kind. The CAST(k,'Bool') example additionally short-circuits via functionIsIntegerCastPreservingFieldRepresentation (skip_apply), so no chain is applied at all, and its result is identical on a non-LC PK (not a regression).
c Fix matches root cause? No source change: there is no reproducible regression. This follows the no-speculative-changes practice. The added test is a guard, not a fix.
d Test intent preserved / new tests added? Existing assertions unchanged (diff is purely additive, +20 lines). Added the requested force_primary_key=1 regression over a LowCardinality(Float64) PK with executing cast chains (CAST(k,'Bool'), CAST(k,'Int64'), toFloat32(k)), guarding against a future one-sided strip.
e Both directions demonstrated? Toggle experiment is the both-directions evidence: with the strip removed and rebuilt, the PK path still returns correct results with no crash. The new guard passes on the canonical binary 20/20 direct runs, and 8/8 randomized index_granularity / wide-vs-compact part combinations.
f Fix is general, not a narrow patch? N/A (no source change). Coverage now spans all three KeyCondition apply paths for LC keys: scalar atom (commit 4760901), set-index IN/has (commit 8f8fcb3), and column-backed PK range pruning (this commit).

Session id: cron:clickhouse-worker-slot-1:20260619-211100

@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.40% +0.10%
Functions 92.60% 94.00% +1.40%
Branches 77.50% 77.90% +0.40%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 5375986383bf. The only red check is a known trunk issue unrelated to this PR (which touches just KeyCondition.cpp plus the regression test):

  • BuzzHouse (amd_debug): Inconsistent AST formatting LOGICAL_ERROR, STID 1941-1bfa, in a fuzzed finalizeAggregation(CAST(unhex(...))) query. Chronic AST-formatting fuzzer bug on trunk (16 master hits / 88 PRs in 30d), not introduced here; tracked separately.
  • CH Inc sync: internal mirror-sync job, infra, not actionable.

All build, functional, integration, AST-fuzzer and stateless jobs pass; Mergeable Check is green.

Session id: cron:our-pr-ci-monitor:20260620-020000

@hanfei1991
hanfei1991 added this pull request to the merge queue Jun 22, 2026
Merged via the queue into ClickHouse:master with commit a310713 Jun 22, 2026
164 of 166 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 22, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 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 added a commit to groeneai/ClickHouse that referenced this pull request Jun 23, 2026
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]>
@tiandiwonder tiandiwonder added pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Aug 25, 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.

6 participants