Repository navigation
Fix wrong results and TYPE_MISMATCH from index analysis for IN on a Tuple key under a key transform - #118899
Conversation
`k IN (tuple(...), ...)` over a `Tuple`-typed key column arrives at key analysis unpacked, one set column per tuple element. `tryPrepareSetIndexForIn` re-packed that layout into a single `Tuple` column only when the key expression's own result type was a tuple of the same arity, so a key wrapped in a transform that returns something else (`ORDER BY toString(k)`) never matched: the set columns were then cast to the key expression result type one at a time, and `CAST AS Tuple` threw `TYPE_MISMATCH`. Where an element happened to parse as a tuple literal the cast succeeded with an unrelated value instead and pruned the granule holding the matching row, losing it silently. Match the layout against the type the set elements are actually compared at, which is the transform chain's input type when there is a transform and the key expression result type otherwise. Partition pruning, the `minmax` skip index and the `set` skip index build their conditions through the same function and threw the same way. Such a newly admitted layout is not exact. The transform preserves the set semantics only if it maps distinct key values onto distinct transformed ones, and `toString` does not: it renders every NaN payload as `nan` while `IN` compares floats bitwise, and it renders the two instants of a fall-back hour as one local time. So for the layouts admitted here for the first time, decline the atom under the negated forms, where an over-approximating set would exclude rows that satisfy the predicate, and mark it relaxed otherwise. Declining rather than relaxing does not depend on every present and future consumer applying relaxation before it negates the atom, and it is the disposition `tryPrepareSetIndexForHas` already takes for the same merge. A layout whose key expression result type is already a tuple of the set's arity was re-packed before this change and is left exactly as it was, so nothing that worked before can regress: `ORDER BY identity(k)` still yields an exact atom, and so does a scalar key, which never reaches the re-pack at all. The pre-existing exactness of a set that already arrives packed as one `Tuple` column, and of a scalar key under a conversion that claims injectivity without being injective, is unchanged here; that family belongs to ClickHouse#117238, whose narrowed `isInjective` reaches this path through `out_relaxed`.
Internal second-model reviewReviewed cold by a second model before publishing, then adjudicated against the recorded ❌ Fixed before publishing
💡 Improvement noted, not made
|
|
Workflow [PR], commit [4a4d1ad] Summary: ✅
AI ReviewSummaryThis PR fixes the unpacked-set Findings❌ Blockers
LLVM Coverage ReportMeasured on commit 4a4d1ad.
Changed lines: Changed C/C++ lines covered: 24/26 (92.31%) · Uncovered code |
Pre-PR validation gate (click to expand)
Pruning is preserved rather than disabled, and the test proves it per consumer: the partition and primary-key arms assert the Scope left alone deliberately, and stated once: the pre-existing exactness of a set that already arrives packed as one Validation for this revision: 50/50 randomized runs green (50 Session id: cron:clickhouse-impl-self-slot-57:20260908-150400 |
|
cc @rschu1ze @al13n321, could you review this? |
|
@nihalzp KeyCondition.cpp 😩 |
| /// A layout the key expression result type rejects has never reached index analysis before, so it is | ||
| /// unknown whether the transform maps distinct key values onto distinct transformed ones: `toString` | ||
| /// claims that for every type, yet it folds NaN payloads and fall-back hours. | ||
| if (repacked_only_by_transform_input) |
There was a problem hiding this comment.
repacked_only_by_transform_input only fires for unpacked sets (set_columns.size() > 1). A packed single-column Tuple carrier such as k IN (SELECT tuple(a, b) ...) or an external Set with one Tuple column still skips this branch, so it falls back to the old injectivity gate from analyzeKeyExpressionForSetIndex.
That keeps ORDER BY toString(k) exact there, because FunctionConvert<..., NameToString>::isInjective() is still hard-coded true in src/Functions/FunctionsConversion.h:3157. The same NaN / fall-back-hour collisions this patch is fencing off therefore remain reachable for packed IN / NOT IN sets, so the current fix only closes the unpacked carriers. Please extend the relax/decline rule to packed one-column Tuple sets too.
There was a problem hiding this comment.
Measured it. The mechanism is right, the scope conclusion is not, and one of the two carriers you name does not reproduce.
Confirmed: a packed one-column Tuple set skips the re-pack branch, isInjective is std::is_same_v<Name, NameToString> (FunctionsConversion.h:3157), and the atom stays exact. With k Tuple(Float64, Float64), ORDER BY toString(k), one row holding the NaN payload 9221120237041090561 and the set holding ...562:
k NOT IN (SELECT tuple(...562, 1)) -> 0, truth 1 (use_primary_key = 0): the row is lost
k IN (SELECT tuple(...562, 1)) -> 1, truth 0: a phantom row is counted
Condition: (toString(k) notIn 1-element set)
Three further measurements decide where it belongs:
- Identical on pure master (commit
7948002, no PR content). Master analyses that layout today, so it sits outside the invariant this PR adds, which is that a layout master rejected must not yield an exact atom. - It is not about packed sets. The same row loss reproduces on a scalar
Float64key with a plain literal set, noTupleand no packing anywhere:
CREATE TABLE t (k Float64) ENGINE = MergeTree ORDER BY toString(k);
INSERT INTO t SELECT reinterpretAsFloat64(toUInt64(9221120237041090561));
INSERT INTO t SELECT toFloat64(7);
SELECT count() FROM t WHERE k NOT IN (reinterpretAsFloat64(toUInt64(9221120237041090562)), toFloat64(9));
-- 1 here and on master, 2 with use_primary_key = 0k NOT IN <Set-engine table>printsCondition: trueon master and here alike, so that atom is already declined and the external-Setcarrier never reaches the exact path.
The root is the injectivity claim itself, and it has a fix in flight: #117238 makes toString's claim type-aware, and isDeterministicTransformInjective already passes the real argument types to isInjective (KeyCondition.cpp:2380, :2388), so that PR relaxes these atoms at the root, packed, unpacked and scalar alike. The date-time variant of the packed shape (Tuple(DateTime('Europe/Berlin'), UInt8), fall-back hour) loses its row the same way here and on master, and renderingCollapsesDistinctValues covers exactly that case; a multi-payload NaN in a float is the one collapse its list does not carry.
So I am not extending the rule to packed sets in this PR: keyed on the layout it would change the exactness of a shape master accepts today, while still missing the scalar carrier that has nothing to do with layout.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 21 s compile time in total, 7 of them have a recent master baseline. |
| || function_name == "globalNotNullIn") | ||
| return false; | ||
|
|
||
| out.relaxed = true; |
There was a problem hiding this comment.
@groeneai This is not needed for injective transforms. Once the toString injectivity declaration is fixed, this block becomes redundant with the is_injective path; let's make sure it is made conditional on that rather than kept once that fix lands.
There was a problem hiding this comment.
Agreed. #117238 (still open) makes toString's isInjective depend on the argument type and stops claiming it for Float and non-fixed-offset date-time elements, which are the two foldings this block exists for; analyzeKeyExpressionForSetIndex then relaxes these atoms through is_injective already. When #117238 merges I'll send a follow-up that makes this block conditional on the transform not being injective, so an injective toString (e.g. of Tuple(Int64, String)) keeps an exact atom here.
There was a problem hiding this comment.
I sent the follow-up: #124831. I removed the block rather than gating it. With #117238, isInjective is false for the Float and fall-back-hour foldings, so analyzeKeyExpressionForSetIndex already relaxes those atoms, and a relaxed NOT IN atom never prunes on its own, so a gated decline would only change the EXPLAIN line. An injective toString of Tuple(Int64, String) now keeps an exact atom. The PR also stops claiming injectivity for toString of Time, Time64 and a floating-point QBit, which this layout would otherwise miscount.
9069f48
Pinned master caf26de. One conflict, in tryPrepareSetIndexForIn: master's ClickHouse#118899 added the repacked_only_by_transform_input block at the same insertion point where this branch declares set_is_approximate, so the two independent additions could not be ordered automatically. Both are kept: master's block first, since it can return early, then the declaration immediately above the call it feeds. Nothing of master's is reverted. Against the pinned master this branch now deletes exactly five lines, all of them lines this fix replaces by design: the tryPrepareSetColumnsForIndex signature, its two call sites, and the two adjusted_indexes_mapping.size() < set_types.size() conditions the set_is_approximate disjunct extends.
ReproducerCREATE TABLE t_str (k Tuple(String, String)) ENGINE = MergeTree ORDER BY toString(k);
INSERT INTO t_str SELECT tuple('(\'a\',\'b\')', 'zzz');
SELECT count() FROM t_str WHERE k IN (tuple('(\'a\',\'b\')', 'zzz')); -- 0, expected 1
SELECT count() FROM t_str WHERE k IN (tuple('(\'a\',\'b\')', 'zzz')) SETTINGS use_primary_key = 0; -- 1
CREATE TABLE t_float (k Tuple(Float64, Float64)) ENGINE = MergeTree ORDER BY toString(k);
INSERT INTO t_float VALUES ((3, 1)), ((5, 1));
SELECT count() FROM t_float WHERE k IN (tuple(3., 1.));
-- Code: 53. DB::Exception: CAST AS Tuple can only be performed between tuple types or from String. (TYPE_MISMATCH)
-- Observed on 26.2.19.43 through 26.8.11.7. 26.1.12.23, 26.9.2.8 and master return 1, 1, 1.Results:
Backport the fix to CC component owner: @CurtizJ @alexey-milovidov Analysis metadata
Introducing change: not identified
|
… type-aware ClickHouse#118899 relaxed `IN` and declined `NOT IN` for every transformed Tuple key re-packed against the transform input, because `toString` then claimed injectivity for every type while it folds NaN payloads and fall-back hours. ClickHouse#117238 made that claim type-aware, so `analyzeKeyExpressionForSetIndex` already relaxes those atoms through `is_injective`, and a relaxed `NOT IN` atom never prunes on its own. Removing the block lets an injective transform such as `toString` of `Tuple(Int64, String)` keep an exact atom. Follow-up to ClickHouse#118899 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
CAST AS Tuple can only be performed between tuple types or from Stringerror, and silently wrong results for aTuple(String, ...)key, when aMergeTreesorting, partition or skip-index key wraps a singleTuple-typed column in a deterministic function (for exampleORDER BY toString(k)) and the query filters that column withk IN (tuple(...)),k NOT IN (tuple(...))or a multi-column subquery set.Description
A
Tuplekey column wrapped in a key transform mis-analysesk IN (<tuple literal>):Code: 53; underPARTITION BY toString(k)evenuse_primary_key = 0fails.Tuple(String, String)and an element that itself parses as a tuple, the bad cast succeeds with an unrelated value and prunes the granule holding the matching row, socount()returns0.Root cause:
IN (<tuple literal>)builds the prepared set unpacked, one column per tuple element, andKeyCondition::tryPrepareSetIndexForInre-packs it into oneTuplecolumn only when the key expression result type (StringfortoString(k)) is a tuple of the set's arity. Otherwise the re-pack is skipped and a scalar set element is cast to the whole tuple type.The fix decides the re-pack against the transform chain's input type, which is the type the set elements are compared at, matching
areSetAndKeyTypesCompatibleForHas. The untransformed path is unchanged. The partition key, theminmaxandsetskip indexes and multi-column subquery sets carry the same defect.A layout admitted here for the first time is not exact:
toStringclaims injectivity, yet it renders every NaN payload asnan, and both instants of a fall-back hour as one local time, whileINcompares floats bitwise. Such layouts are declined under the negated forms and marked relaxed otherwise. A layout whose result type already re-packs the set (ORDER BY identity(k)), and a scalar key, keep the exactness they had.Pruning is preserved:
05063_key_transform_tuple_key_in_setasserts theEXPLAIN indexes = 1lines. 50/50 randomized, no new setting.Found while measuring this area; no existing issue.
Related: #115294 (same transform-input rule for
has)Related: #117238 (narrows the same injectivity claim for date-time renderings)
Related: #118683 (the same NaN merge on an untransformed
Tuplekey)Workflow [PR]
Sync PR [sync-upstream/pr/118899]
Version info
26.9.1.1448(included in26.9and later)