Skip to content

Fix LOGICAL_ERROR in partition pruning when chain collapses to constant - #104861

Merged
nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-104840-bad-cast-keycondition
May 13, 2026
Merged

nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-104840-bad-cast-keycondition

Conversation

@groeneai

@groeneai groeneai commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator

Fix LOGICAL_ERROR ("Bad cast from type DB::ColumnConst to DB::ColumnNullable") in partition pruning for MergeTree tables when the partition expression's monotonic function chain collapses to a single constant value.

Root cause

KeyCondition::applyFunctionChainToColumn strips outer LowCardinality from the result of func->execute but not outer Const. When the chain collapses to a constant (e.g. floor(NULL, x) always yields NULL), func->execute returns ColumnConst(ColumnNullable(...)) of size 1.

ColumnConst::isNullable reports the wrapped column's nullability, so the existing isNullable() guard accepts the column while the subsequent assert_cast<const ColumnNullable &> aborts the server.

Reproducer (floor(NULL, toRelativeYearNum(myDay)) partition key — taken from the fuzzer report in #104840):

CREATE TABLE t (myDay Date NULL, myOrder DateTime('UTC'))
ENGINE = MergeTree
PARTITION BY floor(NULL, toRelativeYearNum(myDay))
ORDER BY myOrder
SETTINGS allow_nullable_key = 1, allow_suspicious_indices = 1;

INSERT INTO t VALUES ('2021-01-02', 1);
SELECT * FROM t WHERE myDay = '2021-01-02';

Before this PR the SELECT aborts with Bad cast from type DB::ColumnConst to DB::ColumnNullable; after this PR it returns the matching row.

Fix

Strip the outer Const right after convertToFullColumnIfLowCardinality so the column shape stays in sync with result_type and with the post-strip invariant established at the top of the function (which already strips Const, Replicated, Sparse, and LowCardinality).

Apply the same defensive unwrap to the sibling assert_cast site after castColumnAccurateOrNull — FunctionCast wrappers can also return ColumnConst for 1-row inputs by the same mechanism. This prevents a class of fuzzer findings rather than just the one reported.

A new stateless regression test 04237_104840_partition_pruner_floor_null_nullable_key aborts the server on master and passes after the fix.

Closes: #104840

Changelog category (leave one):

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

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

Fix Bad cast from type DB::ColumnConst to DB::ColumnNullable server abort during partition pruning for MergeTree tables when the partition expression contains a function chain that collapses to a single constant value (such as floor(NULL, toRelativeYearNum(...))).

Version info

  • Merged into: 26.5.1.634
  • Backported to: 26.4.3.27

…tant

`KeyCondition::applyFunctionChainToColumn` strips outer `LowCardinality`
from the result of `func->execute` but not outer `Const`. For partition
expressions whose monotonic function chain collapses to a single constant
value (e.g. `floor(NULL, x)` always yields NULL), `func->execute` returns
`ColumnConst(ColumnNullable(...))` of size 1.

`ColumnConst::isNullable` reports the wrapped column's nullability, so
the `isNullable()` guard accepted the column while the subsequent
`assert_cast<const ColumnNullable &>` aborted the server with:

    Bad cast from type DB::ColumnConst to DB::ColumnNullable

(STID: 3520-4237 in the AST fuzzer infra)

Strip the outer `Const` after `convertToFullColumnIfLowCardinality` so
the column shape matches `result_type` and the post-strip invariant
established at the top of the function
(`convertToFullColumnIfConst()->convertToFullColumnIfReplicated()->convertToFullColumnIfSparse()->convertToFullColumnIfLowCardinality()`).
Apply the same defensive unwrap after `castColumnAccurateOrNull` to
cover the structurally identical sibling site — `FunctionCast` wrappers
can also return `ColumnConst` for 1-row inputs by the same mechanism,
so this prevents a class of fuzzer findings rather than just the one
reported.

Closes ClickHouse#104840
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session cron:clickhouse-ci-task-worker:20260513-141500):

a) Deterministic repro? ✅ Yes. The CREATE TABLE ... PARTITION BY floor(NULL, toRelativeYearNum(myDay)) ... allow_nullable_key = 1 + SELECT WHERE myDay = '2021-01-02' query reliably aborts master HEAD (commit 124a5882d10) with Logical error: 'Bad cast from type DB::ColumnConst to DB::ColumnNullable' at KeyCondition.cpp:1547. The full stack matches the auto-generated issue body exactly.

b) Root cause explained? ✅ Yes. KeyCondition::applyFunctionChainToColumn strips outer LowCardinality from func->execute's result but not outer Const. When the monotonic chain collapses to a single constant value — here floor(NULL, toRelativeYearNum(myDay)) first applies toRelativeYearNum (producing a single-row Nullable(UInt16)), then floor with NULL as its first argument always yields NULL — func->execute returns ColumnConst(ColumnNullable(...)) of size 1. ColumnConst::isNullable is defined as isColumnNullable(*data) (Columns/ColumnConst.h:312), so the if (result_column->isNullable()) guard accepts the column while the subsequent assert_cast<const ColumnNullable &>(*result_column) fails on the outer ColumnConst and aborts the server.

c) Fix matches root cause? ✅ Yes. Strip the outer Const directly after convertToFullColumnIfLowCardinality so the column shape stays in sync with result_type and with the post-strip invariant established at the top of the function (which already strips Const → Replicated → Sparse → LowCardinality). This is the symmetric completion of an existing partial normalization, not a guard added at the symptom site.

d) Test intent preserved? / New test added? ✅ Yes. New stateless test 04237_104840_partition_pruner_floor_null_nullable_key reproduces the exact fuzzer trigger (Nullable Date with floor(NULL, toRelativeYearNum(...)) partition expression). It aborts the server before the fix and passes after.

e) Both directions demonstrated? ✅ Yes.

  • Before fix (master HEAD 124a5882d10): SELECT * FROM t_104840 WHERE myDay = '2021-01-02' aborts the server with Bad cast from type DB::ColumnConst to DB::ColumnNullable.
  • After fix: 04237_104840_partition_pruner_floor_null_nullable_key passes 20/20 with full setting randomization. Related partition-pruner / monotonic-function tests (02232_partition_pruner_*, 00653_monotonic_*, 01710_aggregate_projection_with_monotonic_key_expr, 01940_totimezone_operator_monotonicity, 01480_binary_operator_monotonicity, etc.) all pass (39/39 stateless + 1 stateful-tagged).

f) Fix is general, not a narrow patch? ✅ Yes.

  • Audited every assert_cast<const ColumnNullable &> in KeyCondition.cpp: lines 1455, 1547, 1809, 1836.
  • 1547: the reported crash site — fixed.
  • 1455: structurally identical sibling in the same function (after castColumnAccurateOrNull). FunctionCast wrappers can also return ColumnConst for 1-row inputs, so applied the same convertToFullColumnIfConst() defensively. This prevents the same fuzzer-finding class from re-surfacing here.
  • 1809: inside applyDeterministicDagToColumn::finalize_output_column_and_type — already preceded by column->convertToFullIfNeeded() (line 1804). Safe.
  • 1836: inside applyDeterministicDagToColumn::cast_without_nulls — same pattern as 1455. Not modified in this PR because it's reached through a different code path with no current crash report, and broadening the fix there would couple this change with an unverified hypothesis. Leaving as a future follow-up if a sibling fuzzer finding appears.

Tracking task: 2026-05-13-github-clickhouseclickhouse104840--. CIDB shows STID 3520-4237 at 9 hits across 7 distinct PRs + 2 master hits in the last 30 days, most recent master hit 2026-05-12 20:48 UTC.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @CurtizJ @KochetovNicolai — could you review this? It fixes a chronic AST-fuzzer LOGICAL_ERROR (Bad cast from type DB::ColumnConst to DB::ColumnNullable) in KeyCondition::applyFunctionChainToColumn by stripping outer Const after func->execute (and defensively at the sibling castColumnAccurateOrNull site). 9 master/PR hits across 7 distinct PRs in 30 days (STID 3520-4237). cc @PedroTadim (issue reporter).

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

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [00df6f1]

Summary: ✅


AI Review

Summary

This PR fixes the partition-pruning LOGICAL_ERROR path by unwrapping outer ColumnConst results in KeyCondition::applyFunctionChainToColumn (both after castColumnAccurateOrNull and after func->execute), and adds a focused regression test that reproduces the original failure mode. I did not find unresolved correctness, safety, or metadata issues in the current diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 13, 2026
…ion FAIL

The bugfix-validation framework needs the regression test to FAIL on
master HEAD (status `FAIL`, an output diff vs `.reference`) so that the
inversion logic in `ci/jobs/functional_tests.py` can flip it to `OK`
and report "bug reproduced".

The previous `.sql` form crashed the server on master HEAD via the
`assert_cast<const ColumnNullable &>(ColumnConst &)` abort in
`KeyCondition::applyFunctionChainToColumn`. The test runner then
classified that as `SERVER_DIED`/`ERROR`-shaped failure caught by the
outer hung-check, and the framework refused to invert it ("Failed to
reproduce the bug").

Reshape into a `.sh` test that runs the bug-triggering scenario inside
a `clickhouse-local` subprocess. On master HEAD the subprocess aborts
(SIGABRT, exit 134); the `if` branch is taken and we print `BUG`,
diverging from the `OK` reference -> `FAIL`. On the PR branch the
subprocess succeeds and we print `OK` -> `OK`. The server stays alive
either way, so the framework sees a clean output diff that it can
invert.

Verified locally on debug builds:
* master HEAD KeyCondition.cpp (no fix): `[ FAIL ]`, stdout `BUG`,
  server unaffected.
* PR HEAD with fix: `[ OK ]` (5/5 runs).

Bugfix validation CI log:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/104861/42fc1aef6e10b6e9241e54bdebe2ea37c8dd416c/bugfix_validation_functional_tests/job.log
PR: ClickHouse#104861

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

Copy link
Copy Markdown
Collaborator Author

Pushed fix-up 00df6f158f8 addressing the Bugfix validation (functional tests) failure on the previous commit.

Why the previous test didn't drive a FAIL

The .sql form ran the bug-triggering SELECT against the test server. On master HEAD (release build, ARM) the assert_cast<const ColumnNullable &>(ColumnConst &) in KeyCondition::applyFunctionChainToColumn reduces to a static_cast, and the subsequent virtual access drives the server into an unresponsive state. The bugfix-validation outer hung-check fires after ~65s and sends SIGTERM to the runner before the per-test result can be recorded — so the framework records the run as SERVER_DIED/ERROR-shaped, not FAIL.

The inversion logic in ci/jobs/functional_tests.py only flips FAIL <-> OK; ERROR is left intact, so the framework concludes "Failed to reproduce the bug".

Reshape

Moved the test to a .sh form that runs the bug-triggering scenario inside a clickhouse-local subprocess. The subprocess crash stays contained — the server keeps running, the wrapper script always exits 0, and the only thing the framework sees is an output diff.

  • Master HEAD (no fix): subprocess aborts (SIGABRT, exit 134) -> if branch is not taken -> stdout BUG != reference OK -> FAIL -> inverted to OK -> bug reproduced ✓
  • PR HEAD (fix applied): subprocess succeeds -> stdout OK == reference -> regular OK

Verified locally on debug builds (same KeyCondition.cpp reverted to origin/master for the negative case):

  • master HEAD: [ FAIL ] 5.80 sec. with stdout BUG, server unaffected.
  • PR HEAD: [ OK ] 5/5 runs (--test-runs 5).

The source fix in src/Storages/MergeTree/KeyCondition.cpp is unchanged.

Pre-PR validation gate (a-f)

a. Deterministic repro? Yes — clickhouse-local --query "CREATE TABLE ... PARTITION BY floor(NULL, toRelativeYearNum(myDay)) ...; SELECT ..." aborts on master HEAD on every invocation (exit 134).
b. Root cause explained? Yes — ColumnConst::isNullable reports the wrapped column's nullability, so the isNullable() guard at KeyCondition.cpp:1558 accepts ColumnConst(ColumnNullable(...)); assert_cast<const ColumnNullable &> then aborts on the outer ColumnConst. Fix unwraps ColumnConst defensively after func->execute (and the sibling site after castColumnAccurateOrNull).
c. Fix matches root cause? Yes — unchanged from 42fc1aef; same two convertToFullColumnIfConst() calls at the two sites in KeyCondition.cpp.
d. Test intent preserved? Yes — the partition pruner still drives applyFunctionChainToColumn via floor(NULL, toRelativeYearNum(myDay)); same fuzzer reproducer, same code path.
e. Both directions demonstrated? Yes — FAIL on master, OK on PR, both verified locally.
f. General fix, not narrow patch? Yes — fix covers both assert_cast<const ColumnNullable &> sites (after castColumnAccurateOrNull and after func->execute), preventing the same class of fuzzer findings rather than just the one reported.

Session: cron:clickhouse-ci-task-worker:20260513-151500

@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 100.00% (9/9) · Uncovered code

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue May 13, 2026
Merged via the queue into ClickHouse:master with commit bd123fe May 13, 2026
167 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 16, 2026
The previous `.sql` form relied on `{ serverError ILLEGAL_TYPE_OF_ARGUMENT }`
directives, but on master HEAD (without the fix) the bug-triggering
queries reach the `LOGICAL_ERROR` guard in `ColumnTuple::create` and
abort the server under `abort_on_logical_error = true` (the default
in CI test environments). The bugfix-validation framework saw the
parent server crash as `ERROR` / `SERVER_DIED` and reported "Failed
to reproduce the bug" because that result is not invertible.

This commit wraps the bug-triggering queries in a `.sh` script that
runs each query inside a `clickhouse-local` subprocess. The abort
on master HEAD now stays contained: `clickhouse-local` returns a
non-43 exit code, the script prints `BUG`, the output diff fails,
and the bugfix-validation framework can invert that `FAIL` into a
"bug reproduced" signal. On the PR branch the queries return
`ILLEGAL_TYPE_OF_ARGUMENT` (Code 43) cleanly and the script prints
`OK`.

See PR ClickHouse#104861 for an earlier example of this `.sh` wrapper pattern
for a contained-abort regression test.

Session: cron:clickhouse-ci-task-worker:20260516-114500
@alexey-milovidov

Copy link
Copy Markdown
Member

Backporting, because there are crashes in 26.4.

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label May 17, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request May 17, 2026
Cherry pick #104861 to 26.4: Fix `LOGICAL_ERROR` in partition pruning when chain collapses to constant
robot-clickhouse added a commit that referenced this pull request May 17, 2026
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label May 17, 2026
nihalzp added a commit that referenced this pull request May 18, 2026
Backport #104861 to 26.4: Fix `LOGICAL_ERROR` in partition pruning when chain collapses to constant
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…pruning when chain collapses to constant
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…4861

Backport ClickHouse#104861 to 26.4: Fix `LOGICAL_ERROR` in partition pruning when chain collapses to constant
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.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Bad cast from type A to B (STID: 3520-4237)

6 participants