Skip to content

Cherry pick #110006 to 26.6: Support index pruning for IS NOT DISTINCT FROM and IS TRUE - #111412

Merged
robot-clickhouse-ci-1 merged 27 commits into
backport/26.6/110006from
cherrypick/26.6/110006
Jul 22, 2026
Merged

robot-clickhouse-ci-1 merged 27 commits into
backport/26.6/110006from
cherrypick/26.6/110006

Conversation

@robot-clickhouse

Copy link
Copy Markdown
Member

Original pull-request #110006

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 26 commits July 10, 2026 14:33
KeyCondition::atom_map did not map isNotDistinctFrom (the <=> operator that
IS NOT DISTINCT FROM lowers to), so `k IS NOT DISTINCT FROM 42` fell through
to Condition: true and scanned all granules. For a non-NULL constant, key <=> c
matches the same rows as key = c for both Nullable and non-Nullable keys, so it
is mapped to the same FUNCTION_IN_RANGE atom as equals. NULL constants are
rejected before the atom is built, because key <=> NULL means "key IS NULL",
not "key = NULL".

(k = 42) IS TRUE is lowered by the analyzer to isNotDistinctFrom(equals(k, 42),
true), where the key-side argument is a boolean sub-expression, not the key
column. tryRewriteIsTrueCondition unwraps isNotDistinctFrom(X, true) to X in
truth-tested boolean position when X is a boolean-returning function, so the
inner predicate becomes a prunable key atom. The rewrite is gated to
boolean-result functions because for a non-boolean X, X <=> true means X = 1,
not "X is truthy".

Closes: #109995

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The isNotDistinctFrom KeyCondition mapping added in this PR now prunes
the granules for the boolean-key IS TRUE / IS FALSE predicates in
04304_primary_key_is_true_false_unknown (SelectedMarks: IS FALSE 3->1,
IS TRUE 3->2). Results are unchanged; only granule reads drop, which is
the intended optimization. Update the reference and the explanatory
comment accordingly.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
tryRewriteIsTrueCondition gated on the raw child of isNotDistinctFrom(X, true)
being a boolean-result function. Equivalent wrapped forms like
CAST(k = 42, 'UInt8') IS TRUE or materialize(k = 42) IS TRUE reached the gate
as CAST / materialize (not boolean-result functions) and returned nullptr, so
the wrapped predicate did not become a prunable key atom even though the later
clone strips those wrappers anyway. Peel alias / materialize / trivial CAST
(the same wrappers cloneDAGWithInversionPushDown strips) before the gate so
these equivalent predicates prune identically.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Partition pruning goes through a separate KeyCondition path (PartitionPruner
over the partition value / minmax) than primary-key granule pruning. The
isNotDistinctFrom atom map and IS TRUE rewrite already apply there, so
b IS TRUE and b IS NOT DISTINCT FROM true now prune partitions the same as
b = true. Add EXPLAIN indexes=1 Parts-count assertions plus correctness checks.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…true)

Follow-up to the IS TRUE / IS NOT DISTINCT FROM rewrite. The same
KeyCondition rewrite now also peels two more truth-equivalent positive
boolean wrappers so a wrapped predicate becomes a prunable key atom:

  - notEquals(X, false)  i.e.  (k = 42) != false
  - in(X, <all-true const set>)  i.e.  (k = 42) IN (true)

Both are truth-equivalent to bare X only when X is boolean-valued, so
the same boolean-result gate as the IS TRUE path applies (extracted into
predicateIsBooleanResult). The IN path only handles literal/constant
sets whose explicit elements are available and every element is exactly
true (numeric 1); it declines otherwise (X IN (false), X IN (true,
false), X IN (2), empty set, subquery set), falling back to existing
behavior.

Benefits every index that goes through this shared canonicalizer:
primary key, minmax, bloom_filter and partition pruning.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Build (arm_tidy) failed with cppcoreguidelines-init-variables:
'variable expected_const is not initialized'. Every non-return path
assigns it, so the initializer is defensive/dead, but tidy runs as
WERROR. Initialize to 0.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
tryRewriteInTruthyCondition called buildOrderedSetInplace unconditionally
while cloning the key-condition DAG, which runs for every query on the
primary-key path. For X IN (SELECT ...) this executed the subquery purely
for analysis, so EXPLAIN SELECT ... WHERE c IN (SELECT throwIf(1)) with
use_skip_indexes=0 threw (server abort in debug/sanitizer builds) even
though no index is used, breaking 02707_skip_index_with_in.

Only inspect an already-built set (FutureSet::get() non-null for literal
tuple and storage sets); decline a not-yet-run subquery set. This matches
the intent that the IN set is not built when indexes are not used.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…onotonic chain

applyFunction (the range path) passed a raw ColumnLowCardinality to
func->execute while the monotonic-function chain is built against the
outer-LowCardinality-stripped key type, so a specialized UInt8->Bool CAST
wrapper did checkAndGetColumn<ColumnUInt8> on a ColumnLowCardinality and
aborted with a bad cast. Strip outer LowCardinality from the argument
column and type (and keep the cached result full), matching the sibling
applyFunctionChainToColumn.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…table

The lc_bool regression table sets index_granularity_bytes = 0 (non-adaptive
granularity), which is incompatible with the default min_bytes_for_wide_part
(10 MB Compact threshold). MergeTree then logs a Warning to stderr, and Fast
test fails any test that writes to stderr. Add min_bytes_for_wide_part = 0 to
force Wide format, matching the non-adaptive granularity. Test output is
unchanged (reference already matched); this only silences the warning.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…L to isNull

Address two clickhouse-gh[bot] review Majors on the positive-boolean-wrapper
key pruning:

- Derive the boolean-result gate in predicateIsBooleanResult from
  KeyCondition::atom_map (single source of truth) instead of a hand-maintained
  comparison list, so IS TRUE / != false / IN (true) wrappers peel to ANY
  prunable boolean atom KeyCondition supports (has, startsWith, startsWithUTF8,
  match, pointInPolygon, ...), not just comparisons. startsWith(s,'ab') IS TRUE
  now prunes the key the same as bare startsWith(s,'ab').

- Route the NULL arm of isNotDistinctFrom onto the existing isNull atom:
  key <=> NULL is equivalent to isNull(key), so a Nullable PK / minmax index
  now prunes to the NULL granule exactly instead of scanning every granule.

Add 04401 coverage for the newly-covered forms and flip the previously-weaker
IS NOT DISTINCT FROM NULL assertion to assert pruning.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ifNull(k = 42, 0) IS TRUE (and the != false / IN (true) forms) lowered to
isNotDistinctFrom(ifNull(equals(k, 42), 0), true) did not prune: the
boolean-result gate in predicateIsBooleanResult rejects the ifNull wrapper, so
tryRewriteIsTrueCondition declines and the fallback clone with boolean_context
= false denies the existing coalesce rewrite its chance too, leaving
Condition: true even though bare ifNull(k = 42, 0) already prunes when
allow_key_condition_coalesce_rewrite is enabled.

Recurse the boolean-result gate through a falsy-zero ifNull/coalesce wrapper
(gated by the same setting): ifNull(Y, 0) is boolean-valued iff Y is, so the
outer peel enters boolean context and the existing recursion unwraps the ifNull
to the prunable inner atom. Factor the ifNull/coalesce(X, 0) shape recognition
into isFalsyZeroCoalesceCondition, shared by the gate and tryRewriteCoalesceCondition.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pin index_granularity_bytes = 0 (with min_bytes_for_wide_part = 0 to keep
Wide format and avoid the adaptive-granularity warning) on every table whose
exact Granules: N/M count is asserted, so the count depends only on the
row-count index_granularity and not on the CI-randomized byte cap that would
split the matched key range across granules. Also OPTIMIZE the pk_null table
to a single part up front so the flaky-check's nondeterministic mid-test merge
cannot flip the NULL granule count (1 vs 2) between the IS NULL / <=> NULL
assertions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…Condition

The boolean-result check of the IN predicate's left-hand side is a property of
the predicate alone and independent of the set, so run it before the O(set size)
ordered-set materialization (buildOrderedSetInplace + getSetElements). This avoids
building and iterating the set for common large non-boolean filters like
user_id IN (1, 2, ... huge literal list) only to discard the rewrite, matching
the discipline in tryPrepareSetIndexForIn. Pure reorder, behavior unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The FUNCTION_IS_NULL / FUNCTION_IS_NOT_NULL evaluators ignore
out.monotonic_functions_chain ("nulls are kept"), so a NULL-erasing wrapper
(ifNull, coalesce, assumeNotNull) that isKeyPossiblyWrappedByMonotonicFunctions
accepts into the chain makes ifNull(nullable_k, 0) IS NOT DISTINCT FROM NULL (and
bare isNull(ifNull(k, 0))) get analyzed like isNull(k). Since ifNull(k, 0) is
never NULL the predicate is always false, but the isNull atom narrows a Nullable
PK/minmax index to the NULL granule and marks it exact-true, so exact-count and
implicit-projection paths return rows for an always-false predicate.

Decline the null atom when the key-side monotonic chain contains a NULL-erasing
wrapper (both the unary isNull/isNotNull path and the isNotDistinctFrom NULL
branch), falling back to a full scan. Also decline tryRewriteCoalesceComparison
for a NULL constant, which only reaches it via isNotDistinctFrom and would emit
an isNull-based branch decomposition with the same wrong pruning.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…s-not-distinct-from-109995

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
The monotonicChainPreservesNulls guard used a hard-coded 3-name allowlist
(ifNull/coalesce/assumeNotNull), which missed monotonic conversion wrappers.
A CAST to a non-Nullable type also erases NULL, so isNull(CAST(k,'UInt32'))
and CAST(k,'UInt32') IS NOT DISTINCT FROM NULL wrongly reused the isNull atom,
pruning to the NULL granule and marking it exact-true for an always-false
predicate (wrong results on exact-count / implicit-projection paths).

Replace the allowlist with a semantic per-function check: a chain function
preserves NULL iff, whenever it takes a Nullable argument, its result type is
also Nullable. This keeps NULL-preserving conversions such as
toUInt32(Nullable(UInt32)) (result Nullable(UInt32)) pruning correctly while
rejecting the NULL-erasing conversion family and the three named wrappers.

Also tag 04401 no-random-merge-tree-settings: it asserts exact Granules: N/M
counts that depend on the data layout, which randomized MergeTree settings flip.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The result-type nullability proxy misclassified ifNull/coalesce with a
Nullable-but-non-NULL fallback (e.g. ifNull(k, CAST(0, 'Nullable(UInt32)')))
as NULL-preserving, so the isNull atom reuse for IS NOT DISTINCT FROM NULL /
isNull wrongly pruned to the NULL granule and marked it exact-true for an
always-false predicate. Execute each chain wrapper on a NULL input instead
and check whether the output is actually NULL (a throw counts as not
preserving), which is correct for every monotonic-chain function.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The behavioral NULL-preservation check catches a throw (e.g. CAST to a
non-Nullable type on a NULL input) to mean the wrapper does not preserve
NULLs. Add an 'Ok' comment so the check_style catch-all linter does not
flag the intentional swallow.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Membership-only lookup; unordered_set is the idiomatic O(1) choice.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…KeyCondition

The FUNCTION_IS_NULL evaluators ignore the monotonic-functions chain, so
reusing the isNull atom for a wrapped key assumes the wrapper is both
NULL-preserving and total on the key domain. An overflow-checked conversion
such as toDateTime(Date32) under date_time_overflow_behavior='throw' is
NULL-preserving yet partial: an out-of-range non-NULL value raises instead of
yielding a defined result. Pruning then dropped such a non-NULL granule as
always-false, so a scan that should raise silently returned rows.

Add a totality gate (canBeSafelyCast on each step's argument/result type) next
to the existing NULL-preservation check; a chain qualifies only if every step
both preserves NULL and cannot overflow. NULL-preserving total wrappers
(toUInt32(Nullable), widening casts) still prune.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ondition

The totality gate for reusing the `isNull` atom under a monotonic-function
chain used only `canBeSafelyCast`, a type-level "no value of the source type
overflows the target" test. That misses value-dependent partiality whose result
type equals the argument type: `intDiv(k, 0)` is `Int64 -> Int64`, so it passes
`canBeSafelyCast`, yet raises `ILLEGAL_DIVISION` on every non-NULL row. Reusing
`isNull(k)` for `isNull(intDiv(k, 0))` (or `intDiv(k, 0) IS NOT DISTINCT FROM
NULL`) then pruned the non-NULL granule as always-false, so a query that should
raise like a full scan silently returned the NULL rows instead (reproducible via
the exact-count / implicit-projection path).

Add a second, behavioral guard: also require the wrapper to be monotonic across
its whole input range (`getMonotonicityForRange(...).is_always_monotonic`). The
function already reports `variable / 0` as non-monotonic, so this rejects the
throwing divisor while keeping total wrappers (`toInt64`, `plus`, `intDiv(k, c)`
with `c != 0`). Monotonicity is queried on the `Nullable`/`LowCardinality`-
stripped argument type so numeric identity conversions (`toUInt32` on a
`Nullable(UInt32)` key) still take their always-monotonic fast path. Both guards
are conservative; declining only forces a full scan.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
functionIsTotalOnKeyDomain used canBeSafelyCast + is_always_monotonic to
decide totality. That misses intDiv(k, -1): getMonotonicityForRange reports
is_always_monotonic for a -1 divisor, yet intDiv(Int_MIN, -1) overflows and
raises ILLEGAL_DIVISION for key widths without the constant-divisor
specialization (Int8/Int16/Int128). So isNull(intDiv(k, -1)) could reuse the
bare isNull atom and prune the non-NULL granule, suppressing the exception.

Replace the heuristics with a behavioral boundary probe: run the wrapper on the
extreme values of its integer key domain via the same execute path a scan uses,
and decline the isNull-atom reuse if it raises. This catches conversion
overflow, div-by-zero and the signed min/-1 case uniformly, and admits the
Int32/Int64 intDiv(k, -1) forms that wrap (never raise). Non-integer domains
fall back to the conservative type-level canBeSafelyCast check.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The isNull/isNotNull atoms (and the key IS NOT DISTINCT FROM NULL branch that
reuses them) ignore the key monotonic-functions chain, so they are sound only
for a bare Nullable key. A monotonic wrapper can erase NULL (ifNull, coalesce,
CAST to non-Nullable) or be partial (toDateTime(Date32) / intDiv(k, 0) throw on
some rows), which would let isNull(wrapper(k)) narrow to the NULL granule and
mark it exact-true, returning wrong exact-count results. Decline the atom for
any wrapped key and fall back to a full scan, which is always correct.

This removes the runtime function-probing helpers (functionPreservesNulls,
functionIsTotalOnKeyDomain) in favor of a plain empty-chain check.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The 04304 EXPLAIN/SelectedMarks assertions hard-code granule counts, but
bool_pk and int_pk left index_granularity_bytes randomizable, so a small
randomized adaptive-granularity value could split the tables into a
different number of marks and break the assertions. Pin
index_granularity_bytes = 0 and min_bytes_for_wide_part = 0 on both tables,
matching 04401_date32_zerotransform_monotonicity_pruning in this PR.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…tinct-from-109995

Support index pruning for IS NOT DISTINCT FROM and IS TRUE
@robot-clickhouse robot-clickhouse added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Jul 22, 2026
…ypick/26.6/110006

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
@robot-clickhouse-ci-1
robot-clickhouse-ci-1 merged commit 3c1d77a into backport/26.6/110006 Jul 22, 2026
1 check passed
@robot-clickhouse-ci-1
robot-clickhouse-ci-1 deleted the cherrypick/26.6/110006 branch July 22, 2026 21:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants