Repository navigation
Conversation
…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]>
…orm-null-in-non-nullable-key-111340
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.
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, The substantive ones, and how each was resolved: ❌ ❌ Relaxing on any source ❌ Exactness was not gated on the conversion, in either direction -- rounds 3 to 6. Index ❌ Three liveness controls were wrongly declining -- round 6, caught by the second model. A
✅ Rejected with evidence: index pruning suppresses a runtime exception. The claim was that a ✅ Rejected with evidence: composite recursion is tested only for Four residual shapes are disclosed in the description and tracked separately rather than bundled Session id: cron:clickhouse-review-slot-52:20260801-082500 |
|
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. |
Pre-PR validation gate (a-i)
Verification summary: Session id: cron:clickhouse-review-slot-52:20260801-082500 |
|
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 |
|
Workflow [PR], commit [883b072] Summary: ❌
AI ReviewSummaryThe PR prevents incorrect index pruning when an Findings❌ Blockers
Final VerdictStatus: ❌ 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. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 131/141 (92.91%) · Uncovered code |
CI finish ledger - 61d66f2Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
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.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units7 translation units recompiled, 23 s compile time in total, 7 of them have a recent master baseline. |
|
cc @CurtizJ @hanfei1991, could you review this? |
|
@PedroTadim was closing this intended? This PR now fixes #124823 (open, assigned to me): index analysis used an |
|
My mistakc |
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]>
CI finish ledger - a8f1822Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261016-110007 |
…-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]>
`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; |
There was a problem hiding this comment.
[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;
-- 3The 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Closes: #124823
Related: #117318
Related: #96225
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when
INorNOT INcompares a primary key, partition key,minmaxskip index or statistics column with a subquery whose type is coarser than the column, for example aDateTimekey withIN (SELECT toDate(...)), a coarserDateTime64orDecimalscale, or an integer key against aBool,DateorEnumsubquery; the same holds for aNullableset undertransform_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 dholding2023-02-01 12:00:01and2023-02-03 13:00:00,SELECT count() FROM t WHERE d IN (SELECT toDate('2023-02-01'))returns 0 instead of 1, andNOT INreturns 2 instead of 1 (#124823). The AST fuzzer's TLP oracle found the same: report.Set::executecasts the key into the set's type, whileKeyConditioncasts the set into the key type. When the first cast merges distinct keys (DateTimeintoDate, a smallerDateTime64orDecimalscale), the index holds one point per element and prunes rows that are members.tryPrepareSetColumnsForIndexnow uses anINset only whenkeyToSetConversionMayCollapseknows the key's cast keeps values apart: the same type, integers and floats (not intoBool), a number (notBool),Enum,Date,UUIDor IP intoString, date/time andDecimalwidenings, anEnuminto a type holding all its values,Dynamic, aVariantholding the key's type,IPv4withUInt32,UInt64orIPv6andIPv6withUInt128(either way), and element-wiseTuple/Arrayor an array of pairs intoMap. Float sets over aDecimal,DateTime64orTime64key are left tofloatValuesMissKeyValues.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 asDateandDateTime(a time zone can skip a day),DateTime64andDateTime(the cast saturates),Date32andString, or an integer and aDecimal.05331and03991now expect the full-scan result, not the index's own error;05339no longer forces the primary key for a coarserDecimalset. #117318 covers the same defect inbloom_filter.Validated by the new
05403_in_subquery_set_coarser_than_key(primary and partition keys,minmaxskip index, statistics, the fuzzer's shape and each collapsing set type; each fails without this change) and04545_transform_null_in_non_nullable_key.Workflow [PR]
Sync PR [sync-upstream/pr/112890]