Repository navigation
Conversation
…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.
Internal second-model review (16 rounds) - 67 findings agreed and fixed, 6 disagreed with evidence, 11 droppedAn independent reviewer read the resulting code cold (without the author's evidence), then a Two of the agreed blockers were collisions with my own open Agreed - fixed before this PR was opened1. The identity test used type NAMES, which silently disabled pruning for parameterized types. 2. A composite 3. A nested 4. The test matrix did not vary type attributes. The generated integer cross products contained no 5. The sweep's base arm was an earlier revision of this branch, not pristine master. Because that
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-45:20260801-153200 |
|
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 ( |
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.
|
Workflow [PR], commit [34b5b20] Summary: ❌
AI ReviewSummaryThis PR tightens Findings❌ Blockers
Final Verdict❌ Changes requested. The cross-type guard improves the plain-key path, but the transformed- LLVM Coverage ReportMeasured on commit 34b5b20.
Changed lines: Changed C/C++ lines covered: 52/56 (92.86%) · Uncovered code |
`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.
PR-caused
|
| 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.
Flaky-check timeout on the new test: fixed by splitting it, not by weakening it
The failing job's own Two cross-checks that the environment, not the test's content, is the variable: So the only lever that acts on this without touching an oracle is statement count per file, and the Verified:
I also corrected the validation block in the description, which still described the suite as a single |
| /// 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - e427e4eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The three The Upgrade check red is not caused by this PR. Session id: cron:our-pr-ci-monitor:20260824-210000 |
|
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. |
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.
IN and NOT IN index analysis over a cross-type constant set
|
This push adds two composite cells to 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 Internal second-model reviewAn 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.
💡 💡 The ❌ Disagreed with one of my own findings: I read the "10 runs for the |
|
cc @tiandiwonder @Fgrtue, could you review this? Index analysis casts the |
CI finish ledger - 42e6d96Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
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. Second, the tail of that log is a This PR's diff is Session id: cron:our-pr-ci-monitor:20260910-040059 |
|
Fixing PR for the |
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]>
|
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)) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 2Date32 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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Superseded by #112890 |
Related: #112890
Related: #115294
Related: #118899
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
INandNOT INsilently returning fewer rows when the constant set's element type and the key column type do not convert into each other reversibly, for example aStringset element against aUInt64key. 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
INmembership 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 anENGINE = Memoryoracle:Five other pairs behave the same way.
relaxeddoes not cover it: it only forbids trustingcan_be_false, while four of the six prune throughcan_be_trueand one is already relaxed. The atom is declined instead, by a type-level gate at the caller shaped like master'shasrule (#115294):equals-equal types that also agree on custom names, plus two plain integers.equalsalone is insufficient -Boolisequals-equal toUInt8yet 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'sGLOBAL INnow raisesCANNOT_CONVERT_TYPEfrom the runtime cast instead ofCANNOT_PARSE_TEXTfrom the set-side one (the code that query already returned unindexed).Validation: 6 wrong-result cells (each
0on pristine master), 5 keep-pruning controls (1on both binaries) and 1 decline control (reddens on master); ~100 randomized runs per touched file, 10 for thelong-tagged one, 0 failures;hastests 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
Float64againstFloat64: aFieldcomparison treats-0.0and+0.0as equal (src/Core/CompareHelper.h), while set membership compares the bit patterns, so aNOT IN (0.0)atom prunes a part holding-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 raisesCANNOT_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]