Skip to content

Fix Bad cast in KeyCondition for nested CAST that re-introduces LowCardinality - #111050

Merged
fm4v merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-lc-bidirectional-cast
Aug 5, 2026
Merged

fm4v merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-lc-bidirectional-cast

Conversation

@groeneai

@groeneai groeneai commented Jul 20, 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):

Fixed a LOGICAL_ERROR ("Bad cast from ColumnString to ColumnLowCardinality") during primary-key index analysis when a LowCardinality key column is wrapped in a nested CAST chain that re-introduces LowCardinality, e.g. WHERE CAST(CAST(s, 'LowCardinality(String)'), 'String') < '5'. In debug and sanitizer builds this aborted the server; in release it failed the query.

Description

KeyCondition builds a monotonic-function chain by resolving each function against the previous one's result type, so the argument type every wrapper declares is correct by construction. The failures came from three later strips of LowCardinality applied after that point, which left a wrapper reading a column whose representation no longer matched what it declared. FunctionCast has useDefaultImplementationForLowCardinalityColumns = false, so it reads the raw column.

The three strips, all removed or narrowed here:

  • applyFunction's cache stored every intermediate with LowCardinality stripped from both type and column. It now stores each function's own result type and representation, and only normalizes the chain's raw input. This is the reported abort.
  • applyMonotonicFunctionsChainToRange was given the key column's raw type by some callers and a stripped type by others. It now strips its own seed, which also fixes an abort on the set-index path (IN, has over a LowCardinality partition key) that reproduces on master today.
  • extractAtomFromTree appended a supertype CAST declared against the stripped key type even when the chain's last link returns LowCardinality. It is now declared against the chain's actual result type, fixing Code 44 ILLEGAL_COLUMN for CAST(d, 'LowCardinality(Date32)') < toDateTime(...).

With the invariant restored the explicit-Field path needs no coercion, so applyFunctionForField is unchanged from master. An instrumented build over the new test and a 13-shape matrix saw 1620 applications on that path with zero residual mismatches. Supertype and monotonicity decisions are unchanged, and the tests assert EXPLAIN indexes = 1 pruning so a silently declining index cannot pass on count equality alone.

Version info

  • Merged into: 26.8.1.860 (included in 26.8 and later)
  • Backported to: 26.7.3.20, 26.6.3.8

…rdinality

The monotonic-function chain in KeyCondition is built against the recursively
LowCardinality-stripped key type, but each wrapper (e.g. a FunctionCast with
useDefaultImplementationForLowCardinalityColumns = false) is resolved for its
own declared argument type. For a nested cast such as
CAST(CAST(s, 'LowCardinality(String)'), 'String') over a LowCardinality key,
the inner cast is resolved for a LowCardinality(String) source, but applyFunction
had stripped the intermediate column to a full ColumnString, so the wrapper's
checkAndGetColumn<ColumnLowCardinality> failed with a LOGICAL_ERROR (server abort
in debug/sanitizer builds, query failure in release). This is the mirror of the
previously fixed case where a LowCardinality column was fed to a plain wrapper.

applyFunction (cache-miss branch) and applyFunctionForField now match the
argument column's LowCardinality-ness to the function's declared argument type in
both directions: strip when the declared type is plain and the column is
LowCardinality, re-wrap when the declared type is LowCardinality and the column is
plain. This mirrors the sibling applyFunctionChainToColumn. Primary-key pruning
still fires and stays correct.

Related: ClickHouse#111035

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CAST(CAST(s,'LowCardinality(String)'),'String') < '5' over a LowCardinality(Nullable(Int32)) key aborts on demand (SIGABRT, exit 134) in debug/sanitizer; query failure in release.
b Root cause explained? Yes. The monotonic-function chain is built against the recursively-LowCardinality-stripped key type, but each FunctionCast wrapper (useDefaultImplementationForLowCardinalityColumns = false) is resolved for its own declared argument type. For the nested cast, the inner cast is resolved for a LowCardinality(String) source, but applyFunction had stripped the intermediate column to a full ColumnString, so checkAndGetColumn<ColumnLowCardinality> failed.
c Fix matches root cause? Yes. applyFunction / applyFunctionForField now coerce the argument column's LowCardinality-ness to the function's declared argument type at the execution site.
d Test intent preserved / new tests added? Yes. New test 04612_key_condition_nested_cast_lowcardinality; it checks correctness (pruned count == brute-force countIf) AND that pruning still fires.
e Demonstrated both directions? Yes. Test file aborts (exit 134) on pristine master; passes with the fix. Deterministic revert/rebuild/restore confirmed both Build IDs.
f General, not a narrow patch? Yes. Fixed both applyFunction (cache-miss) and applyFunctionForField; the sibling applyFunctionChainToColumn already had the pattern, so all three KeyCondition execution sites are now aligned.
g Generalizes across inputs? Yes. Matrix verified: String, Nullable(String), FixedString, triple-cast, LowCardinality(Nullable(Int32)); strip direction unregressed (LowCardinality(Bool) UInt8->Bool, single-cast); non-LowCardinality keys untouched.
h Backward compatible? Yes. No setting/format/wire change; behavior change is only "no longer abort + prune correctly". Non-LC and single-cast paths are byte-identical.
i Invariants/contracts preserved? Yes. arg_type->createColumn() on a LowCardinality type always yields ColumnLowCardinality (the assert_cast is safe); insertRangeFromFullColumn is the proven pattern from applyFunctionChainToColumn. Result-type handling is unchanged from the prior fix; only input coercion changed, preserving the Field value representation.

Verified locally: 50/50 randomized runs pass; selective nested-cast predicate prunes to 2/125 granules (index still used).

Session id: cron:clickhouse-author-slot-1:20260720-100300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent second model reviewed this diff before submission. Findings and dispositions:

💡 Nits

  • verbose-lc-comments — AGREE, fixed. The initial code comments restated the full bug narrative (~20 lines) around ~20 lines of logic. Trimmed both to brief invariant-focused notes; the narrative lives in the commit message. No logic change; rebuilt and re-verified the repro.

Delta-recheck artifacts (no action)

  • missing-functional-fix (raised only on the comment-trim delta) — DISAGREE, artifact. The delta recheck window contained only the comment trim, so it could not see the functional change. The full PR diff includes the bidirectional coercion in applyFunction / applyFunctionForField plus the 04612 regression test (3 files, +86/-14). Not a real defect.

No blockers or majors stood.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @CheSema — could you review this? It extends the KeyCondition LowCardinality fix (you reviewed #106793, @hanfei1991) to nested casts that re-introduce LowCardinality mid-chain: applyFunction/applyFunctionForField now match the argument column's LowCardinality-ness to the function's declared argument type in both directions, like the sibling applyFunctionChainToColumn.

@nihalzp nihalzp self-assigned this Jul 20, 2026
@nihalzp nihalzp added the can be tested Allows running workflows for external contributors label Jul 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [01e140e]

Summary: ✅


AI Review

Summary

This PR fixes the three LowCardinality type-mismatch sites in KeyCondition that could still surface after the earlier targeted patch, and it adds focused regressions for primary-key, partition/minmax, and set-index pruning. I read the current diff, traced the updated KeyCondition and MergeTreeSetIndex call paths in the checked-out head, and reviewed the prior thread discussion; I did not find a remaining broken invariant or a missing high-signal regression in the current revision.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 29/31 (93.55%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 281f51b2fc9da7f734d71e8ef7454b558ea5d6a1

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task. Only CH Inc sync is exempt. None are PR-caused: this PR's diff is limited to src/Storages/MergeTree/KeyCondition.cpp + one new stateless test, and none of the failures touch PK-condition/LowCardinality code.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (chronic DDL-recovery race: 506 PRs / 1120 hits / 103 master, 30d) #111029 (external, open)
Stateless (amd_llvm_coverage, ParallelReplicas, s3) / 04507_mvt_encode_state_serialize flaky (14 PRs / 4 master, 30d) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) / server-died cascade (01079_order_by_pk, 04504_variant_discriminators_cow_safe_rows_offset, 03915_exchange_tables_race, 04046_detach_attach_secondary_index_metadata_cache, 04541_create_as_select_table_scoped_insert_grant, 03236_squashing_high_memory, Unknown error) crash #109747 (ours, open) + #110048 (external, open)
Mergeable Check / PR aggregator (rolls up the above) resolves when the above owners land

Root cause of the WasmEdge-2/3 server death (from clickhouse-server.err.log, build id F9676451): Logical error: 'Arguments of 'multiply' have incorrect data types: 'n' of type 'Int256', '0.123' of type 'Float64'' -> signal 6 abort, query SELECT n * 0.123 FROM (SELECT * FROM tbl_03007_1), triggered by a concurrent EXCHANGE TABLES (03915_exchange_tables_race). All other tests in that job are downstream victims. Owned by fixing PRs #109747 (ours) + #110048.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111050&sha=281f51b2fc9da7f734d71e8ef7454b558ea5d6a1&name_0=PR

Session id: cron:our-pr-ci-monitor:20260720-163000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 04507_mvt_encode_state_serialize finish-ledger line (Code 70 Cannot convert type Tuple(Float64, Float64) to Geometry under ParallelReplicas): #111136. That is a trunk bug in the query-tree to AST conversion of folded Variant constants, unrelated to this PR's diff.

Extend the KeyCondition nested-CAST regression test with the typed-ALIAS
variant reported on PR ClickHouse#105045: a LowCardinality(UInt64) ALIAS over a plain
UInt64 key (INDEX ... TYPE bloom_filter) inserts _CAST(..., 'LowCardinality(UInt64)')
into the monotonic-function chain, so an inner CAST wrapper resolved for a
LowCardinality(UInt64) source received the stripped plain ColumnVector<UInt64>
and aborted with Bad cast in FunctionCast::prepareUnpackDictionaries. This is
the numeric, skip-index counterpart of the existing String-cast cases and is
fixed by the same bidirectional coercion in this PR. The test asserts no crash,
that the primary-key-pruned count equals a brute-force scan, and that pruning
still fires (EXPLAIN indexes = 1 reads fewer granules than the total).

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding; bounded: 1 full pass + 1 fix round + 1 delta recheck). Covers the added regression case for the typed LowCardinality ALIAS variant (commit 2be8dc8).

# Sev Finding Verdict Evidence / action
1 💡 Added test comment carried implementation-level root-cause narration that belongs in the commit message AGREE - fixed @ 2be8dc8 Trimmed the typed-ALIAS comment to a concise 2-line statement (call-path detail moved to the commit message). Delta recheck: 0 findings. The pre-existing file-level header was left untouched (already-reviewed content from an earlier commit; editing it would be out of scope).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-0:20260721-035800

The WHERE cases in this test drive KeyCondition::applyFunction through its
cached-column branch only (index bounds are block-backed FieldRefs). The
explicit-field branch (applyFunctionForField) is reached instead when
partition/minmax pruning feeds standalone Field bounds through the same
monotonic-function chain. Add a case with the nested-cast chain over a
LowCardinality partition key so both halves of the fix are exercised;
assert correctness against a brute-force scan and that pruning fires.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a88695b

Every failure below has an owner: a fixing PR. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Unknown error crash (chronic multiply(Int256, Float64) LOGICAL_ERROR abort in the coverage/WasmEdge job; zero KeyCondition frames - unrelated to this PR, whose diff is KeyCondition.cpp plus the 04612 test only, and whose a88695b delta is test-only) #109747 (ours, open) + #110048 (external, open)
Mergeable Check / PR aggregator rolls up the above

No PR-caused failure. The two test-only commits since the prior ledger (SHA 281f51b) do not touch production code, so the fix logic is unchanged and CI-clean; this ledger supersedes issuecomment-5024925811.

Session id: cron:our-pr-ci-monitor:20260721-110000

Comment thread src/Storages/MergeTree/KeyCondition.cpp Outdated
auto arg_type = getArgumentTypeOfMonotonicFunction(*func);
if (args[0].column)
{
if (!arg_type->lowCardinality() && args[0].column->lowCardinality())

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.

How can it be possible? This mismtach looks like a bug itself and a broken invariant. Try to find the root cause and fix it.

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.

The mismatch is not a stray value that appears out of nowhere; it is the intended interaction of two behaviors, and it cannot be removed by stripping.

Build side (isKeyPossiblyWrappedByMonotonicFunctions): each chain function is built against the previous function's getResultType(). For CAST(CAST(s, 'LowCardinality(String)'), 'String') the inner cast's result type is LowCardinality(String), so the outer cast's declared argument type is genuinely LowCardinality(String). That LowCardinality is load-bearing, not spurious: some functions require an LC argument, e.g. lowCardinalityIndices and toLowCardinality.

Runtime side (applyFunction): each cached intermediate column is converted to full so it stays consistent with the recursively-stripped initial key column.

So along the chain the declared argument types are heterogeneous (some LowCardinality, some not) while the column pipeline is stripped. func->execute requires the column type to match the wrapper's declared argument type, so the column has to be coerced to that type right before execution. This is exactly what the long-standing sibling applyFunctionChainToColumn does on the constant side; this PR applies the same rule to the range side. The invariant being restored is "the argument column matches the wrapper's declared argument type".

I tried the strip-at-the-source approach (keep the chain build type recursively LowCardinality-stripped after every function, so no wrapper ever declares LC). It fixes the nested-CAST case but regresses valid queries. On a local debug build:

SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE t (s String) ENGINE = MergeTree PARTITION BY s ORDER BY tuple();
INSERT INTO t VALUES ('a'), ('b'), ('c');
SELECT count() FROM t WHERE lowCardinalityIndices(toLowCardinality(s)) = 1;

this PR returns the pruned count; the strip build throws Code 43: ILLEGAL_TYPE_OF_ARGUMENT ... Expected: LowCardinality, got: String while building lowCardinalityIndices, because the strip erased the LC argument it needs. The same query runs fine on a Memory table, so it is valid; only the stripped KeyCondition chain build rejects it.

Since the declared LowCardinality cannot be removed without breaking those functions, coercing the column to the declared type is the fix. If you would prefer a different formulation (for example factoring the coercion into a shared helper so the invariant is explicit in one place), I will implement it.

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.

This fix relies on broken invariant. Fix at the root cause; it's okay if other parts of KeyCondition need to be changed.

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.

You are right, and my previous answer was wrong. I claimed the mismatch was inherent to the design; it is not. It is self-inflicted, by my own earlier commits, and I found three places that cause it. I am fixing those rather than coercing at the crash site, but I have not finished, so I have not pushed yet.

The types never actually disagreed by construction. isKeyPossiblyWrappedByMonotonicFunctions builds each chain function against the previous one's getResultType(), and applyMonotonicFunctionsChainToRange threads that same sequence, so the type reaching each function equals what it declared. Every mismatch comes from a place that strips LowCardinality out of that sequence after the fact:

  1. applyFunction's cache-miss branch stored every intermediate result with LowCardinality removed from both the type and the column (my commit d05c97b). For a chain that re-introduces it, CAST(CAST(s, 'LowCardinality(String)'), 'String'), the outer FunctionCast declares a LowCardinality(String) argument and, having useDefaultImplementationForLowCardinalityColumns = false, reads the raw column, so it received a ColumnString. That is the abort in this PR. d05c97b was fixing the opposite direction at the chain's entry and I generalized one correct strip into a strip at every link, which destroyed the interior agreement.

  2. Of the three callers of applyMonotonicFunctionsChainToRange, only checkInHyperrectangle strips the type it passes; the two in MergeTreeSetIndex::checkInRange pass the key column's raw type. So a nested-cast IN (and has) over a LowCardinality partition key aborts with Bad cast from ColumnLowCardinality to ColumnNullable. This one reproduces on master today, independently of this PR.

  3. extractAtomFromTree does key_expr_type = recursiveRemoveLowCardinality(key_expr_type) and then appends a common-supertype CAST built against that stripped type, even though the chain's last link may return LowCardinality. So the appended cast declares a plain argument while the preceding link legitimately produced an LC one.

Fixing 1 and 2 is straightforward: normalize once at the chain's input, inside applyMonotonicFunctionsChainToRange so all three callers get it, and let the cache store each function's own result type and representation. With those two, the nested-cast case, the IN/has set-index case and a matrix of single, nested, triple and 4-level strip-and-reintroduce chains over LowCardinality(Int32), LowCardinality(String), LowCardinality(Nullable(Int32)) and LowCardinality(FixedString) keys, as primary, partition and statistics keys, all return the same counts as a scan of the same predicate, and pruning still fires.

Item 3 is the one I am still on, and it is why I am not pushing yet. It is the carrier that keeps the explicit-field path (applyFunctionForField, reached through partition and statistics pruning) genuinely mismatched, so removing the coercion there without fixing 3 turns CAST(s, 'LowCardinality(Date32)') < toDateTime(...) over a LowCardinality(Date) partition key from a correct answer into ILLEGAL_COLUMN. I initially believed that coercion had become dead code and was wrong about that too; a second review caught it. The fix is to build the appended cast against the chain's actual result type instead of the stripped one, which is inside the "other parts of KeyCondition" you authorized, and I would rather get that right than push a partial change.

I will push once item 3 is done and the whole matrix plus the set-index and supertype-cast cases pass, with regression coverage for each. Thank you for pushing back twice; the second push is what made me go look at who created the mismatch instead of arguing that it was intrinsic.

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.

Do item 3 in this PR and make it complete fix.

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.

Done in this PR: a7595e3.

extractAtomFromTree strips LowCardinality from the key type to pick the comparison supertype, then appended a CAST to that supertype declared against the stripped type. When the chain's last link returns LowCardinality that cast is handed an unstripped column, so it now declares the chain's actual result type instead; the stripped copy still selects the supertype, so no supertype or monotonicity decision changes.

That was the last of the three strips, so the explicit-Field path needs no coercion and applyFunctionForField is now unchanged from master.

Measurements:

  • CAST(d, 'LowCardinality(Date32)') < toDateTime('2020-01-03 00:00:00') over a LowCardinality(Date) partition key returns 2, matching a materialize() + use_skip_indexes=0 oracle. Reverting only the declared type gives Code: 44 ILLEGAL_COLUMN ("Illegal column LowCardinality(Int32) of first argument of function toDateTime64"), so the new line is load-bearing.
  • An instrumented build over the regression test and a 13-shape matrix saw 1620 applications on the explicit-Field path with 0 residual declared-vs-argument mismatches, 68 of them this appended cast receiving LowCardinality(Date32). Restoring the source rebuilt to a bit-identical binary.
  • 13 shapes (single, nested, triple and 4-level strip-and-reintroduce casts over LowCardinality of Int32, String, Nullable(Int32), Date, FixedString, as primary, partition and set-index key, plus plus, modulo, toString, IN) each equal their oracle. lowCardinalityIndices(toLowCardinality(d)) is unaffected.
  • The tests now assert EXPLAIN indexes = 1 pruning for the IN, has and supertype-cast predicates (measured Parts: 3/40, 3/40, 3/4; an always-true control yields 0), so a silently declining index cannot pass on count equality alone.
  • 50 randomized runs of the test passed, and a 60-test sweep of related index and LowCardinality tests gives an identical 53 pass / 6 fail on this build and on a build with only this file reverted to the merge base, i.e. no new failures (the 6 need a server the sandbox does not provide).

The description is updated to describe this mechanism; it still described the earlier re-wrap approach.

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.

Carefully inspect the paths again to make sure we are not missing any cases that can lead to type mismtach.

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.

@groeneai Confirm "Carefully inspect the paths again to make sure we are not missing any cases that can lead to type mismtach.".

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.

Enumerated the callers rather than re-reading the diff, since my last message closed on an assertion ("that was the last of the three") rather than on a measurement.

applyFunction has exactly two call sites, both inside applyMonotonicFunctionsChainToRange (KeyCondition.cpp:5120, :5126), so every chain application funnels through that one function. Its four callers all pass a raw key type: checkInHyperrectangle:5562 (data_types[]), the sparse branch :5995 (sparse_data_types[]), and MergeTreeSetIndex::checkInRange at Set.cpp:897 (data_types[]) and :752 (sparse_data_types[]). That is why the strip is seeded in the callee: the earlier asymmetry, where checkInHyperrectangle stripped and the Set.cpp pair did not, is now gone by construction rather than by keeping four call sites in agreement.

Other consumers of the same RPN: Parquet/Reader.cpp:408, :950, :999 and StorageHive.cpp:653, :761, :782 reach checkInHyperrectangle and so inherit the callee strip. NativeORCBlockInputFormat.cpp:568 returns YES_NO_NULL for a non-empty chain and prepareBloomFilterData:6430 skips non-empty chains, so neither can reach applyFunction. matchesExactContinuousRange:5164 reads each function's own declared argument type, so it does not depend on what the cache stores. applyFunctionChainToColumn:1795 is a separate consumer with the opposite invariant (strip at entry, re-wrap per link at :1919) and is untouched here.

Measured 36 shapes over LowCardinality of Int32, Nullable(Int32), String, FixedString(8) and Date, plus bare and Nullable keys, and Array(LowCardinality(String)) where the inner type is stripped while the outer column is not lowCardinality(). Both directions are covered: chains that need a strip, and chains that reintroduce LowCardinality mid-chain. Paths covered are primary key, partition, set index, skip index and Parquet row groups, each compared against a brute-force countIf oracle. All 36 agree on this branch. Five fail on current master: three abort with Bad cast from ColumnString to ColumnLowCardinality (nested re-wrap over an LowCardinality(Int32) and an LowCardinality(Nullable(Int32)) primary key, and the same through the set index), and the partition-key supertype cast returns Code: 44 ILLEGAL_COLUMN.

Where master and this branch already agree the reason is structural, not luck: toLowCardinality as the final link, and Parquet inference giving String rather than LowCardinality(String) unless the type is stated explicitly.

Two mutation arms, since a green matrix proves nothing by itself. Dropping the applyFunction input normalization reddens LowCardinality(Nullable(Int32)) nested re-wrap and aborts 04612. Dropping the callee seed strip leaves all 36 shapes green, so rather than call it dead code I instrumented it: it fires 672 times across these suites, and without it the explicit-Field path takes 206 declared-versus-given mismatches and 04612 aborts. Both arms abort with Bad cast from ColumnLowCardinality to ColumnNullable, the reverse direction of the reported one. So both lines are load-bearing, though only the shipped test separates the second, not my matrix.

The path I could not exercise locally is Hive, which needs a metastore. It reaches checkInHyperrectangle with explicit Ranges, so it runs through applyFunctionForField, which this branch leaves identical to master.

Nothing pushed: the tree is still at a7595e3f3808, and restoring the file after each arm returns it to its committed md5 with no instrumentation left in the binary.

@fm4v

fm4v commented Jul 27, 2026

Copy link
Copy Markdown
Member

Can be merged?

groeneai and others added 3 commits July 28, 2026 13:29
…cache

The previous fix coerced the argument column's LowCardinality-ness to each
function's declared argument type at the two execution sites. That papered over a
broken invariant instead of fixing it, as nihalzp pointed out.

The chain built by isKeyPossiblyWrappedByMonotonicFunctions gives each function
the previous function's getResultType() as its declared argument type, and
applyMonotonicFunctionsChainToRange threads the same sequence, so the types
already agree by construction. What disagreed was the cached COLUMN: the
cache-miss branch of applyFunction stored every intermediate result with
LowCardinality stripped from both the type and the column. For a chain that
re-introduces LowCardinality, such as
CAST(CAST(s, 'LowCardinality(String)'), 'String'), the next FunctionCast declares
a LowCardinality(String) argument and, having
useDefaultImplementationForLowCardinalityColumns = false, reads the raw column,
so it received a full ColumnString and its checkAndGetColumn<ColumnLowCardinality>
failed with a LOGICAL_ERROR.

Strip LowCardinality only where the mismatch actually originates: the chain's
input column. The index column keeps its raw type (statistics and partition
pruning pass it through unchanged) while the chain was seeded with the stripped
key type, so the first function needs that one normalization. Interior links then
need none, because the cache now stores each function's own result type and
representation.

applyFunctionForField goes back to using the threaded chain type directly, and the
re-wrap branch is gone: with the invariant restored it is unreachable. Verified by
instrumenting the cache-miss branch to count residual mismatches over a matrix of
single, nested, triple and 4-level strip-and-reintroduce cast chains across
LowCardinality(Int32), LowCardinality(String), LowCardinality(Nullable(Int32)) and
LowCardinality(FixedString) keys, as primary, partition and statistics keys: 51
input normalizations, zero residual mismatches. Every shape returns the same count
as a scan of the same predicate, and pruning still fires.

Related: ClickHouse#111035

Co-Authored-By: Claude Fable 5 <[email protected]>
…oRange

The previous commit normalized the input only in applyFunction's cache-miss branch,
which covers the range path but not the explicit-field path. The set index reaches
the chain through MergeTreeSetIndex::checkInRange, which passes the key column's
raw type, so a nested-cast IN predicate (and its `has` sibling) over a
LowCardinality partition key still aborted with "Bad cast from
ColumnLowCardinality to ColumnNullable".

There are three callers of applyMonotonicFunctionsChainToRange and only
checkInHyperrectangle stripped LowCardinality from the type it passed; the two in
MergeTreeSetIndex::checkInRange did not. Since the chain is always built against a
recursively stripped key type, the stripping belongs to the callee, which now owns
it for every caller. The redundant strip at the checkInHyperrectangle call site is
removed.

Adds the IN and `has` set-index cases over a LowCardinality partition key, both
checked against a scan of the same predicate. Reverting the normalization aborts
the test (verified), so the new coverage is load-bearing.

Co-Authored-By: Claude Fable 5 <[email protected]>
extractAtomFromTree strips LowCardinality from the key type to pick the
comparison supertype, then appends a CAST to that supertype built against the
stripped type. When the monotonic-function chain's last link legitimately
returns LowCardinality, that cast is handed an unstripped column while
declaring a stripped argument, and FunctionCast (which has
useDefaultImplementationForLowCardinalityColumns = false) reads the column as
declared. Over a LowCardinality(Date) partition key,
CAST(d, 'LowCardinality(Date32)') < toDateTime(...) failed with
"Illegal column LowCardinality(Int32) of first argument of function
toDateTime64" (ILLEGAL_COLUMN).

Keep a separate unstripped chain_result_type for the cast's declared argument;
the stripped copy is still what selects the supertype, so no supertype or
monotonicity decision changes. Monotonicity is evaluated on the type threaded
through applyMonotonicFunctionsChainToRange and the cast's monotonicity functor
is selected from its return type, so pruning is unaffected.

This is the last of the three post-hoc LowCardinality strips that broke the
declared-argument-type invariant, so the explicit-Field path needs no
coercion: applyFunctionForField returns to its upstream shape. An instrumented
build over the regression test plus a 13-shape matrix saw 1620 explicit-Field
applications with zero residual declared-vs-argument mismatches, 68 of them
this appended cast receiving LowCardinality(Date32).

Tests: the supertype-cast case over a LowCardinality partition key (reverting
only the declared type reintroduces the ILLEGAL_COLUMN failure), and
EXPLAIN indexes = 1 assertions that the IN, has and supertype-cast predicates
still prune parts, so a silently declining index cannot pass on count equality
alone.
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 23/27 (85.19%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a7595e3

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky, trunk — under parallel replicas one statement becomes several reads of the same table on this server, each with a different query id, so the long-running holder query competes against itself for the single max_concurrent_queries slot and is rejected instead of holding it #112385 (ours, open)

The earlier partial fix #111528 (pin max_threads = 1 on the holder query) is present on this
head and does not cover the parallel-replicas route, so #112385 disables parallel replicas for
this test outright.

Session id: cron:our-pr-ci-monitor:20260729-103000

@groeneai groeneai mentioned this pull request Aug 4, 2026
1 task done
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 01e140e

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks infra: build-profile telemetry INSERT fails against the CI logs cluster (non-gating hook; the enclosing check reports success, so it is invisible to the check-runs API) #113409 (external, open)

Session id: cron:our-pr-ci-monitor:20260805-170000

@fm4v
fm4v added this pull request to the merge queue Aug 5, 2026
Merged via the queue into ClickHouse:master with commit b8517f0 Aug 5, 2026
180 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 5, 2026
@robot-ch-test-poll robot-ch-test-poll added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-synced-to-cloud The PR is synced to the cloud repo labels Aug 5, 2026
fm4v added a commit that referenced this pull request Aug 6, 2026
Backport #111050 to 26.6: Fix Bad cast in KeyCondition for nested CAST that re-introduces LowCardinality
fm4v added a commit that referenced this pull request Aug 6, 2026
Backport #111050 to 26.7: Fix Bad cast in KeyCondition for nested CAST that re-introduces LowCardinality
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Sep 12, 2026
`master` gained the fix for this class of `LowCardinality` mismatch in
ClickHouse#111050, which normalizes the
chain's input type inside `applyMonotonicFunctionsChainToRange`. Every
statement of this test now passes on `master`, so the header comment claiming
they throw there is stale, as is the note on the dense cached-column case.

Measured on the current merge base: the test passes in full against `master`'s
`KeyCondition.cpp`, and instrumenting every branch this pull request adds shows
none of them changes the outcome of any statement. The `Bugfix validation` jobs
are therefore right to refuse to validate this as a bug fix; the changelog
category is moved to `Not for changelog` accordingly.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Sep 13, 2026
…dition-lowcardinality-key-over-merge

Resolved the conflict in `src/Storages/MergeTree/KeyCondition.cpp` by taking
`master`'s version wholesale, which makes this pull request test-only.

`master` already normalizes the chain's input type inside
`applyMonotonicFunctionsChainToRange` (ClickHouse#111050), and ClickHouse#117054 reworked the sparse
`checkInHyperrectangle` site that this branch had edited so that it always goes
through that helper. Every branch this pull request added to `KeyCondition.cpp`
was measured on the previous merge base to change no statement outcome of the
regression test, and the review thread asked to either drop the hunks or guard
them; dropping them is the accurate resolution.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
…nested CAST that re-introduces LowCardinality
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LowCardinality(String) cannot be inside Nullable column when a CAST to Nullable wraps a LowCardinality primary-key column (26.6 regression)

6 participants