Skip to content

Fix wrong results from WHERE p AND LowCardinality(Nullable(int)) constant on MergeTree - #104767

Merged
Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-where-and-lc-nullable-constant-104393
May 19, 2026
Merged

Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-where-and-lc-nullable-constant-104393

Conversation

@groeneai

@groeneai groeneai commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

On MergeTree tables, WHERE p AND <LowCardinality(Nullable(int)) constant> silently returned zero rows. Found by @qoega via SQLancer in #104393.

splitFilterNodeForAllowedInputs (src/Storages/VirtualColumnUtils.cpp) splits the predicate at part-pruning time. When one branch of an AND is not evaluable on virtual columns it drops that branch and keeps the surviving constant child. If the child's type differs from the original AND result, the function synthesizes a notEquals(x, default) guard so the result is still boolean.

It computed the default with removeNullable(result_type). For a LowCardinality(Nullable(X)) constant the outer type is LowCardinality, not Nullable, so removeNullable was a no-op and getDefault() then went through the LC dictionary and returned Null. The synthesized guard became notEquals(x, NULL), which evaluates to NULL and is treated as false in filter context — so every part was pruned before any data was read.

Replaced with removeLowCardinalityAndNullable, which strips both wrappers. The default of the underlying scalar type (0 for integers) is used instead, restoring the intended (x > 0) AND truthy_const semantics. The pre-existing Nullable(Nothing) special case (for a bare NULL literal) still falls through to the original type's default, so WHERE x AND NULL continues to prune every row.

Verified the new test reproducer FAILS on master and PASSES on the fix branch (50/50 runs with full setting randomization). Related regression tests (partition_pruning, virtual_column, 04074_where_large_int_boolean_predicate, 04104_103049_nullable_and_overflow_filter) still pass.

Closes #104393.

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 wrong results from WHERE p AND <LowCardinality(Nullable(int)) constant> on MergeTree tables. Previously such queries returned zero rows because part pruning derived a NULL default from the LowCardinality(Nullable(...)) type and synthesized a notEquals(x, NULL) guard, pruning every part.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

Version info

  • Merged into: 26.5.1.826

…tant on MergeTree

When `splitFilterNodeForAllowedInputs` reduced `(non_virtual AND const)`
to a single surviving atom whose `result_type` did not match the original
`AND` node's type, it synthesized a `notEquals(x, default)` guard so the
filter still produced a boolean. It used `removeNullable(result_type)`
to choose the default. For a `LowCardinality(Nullable(X))` constant the
outer type is `LowCardinality` (not `Nullable`), so `removeNullable` was
a no-op; `getDefault` on `LowCardinality(Nullable(X))` falls through to
the dictionary type and returns `Null()`. The synthesized guard became
`notEquals(x, NULL)` -> `NULL` -> false, and partition pruning then
discarded every part before any data was read.

Replace `removeNullable` with `removeLowCardinalityAndNullable`, which is
`removeNullable(removeLowCardinality(type))`. This strips both wrappers
so the default of the actual scalar type is used (`0` for integers),
restoring the original `(x > 0) AND truthy_const` semantics. The
`Nullable(Nothing)` special case still falls through to the original
type's default (`NULL`) so a literal `NULL` continues to prune all rows
as before.

Closes ClickHouse#104393.

Reproducer (returned 0 instead of 499 on master):

    SET allow_suspicious_low_cardinality_types = 1;
    CREATE TABLE t (a UInt32) ENGINE = MergeTree ORDER BY a;
    INSERT INTO t SELECT number FROM numbers(500);
    SELECT count() FROM t WHERE (a > 0) AND CAST(1 AS LowCardinality(Nullable(UInt8)));
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (TASK.md Phase 4 step 9)

  • (a) Deterministic repro? Yes — the SQL in the test fails consistently on master (returns 0/0/0/0 for the four LowCardinality(Nullable(...))-flavored queries) and passes 50/50 runs on this branch with full setting randomization.
  • (b) Root cause explained? Yes — splitFilterNodeForAllowedInputs (src/Storages/VirtualColumnUtils.cpp) used removeNullable(result_type) to pick a default for a synthesized notEquals(x, default) guard. For a LowCardinality(Nullable(X)) constant the outer type is LowCardinality (not Nullable), so removeNullable was a no-op and getDefault fell through to the dictionary's Nullable default (Null). The guard became notEquals(x, NULL) -> NULL -> false, so partition pruning discarded every part before any data was read.
  • (c) Fix matches root cause? Yes — switched to removeLowCardinalityAndNullable which strips both wrappers, so the default of the actual scalar type (0 for integers) is used. The Nullable(Nothing) special case for a bare NULL literal still falls through to the original type's default (Null), so WHERE x AND NULL continues to prune all rows.
  • (d) Tests added? Yes — 04234_where_and_low_cardinality_nullable_constant_104393.{sql,reference} covers all six original reproducer variants plus a falsy LC(Nullable(...)) constant, a NULL LC(Nullable(...)) constant, the PREWHERE path, and the no-prewhere variant.
  • (e) Both directions demonstrated? Yes — test FAILS on master HEAD (verified by reverting the fix, rebuilding, and re-running) and PASSES on this branch (verified 50/50 with full randomization).
  • (f) Fix is general, not a narrow patch? Yes — removeLowCardinalityAndNullable handles every (LC?, Nullable?) * scalar combination: LC(UInt8), LC(Nullable(UInt8)), LC(Nullable(UInt64)), plain Nullable(UInt8), plain UInt8, and Nullable(Nothing) (falls through to the special case). Verified that the surrounding related tests (partition_pruning, virtual_column, 04074_where_large_int_boolean_predicate, 04104_103049_nullable_and_overflow_filter) still pass.

Session: cron:clickhouse-ci-task-worker:20260512-214500.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai — could you review this? It fixes a silent wrong-results bug on MergeTree where WHERE p AND <LowCardinality(Nullable(int)) constant> returned 0 rows because part pruning's synthesized notEquals(x, default) used removeNullable (which is a no-op on LowCardinality(Nullable(...))) and got NULL as the default. Closes #104393.

@Algunenano Algunenano 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 [9835180]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) FAIL
03156_tuple_map_low_cardinality FAIL cidb, issue ISSUE CREATED
Stateless tests (arm_asan_ubsan, azure, parallel) FAIL
03040_dynamic_type_alters_2_compact_merge_tree FAIL cidb, issue ISSUE CREATED

AI Review

Summary

This PR fixes a wrong-results path in MergeTree part pruning where WHERE p AND <LowCardinality(Nullable(...)) constant> could be reduced to notEquals(x, NULL) and incorrectly prune all parts. Replacing removeNullable with removeLowCardinalityAndNullable in splitFilterNodeForAllowedInputs matches the failure mode, and the new stateless test covers truthy/falsy/NULL constants, PREWHERE, and disabled-prewhere execution.

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
@Avogar Avogar self-assigned this May 13, 2026
@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 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

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

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, provide fixes for these two errors in separate PRs:

Stateless tests (amd_msan, WasmEdge, parallel, 2/2) FAIL
03156_tuple_map_low_cardinality FAIL cidb
Stateless tests (arm_asan_ubsan, azure, parallel) FAIL
03040_dynamic_type_alters_2_compact_merge_tree

As soon as the fixes are submitted or linked, update the branch here.

@Avogar

Avogar commented May 19, 2026

Copy link
Copy Markdown
Member

Let's move these failures in separate issues, merge this one and I will take care of the issues.

@Avogar
Avogar added this pull request to the merge queue May 19, 2026
Merged via the queue into ClickHouse:master with commit 2cd409d May 19, 2026
163 of 166 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: splitFilterNodeForAllowedInputs in src/Storages/VirtualColumnUtils.cpp:626 — introduced in 26.4.

Why this might apply: The bug was introduced by the #103049 fix (commit 7c78cbd, 2026-04-18) which was backported to 26.4. Branch 26.4 shows removeNullable(res->result_type) at the affected code path, not the fixed removeLowCardinalityAndNullable. Branches 26.3, 26.2, and 25.8 don't have the #103049 fix at all, so they don't have this bug.

Other supported branches (26.3, 26.2, 25.8) predate 26.4 and do not contain this code.

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.4-must-backport.

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 19, 2026
@cnkk

cnkk commented May 27, 2026

Copy link
Copy Markdown

I have a similar issue on v26.3.x which seems to be fixed in 26.5:

https://fiddle.clickhouse.com/41e96b7a-89a5-4831-9927-7fcf3cdb30f0

DROP TABLE IF EXISTS t_repro;
CREATE TABLE t_repro (
    s String,
    n LowCardinality(Nullable(String)),
    INDEX idx_n n TYPE set(100) GRANULARITY 2,
    INDEX idx_s s TYPE ngrambf_v1(4, 1024, 2, 0) GRANULARITY 3
) ENGINE = MergeTree ORDER BY tuple();

INSERT INTO t_repro SELECT 'has-republisher', NULL FROM numbers(100000);
INSERT INTO t_repro SELECT 'no-match', NULL FROM numbers(100);

-- Correct: 100,000 rows match the tag
SELECT count() FROM t_repro WHERE s LIKE '%republisher%';

-- BUG: OR with the nullable column should ALSO return 100,000, but returns 0 on 26.3.x
SELECT count() FROM t_repro WHERE (n = 'republisher' OR s LIKE '%republisher%');

-- WORKAROUND: assumeNotNull() returns the correct 100,000 on all versions
SELECT count() FROM t_repro WHERE (assumeNotNull(n) = 'republisher' OR s LIKE '%republisher%');

@Avogar any ideas if a fix could be related to this PR?

@den-crane

Copy link
Copy Markdown
Contributor

@cnkk It's seems like an issue in combining two skip indexes. Open an issue. It could be accidentally fixed by this PR. Anyway your example should be added to test/ci.

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.

WHERE p AND <LowCardinality(Nullable(UInt8)) constant> returns zero rows on MergeTree

8 participants