Skip to content

Fix index analysis skipping rows for IN with a set whose type is coarser than the key - #112890

Open
groeneai wants to merge 39 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111418-explain-tests
Open

groeneai wants to merge 39 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111418-explain-tests

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124823
Related: #117318
Related: #96225

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 wrong results when IN or NOT IN compares a primary key, partition key, minmax skip index or statistics column with a subquery whose type is coarser than the column, for example a DateTime key with IN (SELECT toDate(...)), a coarser DateTime64 or Decimal scale, or an integer key against a Bool, Date or Enum subquery; the same holds for a Nullable set under transform_null_in = 1. The index no longer uses a set unless converting the key to the set's type keeps distinct key values apart. Closes #124823.

Description

On 26.8.21.12, over t (d DateTime) ORDER BY d holding 2023-02-01 12:00:01 and 2023-02-03 13:00:00, SELECT count() FROM t WHERE d IN (SELECT toDate('2023-02-01')) returns 0 instead of 1, and NOT IN returns 2 instead of 1 (#124823). The AST fuzzer's TLP oracle found the same: report.

Set::execute casts the key into the set's type, while KeyCondition casts the set into the key type. When the first cast merges distinct keys (DateTime into Date, a smaller DateTime64 or Decimal scale), the index holds one point per element and prunes rows that are members.

tryPrepareSetColumnsForIndex now uses an IN set only when keyToSetConversionMayCollapse knows the key's cast keeps values apart: the same type, integers and floats (not into Bool), a number (not Bool), Enum, Date, UUID or IP into String, date/time and Decimal widenings, an Enum into a type holding all its values, Dynamic, a Variant holding the key's type, IPv4 with UInt32, UInt64 or IPv6 and IPv6 with UInt128 (either way), and element-wise Tuple/Array or an array of pairs into Map. Float sets over a Decimal, DateTime64 or Time64 key are left to floatValuesMissKeyValues.

Cost: other sets stop pruning, also where a key expression absorbs the collapse (PARTITION BY toYYYYMM(ts), ts IN (SELECT date)), and for key and set pairs such as Date and DateTime (a time zone can skip a day), DateTime64 and DateTime (the cast saturates), Date32 and String, or an integer and a Decimal. 05331 and 03991 now expect the full-scan result, not the index's own error; 05339 no longer forces the primary key for a coarser Decimal set. #117318 covers the same defect in bloom_filter.

Validated by the new 05403_in_subquery_set_coarser_than_key (primary and partition keys, minmax skip index, statistics, the fuzzer's shape and each collapsing set type; each fails without this change) and 04545_transform_null_in_non_nullable_key.


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

groeneai and others added 10 commits July 22, 2026 15:48
…ubquery

canBeSafelyCast(Nullable(X), T) wrongly returned true when T is a
non-Nullable String (and, via element recursion, Array/Map/Tuple).
A Nullable source cannot be safely cast to a non-Nullable target: a
NULL value has no representation there, so a strict cast throws
CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN (error 349).

This surfaced in MergeTree KeyCondition set-index analysis
(tryPrepareSetColumnsForIndex): for a query like

  SELECT s FROM t WHERE s IN (SELECT s FROM t UNION ALL SELECT NULL)
  SETTINGS transform_null_in = 1

with t(s String) ORDER BY s, the subquery set element type is
Nullable(String) and the key type is String. canBeSafelyCast returned
true, so the code took the strict castColumn branch and threw 349 on
the NULL element instead of the NULL-safe castColumnAccurateOrNull
fallback. Int64 was unaffected because Nullable(Int64) -> Int64 already
returned false and used the correct fallback.

Fix in the predicate so all callers route a Nullable-source /
non-Nullable-target cast through their NULL-safe path: the Nullable case
returns false unless the target is also Nullable. The LowCardinality
case recurses against removeLowCardinality(to_type) so it keeps the
target's Nullable wrapper (LowCardinality(Nullable(X)) -> Nullable(X)
stays exact and set-index pruning is preserved).

The NULL-safe fallback keeps a NULL set element as the key's nested
default. That set is a subset of the original, which weakens IN and,
after negation, strengthens NOT IN, so single-point key ranges
(partition pruning, minmax) could be pruned away incorrectly. Example:
`s NOT IN (SELECT 'a' UNION ALL SELECT NULL)` on `t(s String) ORDER BY s
PARTITION BY s` dropped the '' row. tryPrepareSetColumnsForIndex now
reports set_is_relaxed only when it retains such an approximated NULL
element (not when a cast-produced NULL is filtered out, which keeps the
set exact), and both callers (IN and has) mark the atom relaxed so
checkInRange() does not return an exact can_be_false for a single-point
range. This also fixes the pre-existing same bug for
Nullable(Int64) -> Int64 NOT IN pruning.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The NOT IN / NOT has cases checked only query results, which still pass if
tryPrepareSetColumnsForIndex declines and the engine full-scans. Add an
EXPLAIN indexes = 1 assertion for each negated case proving KeyCondition
builds a 'notIn ... set' atom (a declined path yields 'Condition: true',
which the ILIKE misses), so the relaxed set-index path is exercised, not
just correct results.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
An earlier revision of this PR marked a set-index atom relaxed whenever the
source set column contained a NULL, which disables exact NOT IN / NOT has
partition and minmax pruning even when the pruning set is still exact.
clickhouse-gh[bot] reported that this over-relaxes.

Fix the cause rather than labelling it. When the source set element type is
outer-Nullable and the key type is not, tryPrepareSetColumnsForIndex hands over
the nested column, so a source-NULL position carried the key type's default ('',
0) and the shared row filter kept it. That injected a value the query never
wrote into the pruning set, weakening IN and, after negation, strengthening
NOT IN, so a single-point key range could be pruned away and a legitimate row
disappeared:

    CREATE TABLE t_np (s String) ENGINE = MergeTree ORDER BY s PARTITION BY s;
    INSERT INTO t_np VALUES ('a'), ('b'), ('');
    SELECT s FROM t_np WHERE s NOT IN (SELECT 'a' UNION ALL SELECT NULL)
        ORDER BY s SETTINGS transform_null_in = 1;
    -- returned only 'b'; the '' row was pruned away

Drop the source-NULL row instead, and remove the relaxation plumbing entirely,
so the helper returns to its previous signature and both callers return to their
previous single relaxation condition. The net change against master is one
condition.

Dropping the row is result-neutral because a top-level source NULL can never
match a key that reaches this block: the key's outer type is never Nullable
there (the function returns early when canBeInsideNullable is false, and
recursiveRemoveLowCardinality preserves Nullable), and Set::executeImplCase
short-circuits NULL probe rows regardless. Row dropping keeps every set column
aligned because one shared filter is applied to all of them.

This also affects the positive IN direction, where the set becomes smaller while
staying exact and results are unchanged. Two lines of
03733_has_function_key_condition_explain.reference move accordingly; the
Tuple(Nullable, Nullable) key and the bare Nullable key cases in that file are
unchanged, since a tuple-typed set element is outer-non-Nullable and a Nullable
key does not reach this block.

Extend 04545_transform_null_in_non_nullable_key with the pruning behaviour:
String, Int64 and cross-type UInt64 keys against a Nullable(String) source, the
NOT has sibling caller, a LowCardinality(Nullable(String)) source, a
multi-column set with one NULL component, an all-NULL source producing an empty
set, the positive IN direction, and two cases that must not change. Each case
asserts the query result and, through EXPLAIN indexes = 1, the set size and the
pruned part count.
Index preparation casts set values into the key column's type, while runtime
`IN` membership casts the key into the set's type. `castColumnAccurateOrNull`
only proves that no value overflowed, not that the conversion preserves
equality: `String -> UInt64` maps `'01'` to `1` even though
`toUInt64(1) IN (CAST('01', 'Nullable(String)'))` is false. A set built that
way is a superset image of the predicate, so after negation
`NOT IN` / `NOT has` could prune a partition that still holds matching rows.

Replace the previous revision's presence-based relaxation with a check on the
conversion itself: the atom stays exact only when `canBeSafelyCast` accepts the
source-to-key conversion, and an empty set is exact by construction. Same-type
and safely-widening conversions therefore keep exact partition and minmax
pruning, which is what the bot review asked for, while the cross-type case that
motivated it is relaxed instead of silently dropping rows.

Also strengthen three assertions in `04545` that did not pin what their
comments claimed: the `LowCardinality` recursion in `canBeSafelyCast` is now
pinned through the `has` caller, which is the only shape whose array element
type keeps its `LowCardinality` wrapper and therefore reaches that branch; the
duplicate-key-mapping case asserts the set condition is present rather than
only that nothing was pruned; and the `Tuple(Nullable, Nullable)` case pins its
plan and not only its values.

`04545` now carries `no-parallel-replicas`, `no-replicated-database` and
`no-random-merge-tree-settings` plus `explain_query_plan_default = 'legacy'`,
because its assertions read the local MergeTree read plan. Against a real
three-replica cluster, removing the tag makes the test fail on 56 lines.
`tryPrepareSetColumnsForIndex` builds ONE row filter that is applied to every set
column only after the per-column loop has finished, but the "is this set an exact
image of the predicate" decision was taken inside that loop, from the filter as it
stood at that moment. For a multi-column set a later column's failed cast can
therefore remove the last row that was still surviving when an earlier column
marked the conversion approximate, leaving the final pruning set EMPTY while the
atom stays relaxed.

An empty set is exact by construction: `NOT IN ()` is universally true and `IN ()`
universally false, and both `extractPlainRanges` and `MergeTreeSetIndex`
special-case size 0 before consulting `relaxed`. Marking it relaxed loses pruning
on exactly the two paths the empty-set exclusion exists to protect: a strict
`PartitionPruner` is switched off entirely, and `extractPlainRanges` bails before
reaching its own size-0 handling. The shipped comment also asserted an invariant
the code did not hold for that shape.

Move the emptiness half of the decision after the shared filter, keeping only the
"this column's conversion is not equality-preserving" fact in the loop. Harm was
missed pruning, never a wrong answer.

Regression coverage: a new case in
`04545_transform_null_in_non_nullable_key` builds a two-column numeric key where
the first component takes a non-equality-preserving `String -> UInt64` conversion
and the second component's cast fails, so the set empties only after the shared
filter. Because an empty set and a relaxed set print identical part counts, the
case is pinned on the trivial-count optimization that a strict `PartitionPruner`
switches off for a relaxed condition, together with a relaxed non-empty control
proving the assertion is not vacuously true.
Index preparation casts set values INTO the key type, while runtime
membership in Set::execute casts the KEY into the set's type with
castColumnAccurate. The exactness gate only checked the first direction,
so a String key against a numeric Nullable source was declared exact:
canBeSafelyCast(UInt8, String) is true via the UInt branch's String
escape. At runtime both '01' and '1' cast to 1 and match, while the
pruning set built the other way holds only the canonical '1', so the set
under-approximates the predicate and the positive IN prunes a partition
that still holds a matching row. With rows '01', '1', '2' the query
returned only '1' where an ENGINE = Memory twin returns '01' and '1'.

Relaxation cannot repair this. All six consumers of the relaxed flag
only force can_be_false = true and never widen can_be_true, so an
under-approximating IN atom still prunes. Such an atom now declines the
set index entirely.

Only conversions that can collapse two distinct keys onto one set value
SILENTLY are rejected. Same-family numeric narrowing cannot:
castColumnAccurate refuses an out-of-range value rather than truncating
it, so it is injective on the domain it accepts and the query fails
loudly instead of answering from a collapsed set. That keeps exact
pruning for shapes such as a UInt64 key against a Nullable(UInt32)
source, which an earlier attempt at this gate wrongly declined. The two
conversions that do collapse silently are a text key against a non-text
set element, and a key whose Decimal, DateTime64 or Time64 scale is
finer than the set element's.

Also correct the empty-set comment. It claimed that extractPlainRanges
and MergeTreeSetIndex both special-case size 0 before consulting
relaxed. Neither does: extractPlainRanges returns on a relaxed atom at
the top of its loop, before it can reach its size-0 branches, and
MergeTreeSetIndex::checkInRange has no size-0 case at all. The comment
now states the requirement that an empty set must stay exact.
The set-index exactness gate classified only two collapse shapes, and it
declined only when the forward set-to-key cast was already classified safe.
Both limits let a collapsing conversion be treated as exact or as merely
relaxed, and relaxation cannot help: it only ever forces can_be_false and
never widens can_be_true, so the positive IN direction still prunes a
partition whose rows match the predicate at runtime.

Three gaps, each a measured wrong result against an ENGINE = Memory oracle:

  - The text arm exempted every text-vs-text pair. String and FixedString(N)
    do not share a value representation: the runtime cast of the key into
    FixedString(N) right-pads with '\0' while building the set casts
    FixedString(N) into String trimming trailing zeros, so 'a' and 'a\0'
    collapse onto one set value. A String key against a
    Nullable(FixedString(2)) set element lost a matching row, and before this
    branch that query threw CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN, so the
    exemption turned a loud error into a silently wrong answer. Both
    FixedString width directions were affected too. The comparison path in
    this file already declines the same padding class.

  - The decline was gated on canBeSafelyCast(set -> key), which is false for
    DateTime64 -> DateTime64 and for unequal-width FixedString, so a detected
    collapse short-circuited into a relaxation. A DateTime64(4) key against a
    Nullable(DateTime64(2)) set element lost a matching row. The Decimal arm
    of the identical family was already declined, purely because
    canBeSafelyCast happens to be true for Decimal scale widening; the same
    mechanism now gets the same disposition regardless.

  - The predicate tested only the top-level type while its counterpart
    canBeSafelyCast recurses through Tuple, Array and Map. A
    Tuple(String, UInt64) key against a
    Nullable(Tuple(FixedString(2), UInt64)) set element collapsed on its first
    element and lost a row. Matching composites are now walked elementwise; a
    shape mismatch is not itself a collapse and is left to canBeSafelyCast.

LowCardinality and Nullable are stripped on both sides so the recursive calls
compare unwrapped types.

Six cases added to 04545: the four collapse carriers plus two controls
proving identical text types and identical composite element types still
build an exact set and prune, so the gate is not repaired by declining every
text or composite pair. No existing reference line moves.
The reverse-collapse classifier required BOTH the key and the set element to
report a Decimal scale, so `tryGetDecimalScale` returning nothing for an integer
or float set element short-circuited the test and the atom was left relaxed but
live. Relaxation only forces `can_be_false`, so the positive `IN` direction kept
pruning and dropped rows that match at runtime.

Two branches of `DecimalUtils::convertToImpl` reach that case and lose
information for different reasons, so they get separate tests. The integer
branch takes the whole part, i.e. integer division by the scale multiplier, and
therefore only collapses when the key scale is above zero: at scale zero the
division is the identity and the conversion stays injective. The float branch
divides in Float64 with no strictness check at all, so it collapses at the
target's mantissa boundary even when the key scale is zero. Both reject only on
range overflow.

Measured against an `ENGINE = Memory` oracle, this fixes nine shapes that
returned fewer rows than the predicate matches, including a `Time64` key. Unlike
`DateTime64`, `Time64` gets no help from the sub-second precision guard in
`Set::execute`, whose condition names `DateTime64` alone, so its integer cast
really does collapse. The wrong results are older than this pull request, where
the same conversions are treated as fully exact; what this commit fixes is the
classifier's own claim to have closed the family.

Six shapes measured to be genuinely exact keep pruning: a finer or equal set
scale, and a scale-zero key against an integer set element. Two of the new test
cases are controls for exactly those, since a predicate that declined every
scaled key would pass the carrier cases and silently give up pruning.

The helper's closing comment claimed that anything the predicate does not detect
either fails `canBeSafelyCast` at the call site or rejects rather than
truncates. The first half is not a safety property: failing that check does not
make an atom decline, it falls through to `castColumnAccurateOrNull`, which
still builds a live atom. The block now presents its list as the classes the
predicate detects, states what a failed forward cast does and does not imply,
and names the remaining residual.
The set-index exactness gate asked whether the runtime key-to-set cast can
collapse two distinct keys by looking for a Decimal scale on the key. That test
is blind to temporal granularity: Date and Date32 carry only a calendar date,
Time and Time64 only a time of day, DateTime and DateTime64 both, and no arm of
tryGetDecimalScale answers for the first four at all. A conversion whose target
cannot represent a component the key carries was therefore left merely relaxed
and the atom stayed live, and relaxation only ever forces can_be_false, so the
positive IN direction kept pruning against a set that under-approximates the
predicate.

Both directions are lossy and silent. Casting a timestamp into Date throws off
the time component, so a whole day of keys maps onto one set value; casting a
date or a timestamp into Time throws off the calendar date, so keys sharing a
clock reading collapse. Neither is rescued by a round-trip check, because
can_apply_accurate_cast requires an integer or float source, so a temporal
source never reaches the strict accurate::convertNumeric path.

Add a third arm keyed on the temporal component set rather than on a scale,
placed ahead of the scale arm so a scaled key whose lost component is not the
sub-second one is still caught. Measured over the full six-by-seven temporal
cross-product against a Memory oracle: fourteen wrong results across both
directions, every one of them also wrong on master, and the component model
separates all forty-two cells. Component-equal and widening pairs keep their
current disposition, and the scale arm's own cells are unchanged.

Also correct two test cases that asserted exactness for atoms that are only
relaxed, since canBeSafelyCast rejects their forward cast, and add the NOT IN
part-count assertion to the cases that really are exact: only the negative
direction distinguishes an exact atom from a relaxed one.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (8 rounds, 47 findings adjudicated)

Before opening this PR I ran an independent second-model review of the diff, once per revision,
plus my own cold read of the resulting code. Every finding was verified against the source or by
measurement before being accepted or rejected, and each round's fix produced the next revision.
Cumulative: 47 findings adjudicated -- 35 accepted and fixed, 2 rejected with evidence, 10
recorded as verified-clean or not-defects.
15 came from the second model, 21 from my own cold
reads, the rest from re-reviews of earlier rounds.

The substantive ones, and how each was resolved:

❌ canBeSafelyCast(Nullable(X), non-Nullable String) returned true -- the original bug.
Round 1. Fixed in the predicate rather than at the call site, so all its callers get the
NULL-safe path.

❌ Relaxing on any source NULL was too coarse -- raised by clickhouse-gh[bot] on the first
revision. Accepted: the earlier revision disabled exact NOT IN pruning whenever a source
NULL was present, when the set is still exact if the folded value was already in the set. The
cause is fixed instead: the source-NULL row is dropped, and relaxation is re-scoped to the
property that actually makes the set inexact.

❌ Exactness was not gated on the conversion, in either direction -- rounds 3 to 6. Index
preparation casts set values INTO the key type while runtime membership casts the KEY into the
set's type. A set-to-key cast that is not equality-preserving over-approximates and is now
relaxed; a key-to-set cast that can collapse two distinct keys onto one set value
under-approximates, which relaxation cannot repair, and now DECLINES. Three collapse classes are
detected, each with its own measured carriers: different text types, a loss of Decimal /
DateTime64 / Time64 scale, and a temporal element that cannot represent one of the key's
components.

❌ Three liveness controls were wrongly declining -- round 6, caught by the second model. A
set scale FINER than the key's, and a key scale of ZERO, cannot collapse. Both arms were
narrowed and both cases now ship as controls.

⚠️ The collapse detector is not exhaustive -- raised in five consecutive rounds, including the
last. Accepted as real and deliberately NOT closed here, on measurement. A key type with no
strict round-trip check at all still collapses: accurate::convertNumeric(strict = true) needs
an integer or float SOURCE, and in this cast the source is the KEY. Closing it by inverting the
default to "decline unless proven safe" was implemented and measured, and it is harmful: it
fixes the two remaining carriers but reddens three of this PR's own liveness controls, whose
runtime casts are injective and whose results already agree with an ENGINE = Memory oracle, so
it buys zero correctness there and gives up real pruning (Parts: 1/3 becomes Parts: 3/3).
Widening the protected key-type set instead keeps all six controls green and fixes neither
carrier. That pair of measurements is the point: collapse depends on the conversion DIRECTION
(narrowing or lateral versus widening), not on the key type, so no key-type allowlist can satisfy
both halves. A correct fix needs a per-pair widening predicate with its own carriers and
controls, which is a separate change. Both carriers are byte-identically wrong on master and
unchanged by this PR; the changelog entry now names the three classes it does fix and says the
rest are not addressed.

⚠️ An IPv4 key against a Nullable(UInt32) element returns no rows -- found while measuring
the above, and it is a different defect: the runtime key-to-set cast is injective, but the
forward cast maps every element to NULL, so the pruning set is built empty while runtime
membership is true. Live on master, unrelated to this PR's direction, tracked separately.

✅ Rejected with evidence: index pruning suppresses a runtime exception. The claim was that a
key value outside the set type's range makes a full scan throw while the exact index prunes that
partition and returns a partial result. Its necessary step is that the query SUCCEEDS with pruning
enabled; the finding's own probe recorded it throwing there too, so the exception is not
suppressed.

✅ Rejected with evidence: composite recursion is tested only for Tuple. The predicate walks
Array / Map / Tuple while only Tuple pairs have cases. The recursion is a strict superset
of the tested reach and cannot regress the untested shapes, and the changelog's narrower wording
is the accurate one.

Four residual shapes are disclosed in the description and tracked separately rather than bundled
here: the collapse residue above, an IPv4 key against an integer element, a temporal pair
differing only in RANGE, and a non-Nullable source. None is regressed by this PR, and each is
improved from wrongly-exact to relaxed where this PR's gate reaches it.

Session id: cron:clickhouse-review-slot-52:20260801-082500

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

This PR supersedes #111418 and carries the complete fix; please review here rather than there.

Both were opened from my account for issue #111340. #111418 holds only the first two commits of this work. The six revisions after it, driven by eight rounds of internal review, found and fixed further wrong-results bugs in the same code path, so #111418's current head is an early and incomplete revision of what is here. Its branch became owned by a separate tracking task of mine, which is why this work ended up on a new branch and opened a second PR instead of updating the first. That was my tooling's mistake, not a deliberate split.

I have not closed #111418 unilaterally. If you would prefer one PR, say so and I will close whichever you pick.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Check Answer
a Deterministic repro? Yes, and not flaky. Two shapes. Correctness: SELECT s FROM t_np WHERE s NOT IN (SELECT 'a' UNION ALL SELECT NULL) on rows 'a', 'b', '' in a PARTITION BY s table returned only 'b' before this PR, because the '' row was pruned away. Cross-type: SELECT k FROM t_ct WHERE k NOT IN (SELECT CAST('01', 'Nullable(String)') UNION ALL SELECT NULL) on rows 1, 2, 3 returned only 2, 3. An ENGINE = Memory twin returns the full correct answer in both cases. Inverse cross-type: SELECT s FROM t_sk WHERE s IN (SELECT CAST(1, 'Nullable(UInt8)') UNION ALL SELECT NULL) on rows '01', '1', '2' returned only '1', because the '01' partition was pruned even though '01' matches the set value 1 at runtime. A plain clickhouse-test run of 04545_transform_null_in_non_nullable_key fails on every reverted variant and passes on this one.
b Root cause explained? Yes, two causes in one block of tryPrepareSetColumnsForIndex. First, when the source set element type is outer-Nullable and the key type is not, the code hands over the nested column, so a source-NULL position carries the key type's default ('', 0), and the shared row filter kept it, injecting a value the query never wrote into the pruning set: that weakens IN and, after negation, strengthens NOT IN. Second, exactness was assumed for any surviving set, but index preparation casts set values INTO the key type while runtime IN casts the key into the set's type, and castColumnAccurateOrNull only proves no value overflowed, not that the conversion preserves equality: String -> UInt64 maps '01' to 1 although toUInt64(1) IN (CAST('01', 'Nullable(String)')) is false. That asymmetry cuts both ways: when the runtime key-to-set direction is the lossy one, the pruning set UNDER-approximates the predicate instead of over-approximating it, so the positive IN prunes a partition that still holds a matching row.
c Fix matches root cause? Yes, at the layer where the defect is. The spurious row is dropped at the only function that simultaneously sees the source null map, the cast result and the shared filter, and exactness is gated on BOTH conversion directions rather than on the mere presence of a source NULL, which was the over-broad mitigation an earlier revision used: the set-to-key cast must be safe (canBeSafelyCast) AND the runtime key-to-set cast must be unable to collapse two distinct keys onto one set value. Injective same-family numeric narrowing stays exact, because castColumnAccurate rejects an out-of-range value instead of truncating it, so it cannot collapse anything silently. A collapsing conversion is DECLINED rather than relaxed, because all six relaxed consumers only ever force can_be_false = true and never widen can_be_true, so relaxation cannot protect the positive IN direction. No widened assertion bound, no reduced dataset, no defensive check masking an upstream bug. Three tags and one SET were added to the test (no-parallel-replicas, no-replicated-database, no-random-merge-tree-settings, explain_query_plan_default = 'legacy') because the new assertions read the local MergeTree read plan; the first two are required and proven load-bearing below, the third suppresses randomized pruning stages that shift the Parts: N/M numerator and denominator, and the SET is defence-in-depth matching the 479 tests that pin it.
d Test intent preserved, new tests added? Yes. Thirty-two labelled cases and eighty-three plan assertions, each paired with a result assertion so over-pruning is caught by value and not only by plan text. The newest group covers the temporal granularity axis: a timestamp key against a Date source, whose cast throws off the time of day, and against a Time source, whose cast throws off the calendar date, the same date-dropping direction through DateTime64/Time64 where both sides report a scale, a composite carrier, and two controls that keep a component-equal and a widening temporal pair live so the arm cannot be satisfied by declining every temporal pair. Earlier groups cover the inverse cross-type shape as a wrong-results counterexample, a Decimal scale-collapse shape so the second arm of the new predicate is not dead code, and an injective numeric-narrowing CONTROL that must keep pruning; that control is what stops the exactness gate from being repaired by declining every cross-type conversion, which an earlier revision did and which over-declined seven demonstrably exact shapes. The newest case covers a multi-column set whose pruning set becomes empty only after the shared row filter has been applied to every column; because an empty set and a relaxed set print the same part counts, that case is pinned on the trivial-count optimization, which a strict PartitionPruner switches off for a relaxed condition, together with a relaxed non-empty control proving the assertion is not vacuously true. Assertions from earlier rounds whose premise changed were reconciled rather than deleted, and three that did not pin what their comments claimed were strengthened: the LowCardinality recursion is now pinned through the has caller (the only shape that reaches it), the duplicate-key-mapping case now asserts the set condition is PRESENT and not merely that nothing was pruned, and the Tuple(Nullable, Nullable) case now pins its plan and not only its values. Six further cases pin the widened collapse family: a String key against a FixedString set element, both FixedString width directions, a DateTime64 scale loss whose forward cast is classified unsafe so it used to escape the decline, a Tuple key whose collapse lives in one element, and two controls proving identical text types and identical composite element types still prune. Five further cases and two further controls pin the scale-less half of the collapse family: a Decimal key against an integer set element (the runtime cast takes the whole part), the same against Float32 and Float64 set elements with a key scale of zero (the loss is mantissa precision, so a scale-gated arm would miss it), and a Time64 key against an integer set element, which unlike DateTime64 gets no sub-second guard in Set::execute; the two controls are a finer-scaled Decimal source and a scale-zero key against an integer source, both of which must keep pruning, and a mutation that declines every scale-less source reds exactly the second of them. Nothing was weakened or removed, and the reference gains sixty-seven lines in total while zero existing lines ever move.
e Demonstrated in both directions? Yes, against the real clickhouse-test reference diff, over a mutation matrix built up across revisions, whose newest five mutants each isolate one clause of the temporal arm and each turn exactly the predicted, disjoint set of cases red: deleting the arm reds the four temporal carriers and leaves both controls green, making it fire for any temporal pair reds only the two controls, dropping either half of the component comparison reds only that half's direction, and forcing the exactness flag false reds every assertion that pins exact pruning, which is what proves those assertions measure exactness and not mere liveness. Reverting only the exactness gate makes the cross-type counterexample lose a result row; forcing the gate false flips every same-type exactness assertion; reverting the LowCardinality recursion alone flips the two assertions that pin it; making the IN caller decline flips the presence assertions while the part-count lines still pass; restoring master's block loses the '' result rows; moving the emptiness decision back inside the per-column loop, and dropping it altogether, each flip exactly the new final-empty assertion and nothing else. Every variant was built with the changed object files deleted first and its Build ID verified to move and to match SELECT buildId(); reverting the collapse predicate to the earlier one-directional gate loses the inverse counterexample's result row; neutralizing the text arm alone flips only that case and neutralizing the scale arm alone flips only the Decimal case, so each arm is separately load-bearing; and replacing the decline with a relaxation still loses the result row, which is the measurement proving relaxation cannot repair the positive direction. Three further mutations cover the widened gate: restoring the text arm's non-text exemption reds exactly the three FixedString cases, restoring the forward-cast conjunct on the decline reds the DateTime64 case and the two unequal-width FixedString cases, and deleting the composite recursion reds only the Tuple case; the overlap is itself a measurement, since an unequal-width FixedString pair needs both halves because its forward cast is classified unsafe. Four further mutations cover the scale-less arm and are the measurement that separates its two mechanisms: restoring the earlier both-sides-must-report-a-scale arm reds exactly the five new carrier cases and leaves all seven controls green, deleting only the float clause reds exactly the two float carriers, deleting only the integer clause reds exactly the integer carrier and the Time64 one, and making the arm fire for any scale-less set element reds exactly the scale-zero control, which is what proves the arm is not over-declining. Restoring reproduced the fixed Build ID bit-identically with the sources byte-identical and no mutation markers left, and the final comment-only edit rebuilt to a bit-identical Build ID as well.
f General across code paths? Yes. tryPrepareSetColumnsForIndex has exactly two callers, tryPrepareSetIndexForIn and tryPrepareSetIndexForHas; both are covered and both NOT has and the has LowCardinality path are asserted explicitly, and because the new collapse predicate is consulted inside that shared body a single hunk fixes IN, NOT IN, has and NOT has alike. The other canBeSafelyCast call sites in the same file (:1837, :1876, :2292, :2714) and in src/Storages/KVStorageUtils.cpp:197 are not carriers: they either return early on any NULL after cast or never build a pruning set from a folded default. KeyCondition is engine-agnostic, so SharedMergeTree is covered by construction. The sibling runtime guard was hunted rather than assumed: Set::execute nulls out a key whose sub-second part the cast would drop, but its condition is keyed on DateTime64 alone, so Time64 shares the mechanism with none of the protection; that asymmetry is what surfaced the Time64 carrier, and the classifier now treats all three scaled families uniformly instead of depending on which of them that unrelated guard happens to cover. One residual in the untouched non-Nullable-source branch is reproduced, documented and deliberately left to its own change rather than widening this diff.
g Generalizes across inputs? Yes, measured over a five-key by eight-source matrix re-run against the final binary, plus the shapes the committed test covers. Key types String, FixedString, Int64, UInt64, Int32, Date, Date32, DateTime, DateTime64, Time, Time64, Decimal, LowCardinality(String), Nullable(String), Tuple(Nullable, Nullable); source wrappers bare Nullable(T), LowCardinality(Nullable(T)) and an unsuffixed literal; cross-type String to UInt64 and sign-crossing numerics; multi-column sets, including one whose set empties only after the shared filter; and boundary set sizes 0 (all-NULL source) and 1. A text key against a set element of any DIFFERENT type, text or not, and a key whose Decimal, DateTime64 or Time64 scale is finer than the set element's, are declined, and the test covers both FixedString width directions; the mirror directions (a finer-scaled SET, an IDENTICAL text type, same scale) stay live, so the predicate is correctly directional; the collapse test recurses into Tuple, Array and Map so it has the same reach as the canBeSafelyCast check it complements, with a measured Tuple carrier and an identical-elements control, and a shape mismatch is not itself treated as a collapse; a FixedString key against a numeric set element is unreachable, since CAST AS FixedString is only implemented for String and FixedString. Same-type and safely-widening conversions keep exact pruning, including injective same-family numeric narrowing; sign-crossing, String and Float64 sources relax. A second matrix covers the scaled keys specifically, over all three scaled families (Decimal, DateTime64, Time64) against coarser, finer and equal scales and against Int, UInt, Float32, Float64 and text set elements, at the float mantissa boundaries two to the twenty-fourth and two to the fifty-third and at key scales both zero and greater than zero: it found nine shapes whose answer disagreed with an ENGINE = Memory twin, all nine now agree, and six shapes measured to be genuinely exact keep pruning, so the arm is gated on the mechanism rather than on the type name. In every cell of both matrices the results agree with an ENGINE = Memory twin in both the IN and the NOT IN direction, so a relaxing cell gives up pruning only and never an answer.
h Backward compatible? Yes. No setting, no setting default, no serialization, no protocol and no on-disk format change, so no SettingsChangesHistory.cpp entry is needed. Where NOT IN and NOT has results change, they change from wrong to correct; where pruning changes, it becomes more conservative, which is always safe.
i Invariants and contracts preserved? Yes. Set-column alignment holds because the drop is per row through the one shared filter applied to every column. set_types is left as on master, so the caller's size comparison is unaffected. The new out-param is trailing, is initialised by both callers, and either ORs into an existing relaxation decision or, when the runtime key-to-set conversion can collapse distinct keys, causes the function to decline the set index outright; in the relaxing case checkInRange can still be trusted for can_be_true and is simply no longer trusted for an exact can_be_false, and in the declining case no set index is built at all. The declining return is taken before any set column is mutated, so it leaves set_columns, set_types and indexes_mapping untouched and both callers' pre-existing if (!tryPrepareSetColumnsForIndex(...)) return false; handles it unchanged. Its meaning is now exactly "the final pruning set is non-empty and was built through a conversion that is not equality-preserving", because the emptiness half of the decision is taken after the shared filter has been applied to every column rather than from the filter as it stands mid-loop; that is what the accompanying comment claims, and an earlier revision's comment claimed an invariant the code did not hold for a multi-column set. The lifetime pin on the original set column is unchanged, no locking or concurrency is involved, and the function's early-return paths are untouched.

Verification summary: 04545, 03733 and 04145_extract_plain_ranges_relaxed_not_in all pass, each 50 of 50
green under --test-runs 50 for 150 runs with no failure. A 168-test regression sweep over the element set, transform_null_in, key_condition, partition_pruning and in_subquery neighbourhood was run with a ninety-second per-test cap, and its result is reported as measured rather than as a clean pass. Six tests failed, every one of them a harness timeout with no reference difference, and each of the six passes on its own in one to three seconds. The failures are attributed by control rather than by assertion: the same six tests at the same concurrency against a pristine master snapshot build fail identically, three rounds out of three, with byte-identical failure sets, and the full-list master control run independently timed out on four tests of the same class plus one genuine pre-existing reference difference that the run under test never reached. The cause is load on the shared build host, which at one point killed the master control server itself. There is therefore no regression attributable to this change. The two new tags were verified to be
load-bearing rather than assumed: against a real three-replica default_parallel_replicas cluster, with the
server log confirming parallel replicas were engaged, removing the tag makes the test fail on 56 lines.
03733_has_function_key_condition_explain.reference moves by exactly the two lines already described and no
further.

Session id: cron:clickhouse-review-slot-52:20260801-082500

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @hanfei1991, could you review this? It gates MergeTree set-index exactness on the conversion in both directions: index preparation casts set values into the key type while runtime membership casts the key into the set's type, so a cast that maps two distinct key values onto one set value made the pruning set under-approximate the predicate and IN silently dropped matching rows.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [883b072]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR prevents incorrect index pruning when an IN subquery's type merges distinct key values. The latest DateTime64 saturation fix is correct, and both new SQL tests match their references on the PR-head CI binary. One independently reproduced named-tuple cast-safety gap still causes wrong results.

Findings

❌ Blockers

  • src/Storages/MergeTree/KeyCondition.cpp:3631: Named-tuple casts can still produce an incorrect exact pruning set. The new guard matches fields by name, but the subsequent canBeSafelyCast fast path matches them by position. For key Tuple(a UInt8, b UInt16) and RHS Tuple(b UInt8, a UInt16) containing (2, 257), the forward cast wraps a = 257 to a = 1. An exact NOT IN atom then discards key (1, 2), although runtime membership rejects it. On head 883b072a6fe5, partition pruning returns 2 rows versus 3 from the same predicate inside countIf; a minmax skip index also returns 2 versus 3. This pre-existing gap remains reachable through the new named-tuple handling. Match field names in the forward safety check, or validate these layouts through an accurate cast and round trip; add a focused regression with reordered fields and narrowing overflow.
Final Verdict

Status: ❌ Block. Correct or explicitly track the named-tuple forward-cast gap and add its regression coverage. The earlier saturation finding is fixed and its review thread is resolved.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 1, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 131/141 (92.91%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 61d66f2

Every failure below has an owner: a fixing PR (ours 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
(none) 174 check-runs, 0 failures nothing to own

Config Workflow and Finish Workflow both completed successfully; no check queued or in progress.

Session id: cron:our-pr-ci-monitor:20260803-180000

…-explain-tests

Resolve the KeyCondition.cpp conflict in tryPrepareSetColumnsForIndex.

Master's ClickHouse#109926 rewrote the Nullable-source block and now handles the
non-Nullable-key case this branch had addressed on its own, in a strictly
more general form: it also preserves a NULL set member for a Nullable key
and treats a Nothing element as a source NULL. Master's version of that
block is taken whole, and the branch's own source-NULL filtering, which
master subsumes, is dropped.

What this branch still contributes is the equality-preservation of the set
conversion, which master does not cover: keyToSetConversionMayCollapse
declines an atom whose runtime key-to-set cast can map two distinct keys
onto one set value, and set_is_approximate relaxes an atom whose forward
set-to-key cast is not equality-preserving. Both are kept, rebased onto
master's variable names, and the approximate flag is now raised outside the
per-row loop next to master's source_null_map handling.

Master independently updated 03733_has_function_key_condition_explain to
the same expected set sizes this branch had produced, so that reference no
longer differs.
Four changes, all from re-reviewing the merged tree.

Trim the commentary around keyToSetConversionMayCollapse to the invariant each
site needs, per the standing request that motivation and context live in the
commit message rather than in the code.

Correct the helper's header: it had claimed an unclassified many-to-one
conversion is only ever treated as approximate, but when
canBeSafelyCast(set -> key) holds, tryPrepareSetColumnsForIndex takes the early
exit that casts the set values directly and returns before consulting the
predicate, so the atom stays exact there. The scope limit itself is unchanged
and pre-existing.

Add Case E2 to 04545. Case E's carrier was a String-to-String conversion, which
is equality-preserving and so never sets set_is_approximate, leaving
tryPrepareSetIndexForHas's own relaxation arm unasserted: deleting
`|| set_is_approximate` from that caller kept the test green. E2 carries a UInt8
key against a Nullable(Int64) element, whose conversion is not
equality-preserving. A text pair cannot be used because has requires a supertype
for the key and the element. Rows are correct either way, so the load-bearing
assertion is Parts: 3/3; the mutant prunes to 2/3 and fails on that line. Its
table is dropped in the epilogue with the other thirty.

Remove ignore_drop_queries_probability = 0 from the thirty cleanup statements,
as asked on ClickHouse#112005. The setting defaults to 0 and only the stress runner and
the upgrade check's --fake-drop client inject it; neither compares per-test
results, and clickhouse-test's leftover-tables check is gated on
`case_file >= "02800"` where case_file is an absolute path, so it never fires.
The DROP statements are unchanged.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 18, 2026
PR ClickHouse#111418 was closed on 2026-08-17 and superseded by ClickHouse#112890, so the comment pointed at a
dead PR. Rewrote it as the local invariant instead of citing any PR, since a reader of the
test does not need the fix history to understand which shapes the file deliberately omits.
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ae4b2f676 with master 432e8f90e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.57, programs/clickhouse-keeper ×0.59 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.3 s 12.2 s +8.6 s (+240%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.3 s +5.2 s (+252%)
Compile time of recompiled translation units

7 translation units recompiled, 23 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai groeneai added the groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR label Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @hanfei1991, could you review this? Set::execute casts the key into the IN subquery's type while KeyCondition casts the set into the key type, so a coarser set (a DateTime key against a Date subquery) pruned member rows in the primary key, partition, minmax and statistics paths; the index now uses such a set only when the key's cast keeps distinct values apart.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim was closing this intended? This PR now fixes #124823 (open, assigned to me): index analysis used an IN subquery set whose type is coarser than the key, for example a DateTime key against a Date subquery, so primary key, partition, minmax and statistics pruning dropped matching rows at default settings. It no longer targets #111340 or #112905. Could you reopen it (that keeps its can be tested label), or should I open the same commits as a new PR?

@PedroTadim

Copy link
Copy Markdown
Member

My mistakc

@PedroTadim PedroTadim reopened this Oct 16, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
groeneai and others added 3 commits October 16, 2026 09:13
A numeric CAST into Decimal(P, S) checks the backing integer's range, not P, so
Decimal(6, 0) can hold 16777217, and its Float32 cast equals 16777216's. The
precision check let index analysis use such a set and prune the row. Float64
holds every Int32 exactly, so only Decimal32 against Float64 still uses the set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… set index analysis

Formatting saturates an out-of-range Date32 to 9999-12-31 and Time/Time64 to
999:59:59, so such keys collapse when cast into a String set (RowBinary stores
them). renderingCollapsesDistinctValues already lists Date32 for the same reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Formatting prints every nonzero Bool byte as true, and RowBinary stores any byte,
so distinct keys collapse when cast into a String set.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a8f1822

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
Build (arm_tidy, 3/4) / Build ClickHouse not from this PR: unit_tests_dbms does not compile on master since af19343b2516 (src/Functions/tests/gtest_functions_stress.cpp:2367: StackTrace::tryResolveAddress no longer returns an optional); the same build fails on 24 other PRs since 09:18 UTC. This failure stopped the workflow, so most test jobs did not run on this head #126269 (external, open)
Finish Workflow / Post Hooks Bugfix validation was dropped because of the row above #126269 (external, open)
Mergeable Check, PR rollups of the rows above #126269 (external, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261016-110007

groeneai and others added 3 commits November 13, 2026 13:45
…-explain-tests

Resolve the conflict in KeyCondition.cpp: master added isTextOfElementValues
(ClickHouse#130537, 79950f0) at the place where this branch adds
keyToSetConversionMayCollapse; keep both.

keyToSetConversionMayCollapse reads the chain's result type, so for
`toString(k) IN (SELECT <integers>)` it sees a String key against an integer
set and would decline the set again, undoing ClickHouse#130537. Apply the same
isTextOfElementValues exemption to it: the chain computes only canonical
numerals (or `Date` text), which the set's cast parses back to one value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master's floatValuesMissKeyValues (c971493, b26ad5a) already checks every
float element over a Decimal, DateTime64 or Time64 key input value by value:
it keeps a float that converts exactly and declines everything else, also
for a value stored beyond the declared precision by a numeric CAST. The
type-level float rule in keyToSetConversionMayCollapse declined every float
set over such a key except Decimal32 against Float64, so it removed pruning
that master keeps on purpose: 05408 asserts `force_primary_key = 1` for
`d IN (SELECT 20.00)` over `Decimal(10, 2)` and fails with INDEX_NOT_USED.

Measured on master 21809ea without this PR: Decimal(6, 0) with 16777216 and
16777217 against `IN (SELECT toFloat32(16777216))`, Decimal(10, 0) against
`toFloat64(9007199254740992)` and DateTime64(3) against a Float32 already
return the full-scan count through the index, so the 05403 lines for those
cases keep passing.

05339: a `Decimal(38, 30)` key against `IN (SELECT toDecimal128(2, 0))` no
longer uses the primary key, as the set's scale is coarser than the key's
(`Set::execute` truncates the key into it). Measured on master with an extra
row 2.5: the index returns 1 row and the full scan 2 (`NOT IN`: 4 vs 3);
with this PR both return 2 (3). Drop `force_primary_key` from that query; its
result does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… type

Master's 04708_accurate_cast_integer_to_ip (from ClickHouse#113040) asserts that an
IPv4 key compared with IN against a UInt32 subquery set still prunes
(`Parts: 1/3`). keyToSetConversionMayCollapse sent that pair to its
conversionPreservesOrder fallthrough, which knows no IP rule, so the set was
declined and the Fast test failed.

Set::execute casts the key into the set type with an accurate cast. Measured
on this build: IPv4 into UInt32/UInt64/UInt128/UInt256 is the identity, into
IPv6 it maps to ::ffff:a.b.c.d; IPv6 into UInt128 is the identity, into IPv4
it is exact for mapped addresses and NULL otherwise; UInt8..UInt64 into IPv4
are range-checked, UInt128 into IPv6 exact; every other pair throws or yields
NULL. So no distinct keys merge.

UInt128/UInt256 sets over an IPv4 key stay declined: the index casts such a set
into IPv4 and gets NULL, so it prunes every part while the scan matches (master:
count 0 vs 1). The new 05403 line checks that; it fails if the arm admits any
unsigned set type. UInt8/UInt16 keys stay declined against an IPv4 set, since
the index cannot cast IPv4 into them (master throws NOT_IMPLEMENTED there).

Validation: 04708 FAIL -> OK; 936-test deterministic A/B against the previous
head changes nothing else; 9 related tests x10 randomized OK.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
`Set::execute` casts a `DateTime64` key into `DateTime` with saturation: every
key before 1970-01-01 00:00:00 becomes the epoch and every key after
2106-02-07 06:28:15 becomes the upper bound. Its sub-second filter does not
catch that, so a set holding a bound matches keys the index reads as not in the
set. Over `DateTime64(3, 'UTC')` keys `1969-12-31 23:59:59` and
`1970-01-01 00:00:00`, `d IN (SELECT toDateTime(0, 'UTC'))` returned 1 instead
of 2 on the primary key, partition key, minmax skip index and statistics, also
for a `Nullable` key, a packed tuple and a `cityHash64` partition key.

Treat the pair like the other non-widening temporal pairs, so the index does
not use the set. This drops the `plain_column` exemption and the
`set_is_packed` flag that only it needed. Cost: a `DateTime64` key against a
`DateTime` subquery set no longer prunes (`Parts: 3/3` instead of `1/3`).

05403 replaces its DateTime64/DateTime pruning control with a bug line at both
bounds; 04545 drops the matching top-level control of case C24.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
return true;
}

return false;

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.

[Blocker] Match named fields in the forward cast-safety check too

This handles the key-to-set cast by name, but accepting this pair still reaches the positional canBeSafelyCast fast path at KeyCondition.cpp:3835. For a key Tuple(a UInt8, b UInt16) and set element Tuple(b UInt8, a UInt16), that check accepts the identical positional types, while the actual set-to-key cast maps a UInt16 into a UInt8. A set value with a = 257 therefore wraps to a = 1, and the resulting atom incorrectly remains exact.

Reproduced on the CI binary for head 883b072a6fe5:

CREATE TABLE t (k Tuple(a UInt8, b UInt16))
ENGINE = MergeTree PARTITION BY k ORDER BY k;
INSERT INTO t VALUES ((1, 2)), ((2, 3)), ((3, 4));

SELECT count() FROM t WHERE k NOT IN
    (SELECT CAST((2, 257), 'Tuple(b UInt8, a UInt16)'));
-- 2
SELECT countIf(k NOT IN
    (SELECT CAST((2, 257), 'Tuple(b UInt8, a UInt16)'))) FROM t;
-- 3

The exact pruning set incorrectly excludes (1, 2). A minmax skip index reproduces the same loss (Granules: 2/3). This is a pre-existing forward-cast gap that the new named-tuple handling still admits. Make canBeSafelyCast follow the cast's field-name mapping, or bypass that fast path and validate the round trip for these layouts. Add a regression with reordered fields and a value outside the destination field's range.

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.

This is pre-existing: master 21809ea gives the same 2 vs 3, because canBeSafelyCast (src/DataTypes/Utils.cpp) matches tuple elements by position while CAST maps named tuples by name, and this PR changes neither it nor the fast path that calls it. It is a set element finer than the key rather than coarser, so I will fix it in a separate PR.

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.

Correction: I am not opening a separate PR for this. #71030 removes the tuple element names before the cast both in Set::execute and in KeyCondition::tryPrepareSetColumnsForIndex, so IN pairs the set element and the key by position on both sides, and this case is covered there. I am following that PR instead.

@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 19, 2026

This branch has not been deployed

No deployments
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-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

IN subquery with coarser type than primary key prunes matching rows

5 participants