Skip to content

Fix wrong results and TYPE_MISMATCH from index analysis for IN on a Tuple key under a key transform - #118899

Merged
nihalzp merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/key-transform-tuple-key-in-set
Sep 14, 2026
Merged

nihalzp merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/key-transform-tuple-key-in-set

Conversation

@groeneai

@groeneai groeneai commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

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 a CAST AS Tuple can only be performed between tuple types or from String error, and silently wrong results for a Tuple(String, ...) key, when a MergeTree sorting, partition or skip-index key wraps a single Tuple-typed column in a deterministic function (for example ORDER BY toString(k)) and the query filters that column with k IN (tuple(...)), k NOT IN (tuple(...)) or a multi-column subquery set.

Description

A Tuple key column wrapped in a key transform mis-analyses k IN (<tuple literal>):

  • Valid input rejected. Most element types fail with Code: 53; under PARTITION BY toString(k) even use_primary_key = 0 fails.
  • Wrong results. With 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, so count() returns 0.

Root cause: IN (<tuple literal>) builds the prepared set unpacked, one column per tuple element, and KeyCondition::tryPrepareSetIndexForIn re-packs it into one Tuple column only when the key expression result type (String for toString(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, the minmax and set skip indexes and multi-column subquery sets carry the same defect.

A layout admitted here for the first time is not exact: toString claims injectivity, yet it renders every NaN payload as nan, and both instants of a fall-back hour as one local time, while IN compares 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_set asserts the EXPLAIN indexes = 1 lines. 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 Tuple key)


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

Version info

  • Merged into: 26.9.1.1448 (included in 26.9 and later)

`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`.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold by a second model before publishing, then adjudicated against the recorded
measurements. Kept deliberately short.

❌ Fixed before publishing

  • Admitting the atom for a key transform that MERGES distinct key values was unsound. toString
    renders every Float64 NaN payload as nan while IN compares values bitwise, so with two
    distinct payloads k NOT IN (tuple(<other payload>, 1)) dropped the granule holding the matching
    row, and the positive direction handed the exact-count projection a range it cannot answer. A
    Tuple(DateTime('Europe/Berlin'), UInt8) key loses a row the same way, because two instants of a
    fall-back hour render as one local time. The layouts the re-pack newly admits are therefore not
    treated as exact at all: the negated spellings are declined, the positive one is marked relaxed.
    Both directions are asserted for both element types, and redden without the guard.
  • A first version of that guard fired on any transformed tuple key, which withdrew index analysis that
    master performs today: ORDER BY identity(k) under NOT IN and a scalar hex(k) key lost their
    exact atoms, and a force_data_skipping_indices query master answers began failing with
    INDEX_NOT_USED. The guard now fires only where the key expression result type does not re-pack the
    set by itself, which is exactly the layout this PR newly admits; two arms assert that the
    previously admitted shapes keep the atoms they had.
  • The test carries a decline detector per consumer that can hold one (EXPLAIN indexes = 1
    Condition: line for the sorting and the partition key, force_data_skipping_indices for the
    minmax index, and one for the negated form so its decline cannot silently become a relaxed atom),
    because an earlier revision asserted only count(), which a fix that merely declined index analysis
    also satisfies by full scan. A set skip index gets a result-only assertion: it decides usability by
    column name against its own index expression, so a predicate on the key column is never admitted for
    pruning either way, and the observable half is that the query stops failing.
  • A multi-column subquery (k IN (SELECT a, b)) builds the set unpacked as well, so it is a carrier
    too, and has an arm.

⚠️ Noted, not changed

💡 Improvement noted, not made

  • The four declined function names could read no_relaxed_atom_functions.contains(...) instead: that
    existing set's IN-family members are exactly those four, and it exists for the same reason ("functions
    with range inversion cannot be relaxed"). Left as an explicit local list; happy to switch it.

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4a4d1ad]

Summary: ✅


AI Review

Summary

This PR fixes the unpacked-set Tuple carrier in KeyCondition::tryPrepareSetIndexForIn by re-packing against the transform DAG input type and relaxing or declining the newly admitted transformed layouts. The TYPE_MISMATCH path for tuple literals and multi-column subqueries looks addressed, but one wrong-results carrier is still open: a packed single-column Tuple set (for example SELECT tuple(a, b) or a Set/external table with one Tuple column) skips the new exactness guard and can still build an exact IN or NOT IN atom under ORDER BY toString(k).

Findings

❌ Blockers

  • [src/Storages/MergeTree/KeyCondition.cpp:2961] repacked_only_by_transform_input is only set inside the unpacked-set branch above, so a packed one-column Tuple set still bypasses the new relax/decline rule, falls back to FunctionConvert<..., NameToString>::isInjective() == true, and can therefore return wrong results for the same non-injective transforms this PR is trying to fence off. Suggested fix: apply the same exactness rule to packed single-column Tuple carriers too, or narrow the PR scope so it does not claim the broader IN fix.

LLVM Coverage Report

Measured on commit 4a4d1ad.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 24/26 (92.31%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand, 100%, no randomization anywhere. On pristine master 7b9dc5a4, with a key wrapped in toString: a Tuple(Nullable(Float64),Float64) key and a two-element set holding one tuple with a NULL and one without raises Code: 53 (the originating report); a Tuple(Float64,Float64) key raises Code: 53; a Tuple(DateTime('Europe/Berlin'),UInt8) key with one row in the 2023-10-29 fall-back hour raises Code: 53; and a Tuple(String,String) key whose set element itself parses as a tuple returns 0 where use_primary_key = 0 returns 1, so that shape loses a row with no error at all.
b Root cause explained? IN (<tuple literal>, ...) builds the prepared set unpacked, one column per tuple element, since each literal tuple is a row. The re-pack special case in tryPrepareSetIndexForIn decided whether to re-pack from data_types[0], the key expression RESULT type, which is String for toString(k), so the re-pack was skipped. Each scalar set element was then cast to the whole tuple type: CAST AS Tuple raises Code: 53, or, from a String source, parses into an unrelated tuple whose transformed value becomes an exact point range and prunes the granule holding the matching row.
c Fix matches root cause? Yes, at the one site that decides the layout, and it is 26 added lines inside tryPrepareSetIndexForIn with no hunk anywhere else. The re-pack block exists for exactly this shape and consulted the wrong type, so the fix consults the type the set elements are actually compared at: the transform chain's input type when there is a transform, the key expression result type otherwise. No widened catch, no cast-site guard, no abandoning index analysis. The second half is the exactness rule, scoped to precisely the layouts this change newly admits: nothing was ever established about the transform being injective for them, and toString is not. Deliberately NOT done here: narrowing FunctionConvert::isInjective, which is #117238's subject, and a hand-written list of collapsing types, which can never be complete.
d Test intent preserved / new tests added? New test 05063_key_transform_tuple_key_in_set: 13 arms, 22 asserted lines, one arm per affected consumer. Arms 1-6 assert values (silent wrong count, throw, the originating Nullable report, NaN payload, fall-back hour); arms 7, 8 and 10 additionally assert that pruning is still APPLIED (the Condition: line from EXPLAIN indexes = 1, or force_data_skipping_indices raising INDEX_NOT_USED when the atom is declined); arm 9 asserts the negated-form disposition itself, Condition: true, which is the only line that separates the decline from an atom admitted as relaxed, since both count correctly; arm 11 is answer-only because a set index has no decline detector; arms 12 and 13 are no-regression arms locking the exactness that identity(k) and a scalar hex(k) key already had. No arm asserts a granule count (randomized index_granularity moves them) and no arm pins a setting for randomization reasons.
e Both directions demonstrated? Yes, on Build-ID-asserted binaries at every launch. Pristine master 7b9dc5a4 reddens the file at arm 3 with Code: 53. A build carrying the re-pack with the exactness guard REMOVED answers the NaN and fall-back-hour arms 0/1 where the truth is 1/0. The previous head a5bab505, whose guard was too broad, reddens exactly arms 12 and 13 (both Condition: lines vanish) and nothing else. A build keeping the re-pack and the relaxed marking but dropping the negated-form decline reddens exactly one line, arm 9's, printing Condition: (toString(k) notIn 1-element set) where the shipped build prints Condition: true; the same file without that arm passes on it byte-for-byte, so arm 9 is the only detector for that disposition. The shipped build matches the reference byte-for-byte, and the reference itself was regenerated only after a line-by-line prediction was written first, which then diffed empty (22/22).
f Fix is general across code paths? All four KeyCondition consumers funnel through the one fixed predicate and each was re-measured: primary key, partition pruning, minmax skip index, set skip index. All four negated IN spellings are covered (notIn, notNullIn, globalNotIn, globalNotNullIn), which is the complete set reaching this function; notHas goes to tryPrepareSetIndexForHas. Siblings inspected and deliberately left untouched: tryPrepareSetIndexForHas is safe by construction, its set arriving packed from array elements; areSetAndKeyTypesCompatibleForHas already used the transform input type, so the two sites now agree; the = path passes the whole tuple; applyFunctionChainToColumn cannot reach a Tuple target because no monotonic key function accepts one.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 21 element shapes measured with the indexed answer equal to the use_primary_key = 0 answer on every one: Float64, UInt32, String, Decimal(18,4), DateTime, UUID, FixedString(4), Enum8, IPv4, LowCardinality(String), LowCardinality(Nullable(String)), Nullable element, NULL value, Array element, Map element, empty string, nan, negative zero, nested tuple, 3-arity tuple, named tuple. Also 1-, 2- and 3-arity keys, two-element sets, NOT IN, a second transform (cityHash64), a bitwise-distinct NaN payload pair in both directions, a multi-column subquery set, and a DateTime in a fall-back-transition timezone. Nullable(Tuple(...)) is not constructible as a key (Code: 44) and is excluded rather than worked around.
h Backward compatible? (maintainer-approved exception only) Yes. No new or changed setting, so no SettingsChangesHistory.cpp entry; no serialization, format or version gate; no experimental flag. 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, and a scalar key never reaches the re-pack, so the exactness rule cannot apply to anything that previously worked. Four shapes are re-measured against pristine master and all four match it: identity(k) under NOT IN (atom analysed), identity(k) under a forced minmax index (7, not Code: 277), a 1000-element hex(k) NOT IN subquery (Granules: 999/1000, not 1000/1000), and hex(k) under a forced minmax index (7).
i Invariants and contracts preserved? Two invariants. A set element handed to applyDeterministicDagToColumn must match the transform DAG's input_type layout; the fix restores that at the one site that broke it. And an atom may only claim what its transformed image supports: where the transform may merge distinct key values, the negated spellings decline outright and the positive form is marked relaxed. On declining rather than relying on relaxation: relaxed does defend the negated direction today, because both IN_SET/NOT_IN_SET evaluation sites force can_be_false = true before applying the NOT_IN inversion. Declining is chosen because it does not depend on every present and future consumer applying relaxation before it negates, and because it is what the sibling has path already does for this same merge. One ordering detail is load-bearing and was proven by mutation rather than argued: the set arity is compared BEFORE set_types is collapsed to the one-element vector, and a mutant comparing it afterwards silently answers 0 instead of 1 on a key whose result type is a 1-arity tuple. The arity equality test itself is untouched, so a wrong-arity tuple is still rejected with Code: 124.

Pruning is preserved rather than disabled, and the test proves it per consumer: the partition and primary-key arms assert the Condition: line from EXPLAIN indexes = 1, and the minmax arm names the index in force_data_skipping_indices so a declined atom raises INDEX_NOT_USED. A variant that merely declines the atom answers the value-only arms correctly by full scan and is caught only by those three. Granule counts are deliberately not asserted, since randomized index_granularity moves them. The set skip index has no such assert: it decides usability by column name against its own index expression, so a predicate written on the key column declines regardless of this change, and the repair there is that the query stops failing.

Scope left alone deliberately, and stated once: 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 by this PR. That family belongs to #117238, whose narrowed isInjective reaches this path through out_relaxed.

Validation for this revision: 50/50 randomized runs green (50 OK, 0 FAIL), which themselves randomize session_timezone across DST-transition zones and index_granularity; the key_condition sweep 70/70 on both this build and the previous head, with zero timeouts on either; the primary_key sweep showing the identical 8 ZooKeeper and cluster sandbox failures on both binaries in an equal environment, so none of them is attributable here; 03916_has_to_in, 00674_has_array_enum, 04056_tuple_inside_nullable_casting and 02707_skip_index_with_in green on both; and the full ci/jobs/check_style.py job with zero hits for either changed file.

Session id: cron:clickhouse-impl-self-slot-57:20260908-150400

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @al13n321, could you review this? IN (tuple(...)) on a Tuple-typed key wrapped in a transform arrives as an unpacked set, and the re-pack decision consulted the key expression result type (String for toString(k)) instead of the transform chain input type, so each scalar element was cast to the whole tuple type and raised Code: 53, or, from a String source, parsed into an unrelated tuple and pruned the granule holding the matching row. The layouts this newly admits are marked relaxed and declined under the negated spellings, since toString renders distinct NaN payloads and both instants of a fall-back hour identically.

@rschu1ze

rschu1ze commented Sep 8, 2026

Copy link
Copy Markdown
Member

@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)

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.

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.

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.

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:

  1. 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.
  2. It is not about packed sets. The same row loss reproduces on a scalar Float64 key with a plain literal set, no Tuple and 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 = 0
  1. k NOT IN <Set-engine table> prints Condition: true on master and here alike, so that atom is already declined and the external-Set carrier 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.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4a4d1ad8c with master a63831d1f (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.

Compile time of recompiled translation units

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

Job report

|| function_name == "globalNotNullIn")
return false;

out.relaxed = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. #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.

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.

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.

@nihalzp
nihalzp added this pull request to the merge queue Sep 14, 2026
Merged via the queue into ClickHouse:master with commit 9069f48 Sep 14, 2026
174 of 175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 14, 2026
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.
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
CREATE 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:

  • Reproduces on: 26.8, 26.7, 26.6, 26.5, 26.4, 26.3
  • Does not reproduce on: master, 26.9
  • Tested versions: master, 26.9, 26.8, 26.7, 26.6, 26.5, 26.4, 26.3
  • Tested for context, not a backport target (outside the supported set): 26.6, 26.5, 26.4
  • Measured on the public release build (no private branch build published): 26.9, 26.8, 26.7, 26.6, 26.5, 26.4, 26.3
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.8, 26.7, 26.3.

CC component owner: @CurtizJ @alexey-milovidov

Analysis metadata

comp-mergetree · Severity P2 · Finding phase_d_pr118899

  • Verified against master build f963ba3157d3 (aarch64)
Introducing change: not identified
  • Secondary components: comp-testing

amogiska pushed a commit to amogiska/ClickHouse that referenced this pull request Nov 18, 2026
… 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]>
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants