Skip to content

Fix rows silently dropped by IN and NOT IN index analysis over a cross-type constant set - #112966

Closed
groeneai wants to merge 41 commits into
ClickHouse:masterfrom
groeneai:fix/keycondition-cross-type-set-exactness-nonnullable
Closed

groeneai wants to merge 41 commits into
ClickHouse:masterfrom
groeneai:fix/keycondition-cross-type-set-exactness-nonnullable

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112890
Related: #115294
Related: #118899

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 IN and NOT IN silently returning fewer rows when the constant set's element type and the key column type do not convert into each other reversibly, for example a String set element against a UInt64 key. Index analysis built an exact set atom out of the converted elements, so partition and min/max pruning could discard a part that held a matching row.

Description

Found while measuring index analysis; no open issue matches.

Index analysis converts the set constants into the key column's type; runtime IN membership converts the key into the set element's type. Where the two are not mutual, the atom names different key values than the predicate matches, and single-point key range pruning (partition and min/max) discards a part holding a matching row. Measured against an ENGINE = Memory oracle:

CREATE TABLE t (k UInt64) ENGINE = MergeTree ORDER BY k PARTITION BY k;
INSERT INTO t VALUES (1), (2);
SELECT k FROM t WHERE k NOT IN (SELECT '01') ORDER BY k;  -- returns 2; correct is 1, 2

Five other pairs behave the same way.

relaxed does not cover it: it only forbids trusting can_be_false, while four of the six prune through can_be_true and one is already relaxed. The atom is declined instead, by a type-level gate at the caller shaped like master's has rule (#115294): equals-equal types that also agree on custom names, plus two plain integers. equals alone is insufficient - Bool is equals-equal to UInt8 yet clamps nonzero values to 1.

Three consequences, none changing a row: declined pairs no longer prune (three plan tests re-recorded); a set empty only after NULL filtering is judged before its cardinality is known, reading one part instead of none; and 03991's GLOBAL IN now raises CANNOT_CONVERT_TYPE from the runtime cast instead of CANNOT_PARSE_TEXT from the set-side one (the code that query already returned unindexed).

Validation: 6 wrong-result cells (each 0 on pristine master), 5 keep-pruning controls (1 on both binaries) and 1 decline control (reddens on master); ~100 randomized runs per touched file, 10 for the long-tagged one, 0 failures; has tests byte-unchanged.

Two further exactness defects live in same-type pairs, admitted here as master admits them; both pre-existing, not fixed:

The two same-type residuals, measured

Float64 against Float64: a Field comparison treats -0.0 and +0.0 as equal (src/Core/CompareHelper.h), while set membership compares the bit patterns, so a NOT IN (0.0) atom prunes a part holding -0.0.

-- MergeTree with a minmax index on a Float64 key holding -0.0
SELECT k FROM mt WHERE k NOT IN (SELECT 0.0);        -- []      (Parts: 0/1)
SELECT k FROM memory WHERE k NOT IN (SELECT 0.0);    -- [-0.0]

NULL-aware membership against a narrower integer set: it uses a throwing accurate cast (castColumnAccurate, src/Interpreters/Set.cpp), so pruning the out-of-range part answers the query where the unindexed form raises CANNOT_CONVERT_TYPE.

-- UInt64 key holding 1 and 257, UInt8 set holding 1
SELECT k FROM mt WHERE k IN (SELECT 1::UInt8) SETTINGS transform_null_in = 1;  -- [1]
-- the same query with no usable key index: Code: 70, CANNOT_CONVERT_TYPE

Neither is reachable through the cross-type conversion this PR gates, and declining a same-type pair would remove pruning that is correct for every value except these, which is a different fix. The signed-zero family is reported in #117543, and #115970 is in flight on the same negative-zero mismatch; I have not measured whether it settles this repro.


Workflow [PR]
Sync PR [sync-upstream/pr/112966]

groeneai and others added 16 commits July 28, 2026 18:34
…t index

KeyCondition's set-index analysis casts the SET values into the KEY type when it
prepares the index, while runtime membership casts the KEY into the SET type. An
atom is only an exact image of the predicate when both directions preserve
equality; master checked neither, so a cast that merges or loses values produced
silent wrong results: rows disappeared with no error.

For example, 'String' -> 'UInt64' maps '01' to 1 without overflowing, so the
pruning set holds {1} while toUInt64(1) IN ('01') is false at runtime. After
negation the partition holding a matching row is pruned away:

    CREATE TABLE t (k UInt64) ENGINE = MergeTree ORDER BY k PARTITION BY k;
    INSERT INTO t VALUES (1), (2);
    SELECT k FROM t WHERE k NOT IN (SELECT '01') ORDER BY k;  -- returned only 2

The same asymmetry is reachable in the other direction, where a key that matches
at runtime is absent from the pruning set and the positive IN direction prunes a
live partition. That class cannot be repaired by relaxing the atom, because
relaxation only ever forces can_be_false and never widens can_be_true, so both
classes are declined instead.

Exactness is now derived from the strictness of the two casts that actually run
rather than from a list of type pairs: identical types (no conversion runs), or
two plain integers (an accurate cast takes the strict accurate::convertNumeric
path exactly when the source is int/uint/float, and that path yields NULL rather
than truncating). Everything else fails closed. Floats are excluded from the
cross-type case because that strictness argument does not cover values whose
equality differs between the two comparison engines, and a custom name over an
integer installs a wrapper that clamps values.

Declining costs index pruning for cross-type pairs that are correct today; they
now read more parts and return the same rows. 02882's reference moves because its
String-element query no longer participates in index analysis, which is the
intended consequence.
A set-index atom is used as an exact image of the predicate, but the two casts
that make it up run in opposite directions: index preparation casts the SET
values into the key type (castColumnAccurateOrNull(set -> key)), while runtime
membership casts the KEY into the set type (Set::execute). When the conversion
does not preserve equality, the pruning set is not the predicate's image.
String -> UInt64 maps '01' to 1 without producing a NULL, so the pruning set
holds {1} while toUInt64(1) IN ('01') is false at runtime; the atom is then a
SUPERSET of the predicate and NOT IN prunes away a partition that still holds a
matching row. A truncating Decimal(20,4) -> Decimal(10,2) is the mirror case:
the set UNDER-approximates and the positive IN over-prunes. relaxed cannot
repair either, because it only forces can_be_false and never widens can_be_true,
so such an atom has to be DECLINED rather than relaxed.

Exactness is now derived from the strictness of the two casts instead of from a
list of type pairs. setIndexConversionPreservesEquality admits exactly two cases
and fails closed on everything else:

  - identical types after removeNullable(recursiveRemoveLowCardinality(...)) on
    BOTH sides, compared by CANONICAL FULL TYPE NAME. getName() rather than
    equals() because numeric equals() ignores custom names, so Tuple(Bool) and
    Tuple(UInt8) would compare equal while the cast installs a wrapper that
    clamps every nonzero value to 1. The normalization is recursive and applied
    to both arguments: removeLowCardinality strips only the outer wrapper, and
    the caller already strips the key side recursively, so an outer-only or
    one-sided strip would decline an IDENTICAL nested-LowCardinality composite
    and silently lose pruning that works today.
  - both plain integers with no custom name. An accurate cast takes the strict
    accurate::convertNumeric path exactly when the source is int/uint/float
    (can_apply_accurate_cast), and that path yields NULL instead of truncating,
    so neither direction can merge two distinct values or lose precision.
    Requiring BOTH sides to be integers makes both sources numeric, hence both
    directions strict. Floats are excluded even though they satisfy the same
    condition: the strictness argument covers magnitude, not the values whose
    EQUALITY differs between the two engines that have to agree (the runtime Set
    hashes bitwise while MergeTreeSetIndex orders through FloatCompareHelper,
    which treats all NaNs as equal, and -0.0 equals +0.0). Enum is excluded
    because its cast source is not accepted by can_apply_accurate_cast, so
    Enum16('a'=257) lands as UInt8(1). Decimal is excluded because it is not in
    can_apply_accurate_cast either and TRUNCATES rather than NULLing.

Applying the predicate once, right after the set-transforming DAG and before the
canBeSafelyCast early exit, retires three separate unsound sites at once: the
early exit becomes unreachable for unproven pairs, the post-filter exactness
classification is unnecessary, and the NULL-drop becomes sound because a drop can
now only happen on a proven-exact pair, where NULL genuinely means the value is
not representable.

The same check also runs inside the transforming-DAG branch, on the ORIGINAL
element against the type the pre-DAG conversion actually TARGETED. That target is
reported by applyDeterministicDagToColumn through a new trailing defaulted
out-param rather than derived from the DAG's shape, because the direct-CAST fast
path can be structurally applicable and still fall through to the slow path on
the values. The report sits at the top of the function rather than inside the
existing !equals() branch: equals() ignores custom names, so a Bool input over a
UInt8 DAG input would skip that branch and report nothing although the DAG output
really differs (toString(true) is 'true', not '1'). Only the REPORT was added;
no execution condition was touched, so the helper's other caller, the scalar
equals/notEquals path, is behaviourally unchanged.

has needs one additional precondition. It never casts the key at runtime:
FunctionArrayIndex::executeConst compares Fields with accurateEquals, and
FieldVisitorAccurateEquals has no Tuple/Array arm, so a composite is compared as
ONE Field whose nested values match only by exact Field type. Field collapses
integer widths but not signedness, so a cross-signedness composite compares
UNEQUAL at runtime while the per-column arms, which see the UNPACKED scalars,
would admit it. compositeHasArgumentsHaveSameType therefore requires a composite
ARRAY ELEMENT to have the same type as the left expression. It is gated on the
element rather than on the key, because the key column's type is not the left
expression's type when the key expression transforms it: for
ORDER BY reverse(tuple(reverse(p), hex(p))) the key is a Tuple while the left
expression of has(['abc'], p) is a plain String, and gating on the key declined a
SCALAR has. IN does not get this precondition, since it casts the key, and
applying it there deletes sound cross-signedness pruning.

Declining costs pruning for cross-type pairs, so four reference files move.
02882, 03635 and 03733 pinned pruning that is measurably unsound: each returned a
wrong row count against an ENGINE = Memory oracle before this change
(02882/03635 [2] vs [1,2]; 03733's composite has 1 vs 2 packed and [2] vs [1,2]
through the unpacked two-column form). One block of 03762 is a pruning loss on a
shape that is correct today, because its key transform collapses the round-trip
pair the same way the element cast does; result-level output over all sixteen of
that file's own queries is byte-identical before and after.

Carriers were measured against an ENGINE = Memory oracle in both directions over
the numeric cross product rather than sampled, including the collapse regions,
Nullable and LowCardinality wrappers, packed and unpacked composites, and the
temporal, text, UUID, IPv4, Enum, Bool and Decimal families. Each element of the
rule was then proven load-bearing by mutation.
The identity arm of the set-index exactness predicate compared canonical
full type names. getName() prints parameterized attributes that
IDataType::equals deliberately treats as interchangeable: the time zone
of DateTime and DateTime64, and the precision of Decimal. Comparing names
therefore declined the very common shape of a key that declares a time
zone against a set element that does not, silently disabling primary-key,
partition and minmax pruning for those tables.

Decide identity with equals() plus a recursive check that both sides
agree on custom names. The custom-name half is a soundness need, not a
style choice: Bool is a DataTypeUInt8 carrying a custom name, so it is
equals-equal to a plain UInt8 while its cast wrapper clamps every nonzero
value to 1. A UInt8 key against a Bool set element is a wrong-results
carrier for exactly that reason, and it keeps declining. The check
recurses because container equals() recurses into elements, so
Tuple(Bool) and Tuple(UInt8) differ only in a nested custom name.

The custom-name signatures are compared as flat sequences, which is sound
only because the check runs after equals() has already guaranteed
identical tree shape and element order. DataTypeObject is the one
container that does not offer that guarantee (its equals matches
typed_paths by lookup while its forEachChild iterates an unordered map),
so it fails closed. JSON cannot reach a key expression today, so this
guards the assumption rather than a live path.

Parameters that equals does compare still decline: DateTime64 and Time64
scale, and a Decimal pair whose underlying type differs.

04549 gains a block covering the type-attribute axis. The test varied
type families exhaustively but never a parameterized attribute, which is
the axis this arm keys on, so nothing in it could observe the defect.
…s-type exactness on nullable elements

Test hardening:

- `enable_time_time64_type` is pinned with a session `SET`. Its default flipped
  false -> true in the 25.12 block of `SettingsChangesHistory.cpp`, and the stress
  runner injects `compatibility='<20..26>.<1..12>'`, so ~17% of stress runs revert
  it and the two `Time64` cells then fail to create their column with
  `ILLEGAL_COLUMN`. A session `SET` survives that, because the compatibility pass
  skips settings already changed manually; a per-statement `SETTINGS` clause would
  not reach the inner `CAST` of the `EXPLAIN` subqueries.
- `session_timezone` is pinned to `UTC` so the set elements that spell `DateTime`
  without a zone stop depending on the runner's timezone randomization, leaving the
  no-zone/zone pair as the discriminator by construction. No stored value changes,
  so the reference is unaffected.
- The comment above `setIndexTypeTreeHasStableChildOrder` credited `MergeTreeData`
  for rejecting `Object` from a key expression. The recursive gate is actually in
  `KeyDescription`; `MergeTreeData` throws the same code only for
  `DataTypeCustomSimpleAggregateFunction`.

Cross-type exactness for a nullable set element:

`castColumnAccurateOrNull` rewrites a source NULL to the nested default without
setting its own null map, so the prepared pruning set holds a value the predicate's
set does not. `IN` is only weakened by that, but `NOT IN` and `NOT has` are
strengthened, and an atom claimed to be an exact image of the predicate then prunes
a partition that still matches. Restrict such a pair to the `equals`-identity case,
where `castColumn` returns the argument unchanged and no rewrite can happen. The
predicate is `isNullableOrLowCardinalityNullable`, matching the null-stripping
branch below it: `isNullable` alone is false for `LowCardinality(Nullable(T))`,
which takes that branch and is a carrier too.

This half is incomplete and is being re-adjudicated: keying the decision on the
element TYPE also declines a positive `has` over an array literal containing NULL,
where the NULL cannot cause row loss, costing pruning on a correct shape
(`03733_has_function_key_condition_explain`). The hazard is whether a NULL survives
into the prepared set, which is not a type-level property at that point -- an `IN`
over the same values arrives non-nullable because `Set::setHeader` strips
nullability and drops NULL rows when `transform_null_in = 0`.
The previous round declined exactness whenever the set element type was
nullable. That test is both too weak and too strong.

Too weak: setIndexConversionPreservesEquality normalizes with
removeNullable, so Nullable(UInt8) against a UInt8 key reaches the
equals-identity arm and is blessed before any NULL reasoning runs. The
element still goes through castColumnAccurateOrNull, because
canBeSafelyCast requires the target to accept NULL, and the null-map
merge below consults only the null map the cast produced. A source NULL
therefore survives into the prepared set as the nested default, a value
the predicate's set does not contain. IN is only weakened by that, but
NOT IN and NOT has are strengthened, so such an atom prunes a partition
that still matches.

Too strong: a nullable KEY is sound. There canBeSafelyCast holds, plain
castColumn runs, the source NULL stays NULL and the prepared set is a
faithful image. Keying the decision on the element type declined those
shapes and silently cost pruning on correct queries.

Gate on the property the mechanism actually depends on instead: whether
the prepared column can still represent the source NULL. Concretely,
decline after the canBeSafelyCast early exit rather than before it, so
the sound path continues untouched and only the lossy path is refused.
The third parameter added last round is removed; it is replaced, not
weakened.

03733_has_function_key_condition_explain's reference moves because its
has([10, 50000, 90000, NULL, NULL], toUInt64(id + 2)) block pinned
pruning that is unsound in general. Its own fixture starts at 2 and so
never reaches the spurious element; running the same predicate over rows
that do reach it returns one row where an ENGINE = Memory oracle returns
two. The block is regenerated, not weakened.
…s() identity by type equality

Replaces the previous type-level guard, which declined before the null-map merge
and therefore made that merge unreachable.

The property that forfeits exactness is a value fact, not a type fact: an element
that was already NULL in the source is not filtered out (only cast-produced NULLs
are), so it survives into the prepared set as the nested default, a value the
predicate's set does not contain. That only weakens IN, but it strengthens NOT IN
and NOT has, so the atom is no longer an exact image of the predicate. Report it
from where the source null map is read and mark the atom relaxed, which keeps the
set index available for pruning while disarming the exact can_be_false path.

compositeHasArgumentsHaveSameType compared canonical names, which contradicted
the policy the scalar helper documents and rejected a key declaring a time zone
against an element that does not. Defer to the same identity notion instead:
equals, plus agreement on custom names and on a stable child order.

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

Two changes, both scoped to this PR's concern (cross-type set index exactness
for a non-Nullable source).

Drop the source-null-map relaxation. That mechanism belongs to the Nullable
source branch of the same function, which is fixed separately by
ClickHouse#111418; the two were
independently authored copies of one fix, character-identical at the write
site, so keeping both here would have left a maintainer resolving a conflict
between two of our own PRs. The six test cells that only pinned it are removed
with it and are asserted on that PR instead. The narrowness controls for the
surviving mechanism stay.

Relax composite has() identity from IDataType::equals to the notion the
runtime actually uses. FieldVisitorAccurateEquals has no Tuple/Array/Map arm,
so a composite element is compared as one Field through Field::operator==,
which rejects a differing Field::Types::Which and otherwise recurses.
Field::TypeToEnum maps every native integer width to a single variant per
signedness while UInt128/UInt256/Int128/Int256 keep their own, so two
composites that differ only in the width of a native integer are
indistinguishable to the runtime and the atom is still an exact image of the
predicate. Signedness, the 128/256-bit tags, tuple field names, container
shape and custom names all remain required: a name-differing tuple pair
reorders or zeroes values in the preparation cast, and Decimal/DateTime64/Time64
share one Field tag but the preparation cast truncates them, which is this
PR's own bug class. The tolerance is deliberately narrower than the scalar
path's, because a scalar is governed by the preparation cast and a composite
by Field identity.
The two 03733-shaped cells are width-only pairs the runtime compares
identically, but pruning is withdrawn for them by the per-column check rather
than by the composite identity rule: with a packed Tuple/Array key column the
unpack loop never runs, so that check receives the whole composite pair and is
exact only for an equals-equal or plain-integer one. Keep the assertions and
labels agreeing on that, and say which rule owns the outcome, so a later reader
does not read the label as claiming the opposite of the recorded value.
analyzeKeyExpressionForSetIndex records the type of the KEY column in
data_types, and it does so in both of its branches: the one that finds the key
directly and the one that reaches it through a deterministic transform. So
under a transforming key expression the recorded type is the type of the
transformed key, not of the runtime left tuple.

compositeHasArgumentsHaveSameType reconstructs the left expression's type from
data_types to decide whether a composite array element can match it, and it
declined a transforming DAG only in the packed single-argument shape. In the
unpacked multi-argument shape it compared the transformed key's type against
the element, which is the wrong pair. The atom is still exact there, because
only a non-injective transform relaxes it and negate is injective, so NOT has
could prune a partition that still held a match:

  CREATE TABLE mt (a UInt32, b UInt32) ENGINE = MergeTree
      ORDER BY (negate(a), negate(b)) PARTITION BY (negate(a), negate(b));
  INSERT INTO mt VALUES (1, 1), (2, 2);
  SELECT * FROM mt WHERE NOT has([tuple(toInt64(1), toInt64(1))], (a, b));
  -- returned (2,2); correct is (1,1) and (2,2), since the runtime Field
  -- comparison of a UInt32 pair against an Int64 pair is false for both rows.

Hoist the rejection so it covers both shapes: the left type is not
reconstructible from a transformed key in either of them.
The must-not-regress cell for a non-transforming composite key asserted only that
the set atom appears in the plan, plus result equality against a Memory oracle.
Both survive a relaxed atom: KeyCondition sets can_be_false when an element is
relaxed, immediately before the NOT_IN_SET negation, so a relaxed atom is still
installed and still prints "element set" while NOT has stops pruning entirely.
Relaxation only forfeits pruning, so the answer stays correct and the oracle cell
is blind to it by construction. An edit that relaxed instead of declining would
have passed the whole test.

Assert the part count instead. The fixture partitions by the key and inserts the
two rows separately, so an exact negated single-point set must read one part of
two. Parts is format-independent, so the existing explain_query_plan_default pin
covers it and no new setting is needed. Forcing the atom relaxed on the has path
now reddens the cell, while the previous predicate still passes.

Also drop a PR-relative phrase from a comment, which does not survive the merge.

Co-Authored-By: Claude Fable 5 <[email protected]>
…has() path

compositeHasArgumentsHaveSameType reconstructs the left expression's type in two
shapes. For an unpacked tuple(a, b) left expression it synthesizes the type with
the unnamed DataTypeTuple constructor, which auto-assigns the placeholder names
"1", "2", ... Both final comparators are outer-name-sensitive, so an element
whose real outer names are anything else could never match and the atom was
declined, losing sound pruning. Measured on a two-column key:

    has([CAST((1, 1), 'Tuple(c UInt8, d UInt8)')], (a, b))  ->  Parts: 2/2
    has([tuple(toUInt8(1), toUInt8(1))],           (a, b))  ->  Parts: 1/2

Both answers were already correct, so this was a lost optimization rather than a
wrong result. The outer names carry no meaning on that path: the unpack loop in
tryPrepareSetColumnsForIndex runs first and is purely positional, so only
per-scalar casts follow and no name-mapped tuple cast ever occurs, and runtime
has() compares Fields, which carry no names either.

Rebuild the element's outer layer with the same unnamed constructor on that
branch only, so both sides agree there while every nested element is compared
exactly as before. A nested name difference still declines, because there the
per-scalar cast is name-mapped and zeroes the value. An outer custom name is
reachable too (Point is a custom-named Tuple(Float64, Float64)) and is covered
by the same normalization. The packed branch is untouched: its left type is a
real key column with real names and the whole composite is cast by name there.

Adds 14 assertion cells to 04549 for a shape that had no coverage: the named and
custom-named outer element in both the has and NOT has directions, the matching
and differing nested name, and two cells bracketing the packed branch. The
reference diff is purely additive, so no pre-existing cell moves.

Note the packed outer names and the nested names are also enforced downstream by
setIndexConversionPreservesEquality in tryPrepareSetColumnsForIndex, so those two
properties hold with or without this function's own check.
…nested Nullable

The set index exactness gate is scalar-shaped, but for a packed Tuple/Array key the
unpack loop in tryPrepareSetColumnsForIndex never runs, so the gate receives the whole
composite. It then declined a pair differing only in native integer widths, because
IDataType::equals is false and a Tuple is not an integer.

That decline is required for IN, whose runtime casts the key into the set type with
castColumnAccurate and therefore throws CANNOT_CONVERT_TYPE on a narrowing composite.
It is not required for has, which casts nothing and compares Fields with accurateEquals,
a comparison that collapses native integer widths. Declining it there lost sound pruning
that master performed: four blocks of 03733_has_function_key_condition_explain went from
Granules 2-3/100 to 100/100 with unchanged results, so only the optimization was lost.

The tolerance is now selected by the caller through a parameter rather than by widening
the shared gate, so the IN path is unchanged and the narrowing composite it would throw
on is still declined there. setIndexTypesHaveSameFieldRepresentation also recurses
through a Nullable on either side, because a Nullable is not represented in a Field at
all: a non-NULL value carries the same variant as its plain counterpart, and the
preparation cast maps a NULL element to a NULL whole composite, which the existing
filter drops. setIndexTypesAgreeOnCustomNames skips a plain Nullable node so its two
flat forEachChild signatures stay aligned when one side wraps a nested element; a
custom-named Nullable is still noted, so a length mismatch then rejects.

03733's reference reverts to its master content entirely. The two 04549 cells that
asserted the decline now assert that pruning is kept, and cells were added for the four
restored shapes in both polarities, for the IN side of the same pair of types, and for
the signedness and 128-bit boundaries over a packed key.

Verified with three mutations, each reddening exactly its own cells: removing the
has-only tolerance moves the six packed-shape cells, giving that tolerance to IN as well
moves the IN cell and stops a serverError CANNOT_CONVERT_TYPE cell from throwing, and
dropping the Nullable recursion moves the four nested-Nullable cells.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The composite Field-identity rule recursed through a Nullable wrapper present on
only one side, justified by the whole-composite cast mapping a NULL element to a
NULL tuple that the caller then filters out. That justification holds for the
packed shape only, and the rule served both.

On the unpacked path tryPrepareSetColumnsForIndex splits the composite into
scalars before any conversion, so no whole-composite cast runs. Each scalar then
takes the nullable branch, which strips Nullable and reads the nested column; at
a source-NULL row that column holds the type default, so the per-scalar
castColumnAccurateOrNull produces no NULL and the row survives the filter. A
(NULL, NULL) element therefore entered the pruning set as the all-default tuple,
which runtime has() does not match because Types::Null matches nothing. With the
atom claimed exact, the negated form then pruned the real all-default part and
dropped a row.

Measured on a three-part table holding (10,0), (50000,0) and (0,0):
NOT has([(10,0),(50000,0),(NULL,NULL)], (a,b)) returned nothing where an
ENGINE = Memory oracle returned (0,0).

setIndexTypesHaveSameFieldRepresentation now takes a flag selecting how strict
the Nullable arm is. A wrapper present on both sides is still recursed through
unconditionally, since it is invisible to a Field comparison either way. A
one-sided wrapper is admitted only by the two packed callers, where the whole
composite really is cast; the unpacked caller declines it. Declining only ever
loses pruning, so both shapes stay correct.

Both one-sided packed directions were measured to keep their pruning and to agree
with the oracle, which is what makes the per-shape split load-bearing rather than
a blanket decline. Two has() controls that matched the atom's own plan text were
changed to assert the part reduction instead: a relaxed atom still prints that
text while its can_be_false is forced true before the negation, so the old
spelling could not tell the exact outcome from the relaxed one.

One in-tree cell in 03733_has_function_key_condition_explain carries the same
unpacked shape and loses its pruning. Its results were already correct on that
fixture, so only the plan changes; the reason is documented at the cell.
Three refinements to when a composite set-index atom may be treated as an
exact image of the predicate.

Tuple field names are only mapped by the preparation cast when BOTH sides
declare them: createTupleWrapper takes its name-matching branch under
from_type->hasExplicitNames() && to_type->hasExplicitNames() and otherwise
converts positionally. Comparing names when only one side is explicit
declined an atom that is equality-preserving in both directions.

    accurateCastOrNull(CAST(tuple(1),'Tuple(d UInt8)'),'Tuple(c UInt8)') = (0)
    accurateCastOrNull(CAST(tuple(1),'Tuple(d UInt8)'),'Tuple(UInt8)')   = (1)

The packed shape's tolerance for a one-sided Nullable rests on the whole
composite being cast by castColumnAccurateOrNull, so a NULL element nulls
the tuple and the caller's filter drops that set row. That aggregation
lives in createTupleWrapper and is top-level only; createArrayWrapper
rebuilds the array with its original offsets and leaves a nullable data
column nested. The tolerance therefore only reaches through Tuple nodes,
and the Array and Map arms now clear it. This also stops such a pair from
reaching that cast, which refuses rather than converts it: the target
validation rejects a nested type that cannot be inside Nullable, so a
Tuple(Array(UInt32), UInt32) key against a Tuple(Array(Nullable(UInt16)),
UInt8) element failed the whole query with ILLEGAL_TYPE_OF_ARGUMENT.

The unpacked shape's hazard is an actual source NULL rather than the
Nullable type. It converts each scalar after stripping the wrapper, and
the nested column holds the type default at a source-NULL row, so a
(NULL, NULL) element enters the pruning set as (0, 0). With no NULL in the
constant there is no such row and the conversion is value-preserving, so
the decision now inspects the values and keeps pruning; the inspection
fails closed on any column layout it does not recognize.

Every carrier is pinned in 04549 against an ENGINE = Memory oracle, in
both directions, including the controls that must still decline.
…uning

Three review items.

setIndexConstantHasNoNulls treated a column that reports isNullable() without
being a ColumnNullable as containing no NULL. That is the inverse of its
contract: isNullable() forwards through ColumnSparse, ColumnReplicated and
ColumnConst, so any such carrier would silently re-enable the exactness claim
behind the unpacked-composite one-sided Nullable tolerance and reintroduce the
dropped row this change exists to prevent. The disjunct is deleted, and a
Nothing column (the all-NULL case, which previously returned true incidentally
through canBeInsideNullable) now fails closed explicitly. Not exploitable at
this revision - the ColumnConst arm intercepts the only reachable case and
Sparse/Replicated do not reach getConstantColumn - so this is a latent
fail-open rather than a live bug, which the byte-identical test reference
confirms.

A relaxed atom keeps positive pruning while losing all negative pruning,
because can_be_false is forced true for any relaxed element. A keep-pruning
control that asserts only the has direction therefore stays green through a
regression that silently kills NOT has pruning. The V33, W33 (both shapes) and
Y33 controls now assert the negated direction too, with the part counts read
off the actual plan (3/4, 2/3, 2/3, 2/3 - three of the four differ from the
positive counterpart). W33 and Y33 additionally gain the NOT has
result-vs-oracle cell they lacked, so pruning is never pinned without also
pinning correctness. Each new plan cell was verified to redden under an
unconditional out.relaxed = true.

Finally, the two longest comment blocks are trimmed by 29% combined, dropping
derivation and a rationale that was stated at three sites down to one.
The `-- Non-safe cast` section of 03173_set_transformed_partition_pruning
queries `id IN (SELECT '50' UNION ALL SELECT '99')` over `PARTITION BY
xxHash32(id) % 3` with `id Int64`. The set elements are `String`, so the
element pre-converts to the DAG input type before the key expression is
applied, and `String -> Int64` is not equality-preserving: distinct source
values can collapse onto one key value.

Index preparation converts set values into the key type, while runtime
membership converts the key into the set's type. When the conversion is not
equality-preserving those two directions disagree, so the atom cannot be
treated as exact - not even for a positive IN. The set index therefore
declines to prune here, and SelectedParts moves 2 -> 3.

Only parts read change; count() is 2 in both arms, so no rows appear or
disappear. Measured with an isolated probe on both arms: an Int64 set over
the same table is unaffected (2 -> 2), confirming the decline is specific to
the non-equality-preserving String -> Int64 conversion.

Scoping the guard to the exactness-consuming NOT IN direction would restore
this parts count but would reintroduce a positive-IN silent wrong result
through the same pre-transform path (carrier Z2, pinned in this PR at
04549_keycondition_cross_type_set_exactness.reference:119-121): a
non-injective key over a String column with a numeric set loses a row.
Trading a correctness carrier for a parts-read count is not acceptable, so
the conservative decline stands.
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (16 rounds) - 67 findings agreed and fixed, 6 disagreed with evidence, 11 dropped

An independent reviewer read the resulting code cold (without the author's evidence), then a
second-model gate re-reviewed the full diff. That cycle ran 16 times before this PR was opened. Every
finding was adjudicated against measurements taken on two Build-ID-verified binaries: a pristine
master snapshot and this branch.

Two of the agreed blockers were collisions with my own open
#111418, which fixes the Nullable-source branch of the
same function. The overlapping mechanism was reverted out of this PR both times, so the two changes do
not pre-empt each other; the Nullable-source half is left entirely to that PR.

Agreed - fixed before this PR was opened

1. The identity test used type NAMES, which silently disabled pruning for parameterized types.
getName() prints attributes that equals() deliberately ignores: the time zone for DateTime /
DateTime64 (DataTypeDateTime.cpp states time zones are interchangeable), the precision for
Decimal. Measured: a DateTime('UTC') key against a DateTime element - the default shape whenever
the column declares a time zone and the set element does not - went from
Condition: (t in 1-element set) / Granules: 1/3 to Condition: true / Granules: 3/3, and under
PARTITION BY toYYYYMM(t) from a fully pruned read to Parts: 3/3. Results were correct throughout,
so this was pruning loss, not a wrong answer. castColumn short-circuits on equals(), so for an
equals()-equal pair both casts are no-ops and nothing can fail to preserve equality. The identity arm
now uses equals() plus a recursive custom-name-agreement check, which keeps the Bool-versus-UInt8
discrimination the rule needs (Bool is a DataTypeUInt8 carrying a custom name, so equals() alone
would admit it).

2. A composite has identity rule over-declined pairs the runtime matches. has casts nothing at
runtime and compares Fields with accurateEquals, which collapses native integer widths but not
signedness and not the 128/256-bit tags. A single scalar predicate therefore could not serve both
callers: IN casts the key INTO the set type with castColumnAccurate and genuinely throws
CANNOT_CONVERT_TYPE on a narrowing composite, while for has that throw is unreachable. The two
callers are now split by an explicit parameter rather than sharing one verdict, and the composite
tolerance is exactly what the Field comparison can see.

3. A nested Nullable on one side was declined on the TYPE, where the hazard is an actual NULL.
The unpacked shape splits the composite into scalars before converting, strips Nullable and reads the
nested column, whose value at a source-NULL row is the type default - so (NULL, NULL) would enter the
pruning set as (0, 0), which the runtime never matches, and negation would prune the real (0, 0)
part. Declining on the type alone also declined every NULL-FREE Nullable-typed element, where no such
row exists. The decline is now value-sensitive and fails closed on any column layout it cannot inspect.

4. The test matrix did not vary type attributes. The generated integer cross products contained no
explicit time zone at all, which is why a whole-class pruning regression initially passed the mutation
matrix, an in-tree sweep and two 50/50 runs. Attribute-axis controls were added and are pinned by a
dedicated mutation that reverts the identity arm to name comparison.

5. The sweep's base arm was an earlier revision of this branch, not pristine master. Because that
base already carried the change under test, one reference this PR turns red failed in BOTH arms and
cancelled out as pre-existing. Re-running with a pristine master base arm (171 tests per arm) surfaced
03173_set_transformed_partition_pruning: one SelectedParts cell, 2 -> 3. Row counts are identical
in both arms, so it is a pruning loss rather than a wrong result, and it is now disclosed in the
description with the other one. Scoping the new rule to NOT IN would recover it but reintroduce a
positive-IN wrong result through the same conversion path (pinned in the new test), so the loss is
accepted instead.

⚠️ Disagreed, with evidence

transform_null_in = 1 can suppress a CANNOT_CONVERT_TYPE exception. The mechanism is real but
is not this change's: the scenario reproduces byte-identically on pristine master. With
transform_null_in = 1, a UInt64 key holding 1, 257 and k IN (SELECT toUInt8(1)) returns 1 from
MergeTree on both binaries while an ENGINE = Memory oracle raises Code 70 on both, with an identical
message. Structurally it cannot be introduced here either - every statement this change adds to the
preparation path is a return false, so no atom is retained that master did not already retain. Its
real cause is that pruning changes which rows reach the runtime cast; that is tracked separately with a
measured repro, and whether it is a defect at all is an owner-level question. This change does improve
the composite half of that family, which now agrees with the oracle.

The exhaustive integer matrices are not live. The observation is accurate - those rows compare
results only - but mechanism liveness does not rest on them. The test carries 91 labelled
EXPLAIN indexes = 1 assertions outside the matrix ranges, including 28 pairs that assert the atom is
declined against 28 that assert it is retained, so neither widening nor narrowing the rule can pass
unnoticed, and each arm of
the rule has a mutation that reddens its own controls and leaves the others green. The matrices have a
different, stated job: proving the answer is correct across a generated rather than sampled cross
product, and pristine master fails several of those rows.

Scoping the new check to the NOT IN direction, to keep the two pruning losses. Refused with a
counter-carrier: ORDER BY length(s) over '1' and '01', then s IN (SELECT toUInt8(1)) returns
['1'] on pristine master against an ENGINE = Memory oracle's ['01','1'] - a positive-IN wrong
result through the very same pre-conversion path. Marking such an atom relaxed cannot rescue it either,
since relaxation only ever forces can_be_false and never widens can_be_true. A direction-scoped
check would trade that correctness carrier for a parts-read count.

💡 Noted, not blocking

Before the identity fix above, the same value pruned through has([...], t) and through
t IN (<literal>) but not through t IN (SELECT ...), because a literal array infers its element type
differently. The equals()-based identity test removes that divergence.

One helper fails closed on JSON/Object because its equals matches paths by lookup while its
forEachChild iterates an unordered map, so the walk order the signature comparison relies on is not
guaranteed. That path is currently unreachable - a key cannot hold JSON - so it is a guard against
the assumption breaking rather than a live branch, and it is commented as such.

A late round asked for the two new explanatory comments in KeyCondition.cpp to be condensed as
over-long. I disagreed: this file already carries 23 comment blocks of 12 or more consecutive comment
lines, 9 of them 26 lines or longer and the largest 50, and the neighbouring assumeNotNull relaxation
block walks concrete granule values the same way. Happy to trim them if a maintainer prefers a terser
house style here.

Session id: cron:clickhouse-review-slot-51:20260801-235700

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, no randomization or timing involved. CREATE TABLE t (k UInt64) ENGINE = MergeTree ORDER BY k PARTITION BY k; INSERT INTO t VALUES (1), (2); SELECT k FROM t WHERE k NOT IN (SELECT '01') returns 2 on master and 1, 2 with the fix. A second carrier: with ORDER BY (negate(a), negate(b)) PARTITION BY (negate(a), negate(b)) over (1,1)/(2,2), SELECT * FROM mt WHERE NOT has([tuple(toInt64(1), toInt64(1))], (a, b)) returned only (2,2).
b Root cause explained? Yes. Index preparation casts the SET into the key type while runtime membership casts the KEY into the set type, so when the conversion does not preserve equality the pruning set is not the predicate's image. String -> UInt64 maps '01' to 1 with no NULL, the set holds {1}, toUInt64(1) IN ('01') is false at runtime, and the negated atom prunes a partition that still holds a match. The mirror case (a truncating Decimal) under-approximates and over-prunes the positive IN.
c Fix matches root cause? Yes. Exactness is decided from the strictness of the two casts that actually run, at the single point where both final types are available. No widened bound, no no-random-* tag, no reduced dataset, no defensive check at the failure site. relaxed is deliberately NOT used: it only forces can_be_false and would leave every under-approximating carrier wrong.
d Test intent preserved / new tests added? Yes. New 04549_keycondition_cross_type_set_exactness (555-line reference; the 12x12 integer matrix and the 8x8 composite grids are generated, not thinned). The five moved pre-existing references were updated, never weakened or deleted, and every moved line is either a measured wrong-results carrier or one of the two disclosed pruning losses (03762, 03173). Nothing was made more permissive: where a decline assertion became a keep-pruning assertion, that decline was itself a regression, and every result-vs-ENGINE = Memory-oracle partner is unchanged.
e Both directions demonstrated? Yes. Both arms are built from one worktree by swapping only KeyCondition.cpp, whose pristine copy is byte-identical to the merge-base by md5sum (master fa749f31, fixed 2d0eb8a3). Aligning by assertion label rather than positionally - the pristine arm emits one extra bare 1 row, so a positional diff misreports - gives 85 of 528 cells differing: 82 of the 525 labels present in both arms, plus 3 counted separately because the pristine arm ABORTS on them (ILLEGAL_TYPE_OF_ARGUMENT), which is itself the both-directions proof for that shape. 0 only-in-master. The fixed arm passes every affected test and 250/250 with randomization ON. A later round re-ran the set-atom-observing sweep with a PRISTINE MASTER base arm (171 tests per arm, rather than an earlier revision of this branch) and that is what surfaced 03173: after its reference cell moved, nothing fails on the fix and passes on master. Each mutation reddens exactly its own guard and nothing else - eight in earlier rounds, and four this round: comparing tuple names unconditionally (3 cells), reverting the unpacked decline to type-only (1 cell), letting the Array arm thread the tolerance again (the shape throws again, aborting the run), and passing false from the packed caller (1 cell, proving the tolerance is still load-bearing after being narrowed). Every run used a server whose SELECT lower(buildId()) was verified equal to readelf -n on the binary - the guard actually fired once this session on a stale server holding the slot port - and every mutated build was restored bit-identically (the restored build reproduced its Build ID exactly).
f Fix is general across code paths? Yes. One predicate governs both callers of tryPrepareSetColumnsForIndex (tryPrepareSetIndexForIn and tryPrepareSetIndexForHas; exactly two by git grep) and both wrapper branches, since it unwraps internally. All three unsound sites collapse into one early decline. Where the two callers legitimately differ they are split explicitly by a parameter rather than by a shared verdict, because IN casts the key at runtime (castColumnAccurate, which throws on a narrowing composite) while has compares raw Fields and casts nothing; both of the predicate's call sites inside tryPrepareSetColumnsForIndex receive the same per-caller value, so a transforming key expression cannot take a different tolerance than a plain one. The composite identity helpers have no callers outside this file, and their only other caller is has-only, so that half cannot reach the IN path. The sibling KV pushdown consumer has the same defect and is tracked separately under the one-concern rule.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, over generated matrices rather than samples: the full 12x12 integer cross product (288 assertions), 8 collapse-region boundary values, 10 identical-type pairs, Nullable element mirrors, a Nullable key, 8x8 packed integer composites in plain and Nullable form (128 result assertions), and nested-LowCardinality composite controls. Normalization is recursive and applied to BOTH sides, because an outer-only strip would silently disable pruning for the whole nested-LowCardinality family. Added axes the matrices did not vary: type ATTRIBUTES (DateTime/DateTime64 time zones and Decimal precision, which equals treats as interchangeable and so must stay exact, each paired with the neighbouring parameter equals DOES compare and which must still decline, plus Bool over UInt8); ACTUAL NULLs (every earlier Nullable control passed a non-NULL value through the wrapper) for NOT IN, NOT IN under transform_null_in = 1, NOT has and their LowCardinality(Nullable(T)) forms; the CONVERSION PATH, which is what the mechanism actually depends on rather than the element's type; tuple NAMES, arity, and the Array/Map shapes; and the per-caller axis (IN vs has) on one pair of types. Composite coverage spans a packed Tuple, a packed Array, an unpacked multi-column key and a nested Nullable on one side only, with signedness, 128-bit, Decimal scale and DateTime64 scale as the must-still-decline boundary.
h Backward compatible? Yes. No new setting, no default change, no serialization change, so no SettingsChangesHistory.cpp entry applies. Declining an index optimization is always safe (FUNCTION_UNKNOWN then a full scan). Results become more correct; some cross-type pairs read more parts, which the PR body states.
i Invariants and contracts preserved? Yes. Every predicate added is pure, total and fails closed, and the guard sits exactly where the lossy conversion path is entered, so the sound canBeSafelyCast path continues before reaching it and keeps pruning (verified by keep-pruning controls, two of which a type-level gate had regressed). Both the equals arm and the has-only composite arm carry the same stable-child-order (Object fail-closed) and custom-name conjuncts, so a Bool-style custom name over an integer still rejects. The new out-param on applyDeterministicDagToColumn is trailing and defaulted and only the REPORT was added, so its other caller is behaviourally unchanged (a k != true control asserts this). out.relaxed is untouched and both callers keep their signatures. The transforming-key rejection also only declines: negate is injective, so such an atom was EXACT rather than relaxed. A numbers() control pins extractPlainRanges' exact-range fast path, which a newly relaxed atom would have silently disabled: this is why unproven pairs are declined rather than relaxed.

Session id: cron:clickhouse-impl-slot-45:20260801-153200

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @tiandiwonder, could you review this? A set-index atom is treated as an exact image of the predicate, but index preparation casts the set values into the key type while runtime membership casts the key into the set type, so a conversion that does not preserve equality (String -> UInt64 mapping '01' to 1) builds a pruning set that is not that image and NOT IN drops a live part; exactness is now decided from the strictness of both casts. It also withdraws sound pruning in two disclosed cases, which the description explains.

The comments this branch added were far too verbose: 262 comment lines against 214 lines of
code, with individual blocks running 10-20 lines. They accumulated over the review rounds,
because each round answered a question by writing the justification into the source instead of
into the commit message, and nothing ever removed one. Per the repo style, a code comment states
the local invariant that is not obvious at the call site; motivation, measurements and rejected
alternatives belong in the commit message and the PR description.

Comment-only change: the code is token-identical, the two call sites are merely rewrapped after
gaining a /*composite_field_identity_is_enough=*/ argument comment.

The reasoning removed from the source, kept here:

* Field-level equality is what a composite has() actually uses. FieldVisitorAccurateEquals has
  no Tuple/Array/Map arm, so a composite element is compared as one Field, and Field::operator==
  rejects a differing Field::Types::Which outright. Field::TypeToEnum collapses every native
  integer width into one variant per signedness while UInt128/UInt256/Int128/Int256 each keep
  their own, so this tolerance is narrower than the scalar path's, and the two must not be
  unified:
      has([toUInt64(5)],        toUInt128(5))         = 1   scalar,    native vs 128-bit
      has([tuple(toUInt64(5))], tuple(toUInt128(5)))  = 0   composite, native vs 128-bit
      has([toUInt8(5)],         toUInt64(5))          = 1   scalar,    native width-only
      has([tuple(toUInt8(5))],  tuple(toUInt64(5)))   = 1   composite, native width-only
  Signedness is likewise not collapsed. Decimal/DateTime64/Time64 share the Types::Decimal64 tag
  and do match at runtime, but stay excluded because their preparation cast truncates rather than
  nulling: accurateCastOrNull(DateTime64(6) '...00.123456', 'DateTime64(3)') is '...00.123'.

* Tuple field names are mapped by the preparation cast only when both sides declare them
  explicitly. createTupleWrapper takes its name-matching branch under
  from_type->hasExplicitNames() && to_type->hasExplicitNames() and otherwise converts
  positionally:
      accurateCastOrNull(CAST(tuple(1), 'Tuple(d UInt8)'), 'Tuple(c UInt8)') = (0)  both explicit
      accurateCastOrNull(CAST(tuple(1), 'Tuple(d UInt8)'), 'Tuple(UInt8)')   = (1)  one-sided
      accurateCastOrNull(CAST(tuple(1), 'Tuple(UInt8)'),   'Tuple(c UInt8)') = (1)  one-sided
  So comparing names on a one-sided pair would decline a sound atom.

* The one-sided Nullable tolerance stops below a container because the whole-composite cast's
  null aggregation lives in createTupleWrapper and is top-level only, while createArrayWrapper
  rebuilds the array with its original offsets and leaves a nullable data column nested.
  Declining also keeps such a pair away from that cast, which rejects it rather than converting
  it: validateNestedTypesForAccurateCastOrNull walks Tuple elements and refuses a nested type
  that cannot be inside Nullable, so a Tuple(Array(UInt32), UInt32) key against a
  Tuple(Array(Nullable(UInt16)), UInt8) element used to fail the query with
  ILLEGAL_TYPE_OF_ARGUMENT.

* The packed shape tolerates a one-sided wrapper because a NULL element nulls the whole tuple and
  that set row is filtered out: a Tuple(UInt32, UInt32) key against
  [(10, 0), (50000, 0), (NULL, NULL)] reports a 2-element set and agrees with an ENGINE = Memory
  oracle for both has and NOT has. The unpacked shape cannot, because it splits the composite
  into scalars before any conversion, so stripping Nullable substitutes the nested column, whose
  value at a source-NULL row is the type default: (NULL, NULL) would enter the pruning set as
  (0, 0), which runtime has does not match. Hence the value-level setIndexConstantHasNoNulls
  check rather than a type-level decline.

* setIndexTypesAgreeOnCustomNames is only ever called on two trees already known to share a
  shape and child order, which is what makes its two single-type walks correspond. Object is
  excluded because its equals matches typed_paths by lookup while its forEachChild iterates an
  unordered map. JSON/Object cannot reach a key expression today (KeyDescription rejects it with
  DATA_TYPE_CANNOT_BE_USED_IN_KEY), so that guard protects the assumption rather than a live path.

* setIndexConstantHasNoNulls does not accept nullability as evidence: isNullable() forwards
  through ColumnSparse, ColumnReplicated and ColumnConst, so using it would invert the contract.
  ColumnNothing is the all-NULL case and fails closed despite reporting canBeInsideNullable;
  Variant/Dynamic carry a NULL discriminator inline and fall through to the same closed default.

* The unpacked branch rebuilds only the element's outer tuple layer with the unnamed ctor,
  because left_type is synthesized there and its outer names are the placeholders "1", "2", ...
  Nested layers stay untouched, where a name difference does still decline: there the per-scalar
  cast is name-mapped and zeroes the value.
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [34b5b20]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
Test script failed FAIL cidb
UndefinedBehaviorSanitizer: undefined behavior (STID: 3593-560a) FAIL cidb

AI Review

Summary

This PR tightens KeyCondition's set-index exactness checks so lossy cross-type IN / NOT IN conversions fall back to scanning instead of building exact pruning atoms. The main direction is correct, but one previously reported wrong-result carrier is still live on transformed DateTime / DateTime64 keys, so I cannot approve the change as-is.

Findings

❌ Blockers

  • [dismissed by author -- https://github.com/Fix rows silently dropped by IN and NOT IN index analysis over a cross-type constant set #112966#discussion_r3698179132] [src/Storages/MergeTree/KeyCondition.cpp:2221-2240, 3019-3021; tests/queries/0_stateless/05180_keycondition_cross_type_in_set_exactness.sql:124-132] Transformed DateTime / DateTime64 keys are still treated as exact across attribute-mismatched pairs. areTypesCompatibleForInSetIndex accepts a plain DateTime element against a DateTime('UTC') key because equals() ignores time zones, and convertColumnForDeterministicDag then skips the pre-DAG cast on the same equals() check. For keys such as PARTITION BY toYYYYMM(ts), that means the set element is transformed in session_timezone instead of the key column's timezone, so the pruning set can still diverge from runtime IN and silently drop matching rows. The new control in 05180 only covers the bare-key case, so this transformed carrier is still untested. Suggested fix: force the pre-DAG cast whenever the transform input types differ in observable attributes, or decline transformed pairs on that axis until the cast path is fixed.
Final Verdict

❌ Changes requested. The cross-type guard improves the plain-key path, but the transformed-DateTime / DateTime64 wrong-result carrier reported earlier still exists in the current code.

LLVM Coverage Report

Measured on commit 34b5b20.

Metric Baseline Current Δ
Lines 89.00% 89.10% +0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 52/56 (92.86%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 2, 2026
`03991_set_variant_low_cardinality_in_global_in` expected `CANNOT_PARSE_TEXT`, which
only ever appeared because key index analysis dragged the set values through its
preparation cast: `castColumnAccurateOrNull` parsed `'not a number'` as `Int128` and
threw out of `tryPrepareSetColumnsForIndex`. Even `EXPLAIN indexes = 1` of the query
failed that way.

The same query returns `CANNOT_CONVERT_TYPE` from the runtime membership cast whenever
no usable key index is involved, measured on unmodified master with `ENGINE = Memory`,
with `ORDER BY tuple()` and with `ORDER BY id`. So that is the engine-independent
result, and the parse error was index analysis leaking a set-preparation failure into
a query that does not depend on the index.

Now that a non-equality-preserving cross-type cast no longer counts as exact, the atom
is declined before that cast runs and the query reports the runtime error on every
table shape. Verified with stderr instrumentation that the set column still reaches
`tryPrepareSetColumnsForIndex` and is refused by the exactness guard with
`key=Int128 set=Variant(LowCardinality(FixedString(12)), LowCardinality(UInt8))`.

The crossover is measured in both directions: reverting this expectation reddens the
test on the fixed binary, and the new expectation reddens it on a pristine master
binary.
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

PR-caused Fast test red on 03991_set_variant_low_cardinality_in_global_in, fixed in b0bd5cc

That test is not mine and is byte-identical to master's copy, so I treated the red as a
regression of this PR and checked which error code is actually correct before touching it.

Reproduced in two arms locally (both buildId-guarded): FAIL on this branch's binary
(expected 6, got 70), OK on a pristine master binary.

Which code is right, measured on the unmodified master binary by taking the key index
out of the picture:

shape (pristine master) result
ENGINE = Memory CANNOT_CONVERT_TYPE (70)
ENGINE = MergeTree ORDER BY tuple() CANNOT_CONVERT_TYPE (70)
ENGINE = MergeTree ORDER BY id CANNOT_CONVERT_TYPE (70)
ENGINE = MergeTree ORDER BY (id, value) (the test's shape) CANNOT_PARSE_TEXT (6)

So 70 is the engine-independent result, and the 6 appeared only when a usable key index
dragged the set values through index preparation: master's stack raises it inside
tryPrepareSetColumnsForIndex via castColumnAccurateOrNull parsing 'not a number' as
Int128. On master even EXPLAIN indexes = 1 of this query fails that way, which is index
analysis leaking a set-preparation failure into a query that does not depend on the index.
With this PR the atom is declined before that cast, so the query reports the runtime error
on every table shape.

I did not want to just move the number to match new behavior, so I checked the test is not
left vacuous. With stderr instrumentation the set column still reaches
tryPrepareSetColumnsForIndex and is refused by the exactness guard with
key=Int128 set=Variant(LowCardinality(FixedString(12)), LowCardinality(UInt8)). Worth
disclosing: a Variant set element can no longer pass that guard at all, because a
Variant/Dynamic/JSON column is rejected in a key expression outright
(DATA_TYPE_CANNOT_BE_USED_IN_KEY), so the original #97854 cast-region defect is now
unreachable through the key-index path by construction rather than by the column/type
symmetry cf8f288f restored. The other call sites from that commit keep their own tests.

The crossover is measured in both directions: reverting the expectation reddens the test on
the fixed binary, and the new expectation reddens it on a pristine master binary.

Finish Workflow / Post Hooks was the same root cause, not a second defect: every per-arch
Bugfix validation job is skipped/DROPPED at that commit because the Fast test red
short-circuited the workflow, so new_tests_check.py found nothing that validated the bug.

Session id: cron:clickhouse-maint-slot-16:20260802-021800

The new test 04549_keycondition_cross_type_set_exactness failed the flaky
check on all four sanitizer arms with "Test runs too long (> 180s)" and, on
the debug and asan arms, the 600s hard kill.

It is not a hang and not a sanitizer effect. The failing job's own
query_log shows every killed run reached ~1280 of the test's 1475 statements
and accumulated ~516s of query time, with a slowest single query of 4.0s.
The cost is per-statement overhead multiplied by statement count: in that
job a DROP TABLE averaged 73ms and a scalar SELECT 701ms, against 0.1ms and
9.6ms locally, because the flaky check runs 8 concurrent copies of the test
(nproc-1 workers, --test-runs 50) on a 9-core runner. Confirmations: the
amd_debug parallel job takes 18.6s, matching a local single run at 18.5s;
replaying the failing run's exact 186-setting randomized vector locally
takes 16s.

So the only lever that acts on the failure without touching an oracle is
statement count per test file. This commit is a pure relocation. Every
banner, label, predicate and assertion moves byte-for-byte; no cell is
dropped, no oracle weakened, no expectation adjusted. Sections, and the
per-key-type blocks inside the two generated grids, are distributed across
04549 and the new 04552-04558 by measured cost. A block that reads a table
it does not create is kept with its producer, so every emitted file is
self-contained.

Verified: the concatenated references contain all 555 original assertion
lines with none lost, differing from the original only by the 6 section
banners that a divided section necessarily repeats in each file that
carries its rows. Total server queries fall from 1475 to 1263. Under a
local emulation of the CI shape (9 cores, 8 concurrent copies) the worst
file takes 4.8s against the monolith's 27s, which scales to about 82s
against the 180s budget. Run against an unmodified master binary, 7 of the
8 files fail as they must; the eighth holds only the control grids, whose
208 cells assert agreement with the oracle and pass on master by design.
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Flaky-check timeout on the new test: fixed by splitting it, not by weakening it

04549_keycondition_cross_type_set_exactness failed the flaky check on all four sanitizer arms
(Reason: Test runs too long (> 180s), and the 600s hard kill on debug and asan). It is not a hang
and not a sanitizer effect.

The failing job's own query_log settles it: each killed run reached ~1280 of the test's 1475
statements and accumulated ~516s of query time, with a slowest single query of 4.0s. The cost is
per-statement overhead times statement count. In that job a DROP TABLE averaged 73ms and a scalar
SELECT 701ms, against 0.1ms and 9.6ms locally, because the flaky check runs 8 concurrent copies of
the test (nproc-1 workers, --test-runs 50) on a 9-core runner; its query_log shows 7-8 concurrent
copies for 425 of the 655 observed seconds.

Two cross-checks that the environment, not the test's content, is the variable: Stateless tests (amd_debug, parallel) takes 18.6s and a local single run takes 18.5s; replaying the failing run's
exact 186-setting randomized vector locally takes 16s.

So the only lever that acts on this without touching an oracle is statement count per file, and the
change is a pure relocation into 04549 plus 04552-04558. Every banner, label, predicate and
assertion moves byte-for-byte: no cell dropped, no oracle weakened, no expectation adjusted.
Sections, and the per-key-type blocks inside the two generated grids, are distributed by measured
cost; a block that reads a table it does not create stays with its producer, so each file is
self-contained.

Verified:

  • the concatenated references hold all 555 original assertion lines with none lost (528
    assertion cells, unchanged), differing only by the 6 section banners a divided section necessarily
    repeats in each file carrying its rows;
  • total server queries fall from 1475 to 1263;
  • under a local emulation of the CI shape (9 cores, 8 concurrent copies, real runner) the worst file
    takes 4.8s against the monolith's 27s, and all 48 runs pass; that scales to about 82s
    against the 180s budget;
  • against an unmodified master binary 7 of the 8 files fail, as they must. The eighth holds only
    the control grids, whose 208 cells assert agreement with the oracle and so pass on master by
    design.

I also corrected the validation block in the description, which still described the suite as a single
test.

@nihalzp nihalzp self-assigned this Aug 2, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Outdated
/// Compare by name, not by `equals`: `equals` ignores custom names, and a custom name changes the
/// DAG output (`toString(true)` is `'true'`, not `'1'`). The fast path below refines this.
if (out_conversion_target)
*out_conversion_target = input_type->getName() == dag.input_type->getName() ? nullptr : dag.input_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.

out_conversion_target notices the getName() mismatch here, but the actual pre-DAG cast is still skipped later whenever input_type->equals(*dag.input_type) is true. That is not safe for transformed DateTime / DateTime64 keys: equals ignores the time zone, while DAGs such as toYYYYMM and toString still observe it. With a key like PARTITION BY toYYYYMM(ts) on ts DateTime('UTC'), a plain DateTime set element will be transformed in session_timezone instead of UTC, so the pruning set can still diverge from runtime IN even though setIndexConversionPreservesEquality accepts the pair. I think we need to force the pre-DAG cast for these attribute differences, or decline transformed pairs on that axis.

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 mechanism is right and I reproduced it, but it is pre-existing on master rather than
introduced here, so I am fixing it in a separate PR instead of this one.

Your exact shape, PARTITION BY toYYYYMM(ts) on ts DateTime('UTC') with a plain DateTime
element and a non-UTC session_timezone:

SET session_timezone = 'Asia/Kolkata';
CREATE TABLE t (ts DateTime('UTC')) ENGINE = MergeTree PARTITION BY toYYYYMM(ts) ORDER BY tuple();
INSERT INTO t SELECT toDateTime(1675195200,'UTC');
SELECT count() FROM (SELECT ts FROM t WHERE ts IN (SELECT toDateTime(1675195200)));  -- 0, wrong
-- ENGINE = Memory oracle on the same data returns 1
arm ELF Build ID MergeTree Memory oracle
pristine master 90042b2dc118b00 c5efc69a3aa8b163 0 1
this PR at 0356aecfcab939c 15283bde8a594796 0 1

Byte-identical on both arms. The arms are genuinely distinct binaries: strings -a finds
setIndexConversionPreservesEquality 0 times in the master binary and 3 times in this one.

toYYYYMM on that instant is 202302 under the session timezone and 202301 under the key's,
the row lives in 202301, and pruning drops the only part holding it. Controls that isolate the
axis, all measured on both arms: an element carrying the key timezone is correct, session_timezone = 'UTC' is correct, dropping PARTITION BY is correct, and toUnixTimestamp(ts) IN (...) (no set
index) is correct. So the row-level IN is fine and only the pruning path is wrong. It also
reproduces on the scale axis, key DateTime64(3,'UTC') versus element DateTime64(3).

Two reasons it is not this PR's regression. :2344 is db245dcc84bb839 (2026-02-23) and this
PR's diff does not touch it, and every statement this PR adds to the preparation path is a
return false, so it can only retain fewer atoms than master, never more.

I filed it separately with the repro and controls above, and it needs a design decision rather
than a quick guard: forcing the pre-DAG cast keeps pruning but has to target the key's attribute
and contend with castColumnAccurateOrNull on the runtime side, whereas declining the pair is
sound but loses pruning for any column that declares a timezone against a bare DateTime
element, which is a common shape. Your first option is the one I will try first.

Separately, you are right that the attribute axis is untested. 04549 and its split siblings
vary type families exhaustively but never a type attribute, which is why no mutation here can
expose this. Attribute-axis carriers belong with the fix, as wrong-results carriers rather than
pruning deltas.

… budget

The 04556 and 04557 parts of the 04549 family still exceeded the flaky check's
180s per-test soft budget on the asan_ubsan arm at the previous head: median
181.5s / max 212.3s for 04556 and 180.5s for 04557, while the same files ran
clean on tsan (max 106.4s) and msan (max 73.8s) across 50 runs each. The earlier
balancing used non-sanitizer measurements, so it under-provisioned the arm that
actually binds.

Each of the two files is cut once at a CREATE TABLE boundary into a new part
(04559, 04562). Both cut points were verified table-independent in each
direction, so every part remains self-contained. This is a pure relocation: no
assertion cell is dropped, no oracle weakened and no expectation adjusted. The
concatenated references contain every original line (528 assertion cells across
the family, unchanged); the only additions are the section banner each divided
section necessarily repeats and its blank line.

Measured on a real 9-core runner emulating the CI shape (8 concurrent copies of
one file, the same shape the flaky check uses), same harness and same binary
before and after: 04556 3.75s -> 2.09s and 04557 3.45s -> 1.59s worst run, with
the new parts at 2.09s and 2.39s. Scaling by the arm's own measured local-to-CI
factor projects every part between 75s and 125s against the 180s budget. All 60
runs across the ten files pass.

Seven of the ten files fail on a pristine master binary, as they must. The three
that pass hold only agreement controls, whose cells assert that MergeTree matches
the ENGINE = Memory oracle and therefore hold on both binaries by design. Their
cells were confirmed live rather than vacuous by mutating one cell of each and
observing the file redden.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e427e4e

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
Upgrade check (amd_release) / Unknown job error + Check failed infra: get_previous_release_tag died on a GitHub API 504 (/repos/ClickHouse/ClickHouse/releases), so no test_results.tsv was written and 0 tests ran #112974 (mine, open)

The three Bugfix validation (functional tests, amd64/aarch64) rows for 04556, 04557 and
04559 are not failures. A test_status=FAIL under check_status=success on that check is the
expected inversion: the new regression tests correctly fail against the pre-fix binary, which is
what the check exists to demonstrate.

The Upgrade check red is not caused by this PR. tests/ci/build_download_helper.py:121 raised
APIException: Unable to request data from GH API after four attempts against
api.github.com/repos/ClickHouse/ClickHouse/releases (one read timeout, then three 504s), so the
job aborted before starting a server. #112974 rewrites exactly that function to back off
exponentially on 5xx and other transient statuses, which is this failure mode. It is open, so per
the ledger rules I link it rather than opening anything new. Over the last three days the same
job-level Upgrade check error hit 13 different pull requests by several authors.

Session id: cron:our-pr-ci-monitor:20260824-210000

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Dear @nihalzp, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@nihalzp nihalzp self-assigned this Sep 2, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
Master landed its own `has`-path set-index exactness rule (ClickHouse#115294, ClickHouse#116381):
`areTypesCompatibleForHasSetIndex` + `areSetAndKeyTypesCompatibleForHas`, called
from `tryPrepareSetIndexForHas`, plus the `Variant`/`Dynamic` in-use-alternatives
recovery `narrowVariantToOccupiedAlternatives`. That supersedes this branch's
`has` half, which reached the same property through a
`composite_field_identity_is_enough` flag inside `tryPrepareSetColumnsForIndex`.

Keeping both would be their conjunction, so it would silently narrow decisions
taken under review: master admits an `Enum8` element against an `Int8` key and
prunes it exactly (its comment cites `00674_has_array_enum`), which this
branch's rule declines. Taking "ours" in the conflicted region would delete
`narrowVariantToOccupiedAlternatives` outright.

So `src/` is reset to master's content verbatim here, together with the six
existing test files this branch had re-recorded for the `has` rule. The `IN`
half, which master has not fixed and which still drops rows, is re-applied on
top in a later commit.
10 files / 4074 lines / 548 assertion rows, written when this branch fixed both
the `IN` and the `has` path. Roughly a third of those rows assert `has`
behaviour that master now owns and records differently, and the numbers
`04549`-`04562` have since been taken by other tests on master, so the files
also collide.

They are replaced by a single file covering one case per scenario.
Index analysis builds an exact set atom out of constants it converted into the
key column's type, while runtime `IN` membership converts the key into the set
element's type. When those two conversions are not mutual, the atom names key
values the predicate does not match and misses ones it does, so single-point key
range pruning (partition pruning and minmax) drops the part holding a matching
row and the row silently disappears.

`tryPrepareSetColumnsForIndex` casts each element with `castColumnAccurateOrNull`
and drops only the elements whose cast produced NULL; whatever survives is
treated as exact. A conversion that succeeds without preserving equality was
never considered. Measured on master, against an `ENGINE = Memory` table holding
the same rows:

  UInt64 key,  k NOT IN (SELECT '01')                    -> [2]         vs [1,2]
  String key,  s IN (SELECT 1)          rows '01','1'    -> ['1']       vs ['01','1']
  String key,  PARTITION BY length(s), s IN (SELECT 1)   -> ['1']       vs ['01','1']
  UInt8 key,   k IN (SELECT CAST(5, 'Bool'))             -> [1]         vs [1,5]
  String key,  k NOT IN (a Variant(String, UInt8))       -> ['4']       vs ['3','4']
  (String, UInt64) key, (a, b) IN (SELECT (1, 1))        -> [('1',1)]   vs both rows

Marking the atom relaxed does not fix this: `relaxed` only forbids trusting
`can_be_false`, and four of the six cases prune through `can_be_true` instead -
the `PARTITION BY length(s)` case is an atom master already marks relaxed. So the
atom is declined outright, and the check is deliberately not gated on
`!out.relaxed` the way the `has` sibling is.

The rule mirrors the one master merged for `has` in ClickHouse#115294 and ClickHouse#116381: a
type-level gate at the caller, before the columns are prepared. It admits two
shapes, both sides first normalized with
`removeNullable(recursiveRemoveLowCardinality(...))`: `equals`-equal types that
also agree on custom names, and two plain integers. `equals` alone is not enough
because `Bool` is `equals`-equal to `UInt8` yet clamps every nonzero value to 1;
`getName()` equality is too strict in the other direction, since it would decline
a `DateTime('UTC')` element against a `DateTime('Europe/Moscow')` key, a pair that
prunes correctly today because a time zone is display metadata no `Field` carries.

It is narrower than `areTypesCompatibleForHasSetIndex` on purpose: that one also
admits `Enum`/native-integer, `Nothing` and container pairs, which are sound for a
raw `Field` comparison but not once `IN` casts the key into the set type, where a
narrowing conversion throws rather than nulling.

Rejected alternatives: gating on polarity (a pair can be unsound in either
direction, so it would need a directional injectivity analysis per type pair);
reusing the `has` predicate verbatim (strictly less safe here); a value-level
round-trip probe (catches the first case, but not the ones where the element
round-trips and a different key value collides with it).

The type-unpacking loop is extracted into `unpackSetTypesToKeyArity` and shared
with the `has` path; returning false where the arity is unreachable preserves that
caller's behaviour exactly.
`05180_keycondition_cross_type_in_set_exactness` covers one case per scenario:
the four conversion shapes that dropped rows (`equals`-unequal scalars in both
polarities, a non-injective key transform, a custom name over an integer, a
`Variant` element) and the multi-column arm, each comparing a partitioned
MergeTree against a Memory table holding the same rows. Four controls assert
that pairs whose conversion does preserve equality still prune exactly, so an
over-broad rule would fail the file too. Verified in both directions: every
asserting cell prints 0 on a pristine-master binary while all four controls
still print 1, so the flip belongs to this change and not to the file.

Re-recorded, one line each:

- `02882_primary_key_index_in_function_different_types`: two of four cells lose
  the `value in 1-element set` atom, a `UInt64` key against a `String` element.
  Same parts and granules read; only the atom and search algorithm change.
- `03173_set_transformed_partition_pruning`: "Non-safe cast" reads 3 parts
  instead of 2. That is the transformed-constant case, an `Int64` transform input
  against a `String` element, which returned a wrong row before.
- `03635_in_function_different_types_many_columns`: all four cells decline a
  `String` element against a `UInt64` key. Two of them held a set that was empty
  after NULL filtering and so pruned every part; those now read one part and the
  runtime filter rejects the rows instead. Results are unchanged in all four.
- `03991_set_variant_low_cardinality_in_global_in`: the error code moves from
  `CANNOT_PARSE_TEXT` to `CANNOT_CONVERT_TYPE`, because the failing conversion is
  now the runtime one rather than the index-preparation one. The same query over a
  table with no usable key index already returned `CANNOT_CONVERT_TYPE`, so the
  code no longer depends on whether a key exists. The behaviour the test was
  written for, no `LOGICAL_ERROR` from issue ClickHouse#97854, is unchanged.

Master's `has` tests are byte-unchanged: `00674_has_array_enum`,
`03733_has_function_key_condition_explain`, `03762_has_in_function_key_condition_`
`deterministic_function_chain_explain`, `03778_deterministic_injective_functions_`
`key_condition_rewrite_has`, `03916_has_to_in`, `04509_not_has_function` and
`04510_not_has_function_explain` all pass unmodified.
Both are comment-only; the gate's logic is byte-identical.

The doc comment claimed the rule fails closed "floats included". It does not:
the first arm admits `Float64` against `Float64` because they are `equals`-equal,
and that pair can still drop a row. `CompareHelper` treats `-0.0` and `0.0` as
equal while set membership compares bit patterns, so a `NOT IN (0.0)` atom prunes
a part holding `-0.0`. That is a different root cause, the `Field`-versus-`Set`
equality mismatch, and same-type float pruning is correct for every other value,
so the claim is deleted rather than the arm narrowed.

The integer arm said an accurate cast "yields NULL rather than truncating". That
describes `castColumnAccurateOrNull` only. For a NULL-aware operator (`nullIn`,
`notNullIn` and the `global` spellings, all routed through this call site)
`Set::executeImpl` selects the throwing `castColumnAccurate`, so the key-side
cast raises instead of yielding NULL. The property that actually carries the arm
holds for both flavours: an accurate cast never truncates, so it cannot
manufacture a false match.
Every cell in `05180` was scalar or top-level, so both recursive steps in the
type check were unmutated: replacing the `forEachChild` custom-name signature
with a top-level check, or `recursiveRemoveLowCardinality` with an outer-only
strip, left the whole file green. Two composite cells close that.

`Tuple(UInt8)` key against a `Tuple(Bool)` element asserts the decline. Only the
recursive signature reaches it, because `DataTypeTuple::equals` ignores custom
names, so the pair is `equals`-equal and a top-level check admits it. Measured on
a pristine-master binary the atom is built and prunes to `Parts: 1/3`, so the
cell reddens there.

It asserts the decline rather than a dropped row because no row is dropped: a
nested `Bool` relabels the element without clamping the stored integer, unlike a
top-level `Bool` cast. `CAST(tuple(5), 'Tuple(Bool)')` keeps 5 underneath and
renders it `(true)`, while `CAST(5, 'Bool')` stores 1. Both conversion directions
are therefore lossless for this pair and master's answer is already correct,
which is why the cell also pins the answer against the Memory oracle, unchanged
on both binaries.

`Tuple(LowCardinality(String))` key against a `Tuple(String)` element is the
keep-pruning half. An outer-only strip leaves `LowCardinality(String)` against
`String`, which are not `equals`-equal, so it would decline an identical
composite; the recursive strip keeps `Parts: 1/2` on both binaries.

50/50 randomized runs pass. The four re-recorded reference files are untouched.
@groeneai groeneai changed the title Do not treat a non-equality-preserving cross-type cast as an exact set index Fix rows silently dropped by IN and NOT IN index analysis over a cross-type constant set Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

This push adds two composite cells to 05180 and corrects two claims in the gate's comments. The code is unchanged: KeyCondition.cpp.o recompiles byte-identical. Both recursive steps of the type check are now mutation-covered, so a top-level-only custom-name check, or an outer-only LowCardinality strip, each reddens a cell.

One question I would rather a maintainer settled than guess at. The gate declines the atom in both unsound directions, though only one of them needs a decline: for a UInt64 key against a String element the key-to-set cast is injective, so can_be_true pruning stays sound and only NOT IN is wrong, whereas the reverse direction is unsound through can_be_true as well (05180 pins both). Taking the strict action for both is what costs 02882, 03173 and 03635 their pruning, including two 03635 cells that used to prune the whole part. Splitting the verdict into exact / relaxed-only / decline would recover most of that, at the price of a second axis in the rule. I kept the strict form because it cannot be wrong; say the word and I will narrow it.

Internal second-model review

An independent review plus an automated second-model gate, adjudicated against measurements on two Build-ID-verified binaries: 9 agreed, 1 disagreed, 1 dropped. This is the last fix round for this PR, so the items below are disclosed rather than fixed.

⚠️ Two exactness defects live in same-type pairs: Float64 signed zero, and NULL-aware membership against a narrower integer set. Both are in the collapsed part of the description with runnable repros. The decisive point for this PR: the change only ever restricts what index analysis admits, so every pair it still admits behaves exactly as it does on master today and neither defect can be introduced here. Owned by #117543 and by the in-flight #115970.

💡 Nothing on the element side is admitted by the has rule and declined by this one. Pruning-only, on k IN (SELECT NULL); left alone rather than widening a rule in a final round.

💡 The Nullable skip inside the custom-name signature cannot fire, since the arm is already guarded by equals. Harmless, and not worth a source edit at this point.

❌ Disagreed with one of my own findings: I read the "10 runs for the long-tagged file" claim in the description as stale. It is not. 03173 carries -- Tags: ... long ..., and the run log shows 5 runs per batch for it against 50 for each of the other four files.

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tiandiwonder @Fgrtue, could you review this? Index analysis casts the IN set into the key type while runtime membership casts the key into the set type, so a String element against a UInt64 key builds an atom naming different key values than the predicate matches, and single-point range pruning then drops a matching row. The fix declines the atom for such pairs, which is why the cross-type pruning in 02882 and 03635 is re-recorded.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 42e6d96

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
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) / 05055_unknown_profile_event_in_trace_list SYSTEM FLUSH LOGS trace_log hit the hardcoded 180 s SystemLogQueue<TraceLogElement>::waitFlush timeout under coverage instrumentation (test 184.01 s vs a 180 s flush budget); the test's own assertions all passed a fix task is created (investigating at full effort - fixing PR link to follow on this PR)
CH Inc sync - CH Inc sync (private, not actionable by me)

Mergeable Check and PR are aggregators of the row above, not independent failures.

Two notes for anyone reading this job's report, since both are misleading as it stands.

First, the report shows 1 node and 0 test rows, and CIDB has no test rows at this head for this check.
The run actually completed (All tests have finished, No queries hung, 13,834/13,834 executed) and then
exited 1 on the single failure, but the results TSV was never written
(Failed to get start time for [Tests]), so the 05055 failure and ~13,700 passes are absent from
system.checks. The failure above was recovered from the job log, not from CIDB.

Second, the tail of that log is a
Too much memory has been allocated without checking for memory limits: 2.2412358224391937 GiB advisory.
That is not the failure: at tests/clickhouse-test:6944 it is a bare print that never sets exit_code,
5,989 CIDB rows carry the same message on passing checks (0.93-5.56 GiB), and master reports the
byte-identical figure while passing.

This PR's diff is src/Storages/MergeTree/KeyCondition.cpp plus test files, with no contact with
trace_log, ProfileEvents, SystemLog, MemoryTracker or Allocator.

Session id: cron:our-pr-ci-monitor:20260910-040059

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 05055_unknown_profile_event_in_trace_list trace_log flush timeout on amd_llvm_coverage: #119187

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 14, 2026
A packed `Tuple` key holding a sub-second `DateTime64` element against a
`Nullable` set of `DateTime` elements: `Set::execute` drops the sub-second rows
only for a top-level `DateTime64` key column, while a tuple element is
truncated to the second, so `('2020-01-01 00:00:01.1000', 1)` matches the set
value `('2020-01-01 00:00:01', 1)` but the index pruned its part.

A transformed key (`ORDER BY cityHash64(d)`) against a `Nullable` set: the
collapse check never saw the conversion that decides membership, which casts
the column the transform reads (`Decimal(10, 4)`) into the set's type
(`Nullable(Decimal(10, 2))`). 1.2345 matches 1.23 at runtime, while the hash
set held only `cityHash64(1.2300)`.

Both reported by the clickhouse-gh review (r4265080699, r4265080708). The
non-Nullable shapes take the `canBeSafelyCast` fast path, which ClickHouse#112966
targets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Dear @nihalzp, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

const auto & compared_type
= set_transforming_dags[index].has_value() ? set_transforming_dags[index]->input_type : key_types[index];

if (!areTypesCompatibleForInSetIndex(set_types[set_element_index], compared_type))

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.

About your decision comment. The direction of the cast determines if a pair is unsafe.
Two cases here from the top of my mind:

  • Numeric key, String set element: the runtime cast key → String is the canonical toString. If toString(k) == s, then parse(s) == k. So the index set is a superset of the true matches: can_be_true is sound and only can_be_false (used by NOT IN) is not. Setting out.relaxed = true covers that case.
  • String key, numeric set element: this direction does under-approximate ('01' matches 1 at runtime, but toString(1) is '1'), so declining is required.

So what about adding a "relaxed-only" outcome when the set element is String and the key is an integer, Date, Date32, DateTime, UUID, IPv4 or IPv6. But keep declining in the other direction?

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.

Master has had this split since #118957 (merged 2026-10-09): a set element whose cast into the key type does not read back as itself makes the atom relaxed, and a non-String element over a String key does not use the index. On master 927e545c, 5 of the 6 wrong-result cells of this PR's 05180 already pass, NOT IN (SELECT '01') included.

DateTime cannot be relaxed-only, though: in a zone with a DST fall-back two keys format to the same string, so the index set is not a superset. Same result on master, 26.8 and 26.3:

CREATE TABLE dt (k DateTime('America/New_York')) ENGINE = MergeTree ORDER BY k PARTITION BY k;
INSERT INTO dt VALUES (toDateTime('2026-11-01 05:30:00', 'UTC')), (toDateTime('2026-11-01 06:30:00', 'UTC'));
SELECT count() FROM dt WHERE k IN (SELECT '2026-11-01 01:30:00'); -- 1, a full scan gives 2

Date32 has the same problem for an out-of-range stored value (e.g. inserted via RowBinary), which formats saturated.

The cell still failing on master is the UInt8 key with a Bool element (k IN (SELECT CAST(5, 'Bool')) returns [1], a full scan [1, 5]). My other open PR #112890 covers all of this: it does not use the index when the key-to-set cast can merge keys, recursing into Tuple/Array/Map, and for a String element it keeps your list except DateTime and Date32. With its src/ change applied to 927e545c, all 6 wrong-result cells of 05180 and both repros above return the full-scan answer.

So this PR is redundant now. Shall I close it in favor of #112890?

const WhichDataType key_which(key_type);
const WhichDataType set_which(set_type);

const bool both_integers = (key_which.isInt() || key_which.isUInt()) && (set_which.isInt() || set_which.isUInt());

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.

The integer rule does not look inside Tuple, unlike the has rule.

For example: a packed Tuple key: Tuple(UInt64, UInt64) vs Tuple(UInt8, UInt64) is not equals-equal; so it is declined, though element-wise both pairs are exact integers.

areTypesCompatibleForHasSetIndex recurses into Tuple/Array/Map. Other pairs where both casts are exact are also declined: Enum vs native integer (which the has rule admits); Date vs Date32, Decimal32 vs Decimal64 at the same scale, IPv4 vs UInt32.

Failing closed is acceptable. However, the comment says the rule is "shaped like master's has rule", which is misleading. Either recurse for integers inside Tuple, or state the narrower scope in the comment.

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.

Agreed, the comment overstates it. Moot if this PR closes (see the first thread): the whitelist goes away, and #112890's check is element-wise inside Tuple, Array and Map.

for (size_t index = 0; index < indexes_mapping.size(); ++index)
{
const auto set_element_index = indexes_mapping[index].tuple_index;
if (set_element_index >= set_types.size())

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.

A guard returns true, which is fail-open, contradicting "everything not admitted fails closed".

set_element_index >= set_types.size() returns "compatible". tryPrepareSetColumnsForIndex then indexes set_types[set_element_index] with no bounds check. This case is unreachable now, so this copies the has sibling without being harmful. We must use return false or chassert, so a future change to the mapping fails closed instead of reading out of bounds.

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.

Agreed. Moot if this PR closes, since #112890 adds no such guard. The has sibling on master keeps the same return true; I can make it fail closed in a separate PR if you want.

@Ergus

Ergus commented Oct 22, 2026

Copy link
Copy Markdown
Member

Superseded by #112890

@Ergus Ergus closed this Oct 22, 2026
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 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 comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants