Skip to content

Fix notHas key type compatibility - #115294

Merged
nihalzp merged 17 commits into
masterfrom
continue-pr-115233-not-has-key-type
Sep 7, 2026
Merged

nihalzp merged 17 commits into
masterfrom
continue-pr-115233-not-has-key-type

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Prevent KeyCondition from compiling has / notHas constant arrays into set atoms when raw Field equality differs from conversion to the primary-key type. This avoids incorrect pruning for representable cross-type values such as String against Enum or unpadded String literals against FixedString keys, while retaining safe composite integer and transformed-key pruning.

The same rule also declines two cases where the conversion is not equivalent to the runtime comparison: a named tuple whose element names are ordered differently from the key tuple (the cast matches elements by name, has compares them positionally), and a Dynamic constant that holds floating-point values (a Dynamic names no children at the type level, so the floating-point guard now runs on the alternatives the constant column actually occupies).

This cleanly supersedes the structurally stacked original branch while preserving its intended three-file fix.

Related: #115233
Related: #109926

Changelog category (leave one):

  • Bug Fix

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

  • Fixes incorrect primary-key pruning for has and notHas when array element types differ from the key type, such as String literals against Enum or FixedString keys.

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

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9db14ac]

Summary: ✅


AI Review

Summary

This PR tightens KeyCondition so has and notHas only build exact set atoms when the runtime Field comparison matches the cast-to-key semantics. The correctness fixes around Enum, FixedString, named tuples, and Dynamic look good, but one part of the promised optimization retention is still missing: cross-width array values that remain semantically exact no longer keep the primary-key set atom.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/KeyCondition.cpp:2594-2603] The new recursive compatibility rule now admits array pairs like Array(Int64) against an Array(Int8) key as safe, but the set builder still aborts once canBeSafelyCast fails because Array targets cannot use the accurateCastOrNull fallback. The new regression test already proves the gap: tests/queries/0_stateless/05048_not_has_nested_mixed_sign_key_condition.reference:69-75 shows Condition: true for notHas([[toInt64(2)]], a) instead of an exact set atom. That means the tuple half of the earlier regression is fixed, while the array half still drops exact primary-key pruning for same-carrier values that has compares exactly at runtime.
Final Verdict

Changes requested: the remaining array case still contradicts the stated goal of retaining safe composite pruning.

LLVM Coverage Report

Measured on commit 9db14ac.

Metric Baseline Current Δ
Lines 88.60% 88.70% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 81.00% +0.10%

Changed lines: Changed C/C++ lines covered: 106/118 (89.83%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 18, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Outdated
const auto set_type = removeNullable(recursiveRemoveLowCardinality(set_element_type));
const auto key_type = removeNullable(recursiveRemoveLowCardinality(key_column_type));

return set_type->equals(*key_type) || (isNativeInteger(set_type) && isNativeInteger(key_type));

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.

areTypesCompatibleForHasSetIndex is stricter than has's actual raw-Field equality for composite numeric values. In the tuple/array cases from 03733_has_function_key_condition_explain, the constant side is still a tree of integer Fields, so has([(10, 0)], key_tuple) / has([[10, 11]], arr_key) can be lowered exactly after tryPrepareSetColumnsForIndex; the only thing that changed here is that the declared types are Tuple(UInt64, UInt64) / Array(UInt64) on the literal side versus Tuple(UInt32, UInt32) / Array(UInt32) in the key. Requiring top-level DataType::equals therefore drops exact primary-key pruning for those default-path queries even though this PR is only trying to block semantic mismatches like String vs Enum. Can this recurse through tuples/arrays and apply the leaf rule (equals or both native integers`) per element instead of rejecting the whole composite type up front?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Addressed: compatibility now recurses through Tuple and Array elements, accepting each pair when equal or both native integers. The exact set atom is retained for the composite numeric cases.

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.

This is still open on the Array half of the original point. areTypesCompatibleForHasSetIndex now admits cross-width arrays at src/Storages/MergeTree/KeyCondition.cpp:2793-2797, but tryPrepareSetColumnsForIndex still bails out as soon as canBeSafelyCast fails because the accurateCastOrNull fallback rejects Array targets at src/Storages/MergeTree/KeyCondition.cpp:2600-2603.

The new regression test already shows the effect: tests/queries/0_stateless/05048_not_has_nested_mixed_sign_key_condition.reference:69-75 still gets Condition: true for notHas([[toInt64(2)]], a) instead of an exact set atom. So the tuple case is fixed, but the array case from the original review is still losing primary-key pruning.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9db14ac8d with master 875e0642e (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.

Object file sizes

2 object files changed (+27.01 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/KeyCondition.cpp.o 1.42 MiB 1.44 MiB +27.00 KiB (+1.86%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Aug 19, 2026
@nihalzp nihalzp self-assigned this Aug 19, 2026
An empty array has element type `Nothing`, so the type-compatibility check
introduced here rejected it and `has([], key)` stopped pruning. The set is
empty in that case, so the atom is false for every key value regardless of
the key type - allow it explicitly.

This also restores the `03762_...` and `03773_...` references to their
`master` contents: with the relaxed carve-out for transformed keys, those
plans are unchanged by this pull request.
For a key built from a chain of deterministic injective functions, the set
elements are pushed through that same chain before the comparison, so the
type whose equality semantics must match the array element type is the
chain's input - the column `has` compares against - and not the key
expression result. Comparing against the key expression result disabled
pruning for keys such as `ORDER BY reverse(tuple(reverse(p), hex(p)))`.

Also move the compatibility check after the empty-array folding, so that
`has([], key)` keeps folding to a constant instead of being rejected for
its `Nothing` element type.
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…not-has-key-type

Master reworked `tryPrepareSetIndexForHas` and greatly extended
`04510_not_has_function_explain` in the meantime. The test file conflict is
resolved in favour of master's version, with this branch's `Enum` regression
coverage re-appended at the end.
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Address review: `has` compares the original array element with the key value
byte-for-byte, while the set index casts the element to the key type, which
pads `FixedString` values with zero bytes. So `notHas(['V0'], fs)` with
`fs FixedString(3)` could prune the row `toFixedString('V0', 3)` even though
the runtime predicate is true there. `areTypesCompatibleForHasSetIndex` now
declines any pair involving `FixedString` unless the types are identical.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
… cast

`has` compares array elements with the key values as raw `Field`s, while
`MergeTreeSetIndex` converts the elements to the key type with an accurate
cast. The compatibility helper previously blocked only the known-bad `Enum`
and `FixedString` pairs, still allowing pairs like `DateTime` vs `Date`
(seconds vs days: `has` is false at runtime while the cast maps the element
onto the matching day) and `IPv4` vs `UInt32` (the raw comparison is not
even defined), so `notHas` could prune rows that satisfy the predicate.

Flip the helper to a whitelist mirroring `RewriteHasToInPass`: identical
types after stripping `Nullable` and `LowCardinality`, two native integers,
an `Enum` next to a native integer (`has` compares enums numerically, see
`00674_has_array_enum`), `Nothing` on the element side, containers
element-wise, and a `Variant` when every alternative is admissible. A
`Dynamic` element is checked through the `Variant` of the types the
constant column actually holds, so the pruning for `Dynamic` elements
carrying compatible values is kept.

Addresses the AI review blocker of 2026-08-25.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115294&sha=47d8d03a62c562bfc1e9a4adb9c2091d2f4a02fd&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%204%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. test_storage_kafka/test_partition_affinity.py::test_partition_affinity_settings_validation failed with kafka.errors.NodeNotReadyError in kafka_setup_teardown (the Kafka broker was not ready when the admin client connected) — an infrastructure flake unrelated to this PR (which only touches KeyCondition and stateless tests), with no other occurrence on master in the last 30 days per CIDB.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. This is a defect in the integration-test helper, unrelated to this PR.

get_admin_client (tests/integration/helpers/kafka/common.py:154) already retries broker-not-ready failures, but its except lists only kafka.errors.NoBrokersAvailable. KafkaAdminClient.__init__ probes the broker twice: once with no node id (admin/client.py:212) and once against the controller id (:219 -> _refresh_controller_id -> :279). kafka-python-ng 2.2.3 reports the same not-ready condition under a different class in those two cases, and documents it on KafkaClient.check_version: "NodeNotReadyError (if node_id is provided), NoBrokersAvailable (if node_id is None)". So the retry loop covers only the first half of the window it was written for, and NodeNotReadyError appears nowhere in the repository.

I will follow up here with a separate PR.

@groeneai

Copy link
Copy Markdown
Collaborator

#116700

It turned out to be a real gap in the test helper rather than only an infrastructure flake.
get_admin_client already retries a broker that is not up yet, but its except named only
kafka.errors.NoBrokersAvailable, and KafkaAdminClient construction picks the exception class by
whether the readiness probe names a node, so the controller probe raises NodeNotReadyError and fell
straight through the loop. The PR catches both classes, keeps IncompatibleBrokerVersion and
UnrecognizedBrokerVersion failing fast, routes the 17 remaining direct constructions through the
helper, and adds a broker-free regression test.

Inside a `Tuple`/`Array`/`Map`, `has` compares the children of two container
`Field`s with the plain `Field::operator==` (the `accurateEquals` same-type
fast path), which requires the same carrier type: a nested `UInt64` child
never equals a nested `Int64` child even for the same value, while the set
index casts the element onto the matching key value. Building an exact set
atom for such a pair could prune rows that satisfy the predicate under
`notHas`.

Admit a nested pair only when both raw `Field`s use the same integer
carrier: two native integers of the same signedness, or an `Enum` (carried
as `Int64`) next to a signed native integer. The same applies to multiple
key arguments, where the right-hand side of `has` is a tuple of key columns.

Addresses the AI review blocker of 2026-08-28.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115294&sha=1fdf12ef0956e8f2b3d37c5987e69268463ec21f&name_0=PR
#115294
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Aug 30, 2026
`get_admin_client` retries the construction of a `KafkaAdminClient` so that a
broker which is not up yet does not fail a test. Nothing in the tree failed if
that `except` clause was narrowed back to a single class, so add
tests/integration/test_kafka_bad_messages/test_admin_client_helper.py: two
functions and four parametrized ids, driving the helper with a stub constructor
and needing neither a Kafka broker nor a ClickHouse instance.

Two ids cover the readiness class that has to be retried, `NoBrokersAvailable`
when the constructor's probe is cluster-wide and `NodeNotReadyError` when it
targets a specific node. Two cover the version faults that have to fail fast,
`IncompatibleBrokerVersion` and `UnrecognizedBrokerVersion`. Both functions
assert the number of attempts; without that an arm which succeeded on its first
attempt would pass as well, so the ids would show only that nothing escaped and
never that a retry happened.

Three mutations of the `except` clause redden pairwise disjoint sets of those
four ids, so no id is redundant and no mutation is a blanket break. Dropping
`NodeNotReadyError` from the tuple reddens its id alone, dropping
`NoBrokersAvailable` reddens its id alone, and a bare `except Exception` reddens
only the two version ids, which then report the loop's exhaustion message
instead of the version mismatch itself. The first of the three mutations is
byte-identical to the line as it stood before the retry was widened, so it is
also the negative control.

The test passes `retries=3` explicitly. Each failed attempt sleeps one second,
and three is the smallest budget that admits two failures followed by a success.

Also wrap the two class names in the comment above the loop in inline code
blocks, as .claude/CLAUDE.md asks for.

CI report of the failure this covers:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115294&sha=47d8d03a62c562bfc1e9a4adb9c2091d2f4a02fd&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%204%2F6%29
Related: ClickHouse#115294

Co-Authored-By: Claude Opus 5 <[email protected]>
Covers the two cases fixed for the review: a named tuple whose element names are
ordered differently must not produce an exact `has` set atom (the cast reorders
by name while `has` compares positionally), and a `Dynamic` constant that holds
floating-point values must be judged by what the column occupies, so `notHas`
does not prune NaN rows.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 9db14ac: both AI-review findings are addressed (see the two review threads), plus a master merge and a new test 05055_not_has_tuple_layout_and_variant_key_condition.

On the reds of 3e159ce, neither of which this change can produce (it only touches has / notHas set-atom construction in KeyCondition):

@groeneai, could you investigate https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115294&sha=3e159cedda71be536e30b7002b9cb52305bb06ca&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 and provide a fix in a separate PR? If a fix for #108845 is already in progress, please link it here.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

No fix PR is in progress, and there is nothing newer in that report than what I have already measured. 3e159cedda71 is the 2026-08-29 occurrence, and it is still the latest failure of this test anywhere. It carries the exact signature from #108845 (1_1_1_0_3 rewritten to Nullable(String) with read_rows = 10000 instead of the metadata-only clone), and its own rerun diagnosis is 155 passes with the same randomized settings. Over 90 days the test has 23 failures across 19 pull requests and none on master, so I agree it is unrelated to your change.

The investigation is finished and the change is small. What blocks it is one decision I cannot make myself, posted at #108845 (comment) and still unanswered:

  • If the full rewrite is a defect, the first step is branch-level attribution in canSkipConversionToNullable. It has five silent return false branches today (src/Storages/MergeTree/MutateTask.cpp:3536), so no report can name the branch that refused, and I do not want to open a third PR into that function on a guess. The fix follows once a real occurrence names the branch.
  • If the metadata-only path is best-effort by design, which was the first reason given when Make MutateTask metadata/commands drift observable #110157 was closed, then the fallback is intended and the change belongs in this test's assertion instead. I would rather take that shape from you than guess it, since the retry approach was already rejected on Fix flaky test 02669_alter_modify_to_nullable #109205.

Which of the two is it? Either answer unblocks this immediately.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 41 analysed

1 improved query(s). K_source=6 K_base=30 flagged=1/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 1 improved

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 17 improvement 101 66 -34.7% <0.0001

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 209a3c42-e095-4646-b06e-c4e10ccace27
  • MIRAI run: 25bd3221-5e9e-4e3e-8105-6c00b79bc2b3
  • PR check IDs:
    • clickbench_1231007_1788556252
    • clickbench_1231013_1788556252
    • clickbench_1231019_1788556252
    • tpch_adapted_1_official_1231030_1788556252
    • tpch_adapted_1_official_1231042_1788556252
    • tpch_adapted_1_official_1231078_1788556252

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@nihalzp
nihalzp added this pull request to the merge queue Sep 7, 2026
Merged via the queue into master with commit 735019c Sep 7, 2026
175 checks passed
@nihalzp
nihalzp deleted the continue-pr-115233-not-has-key-type branch September 7, 2026 12:10
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 9, 2026
Master landed its own `has`-path set-index exactness rule (ClickHouse#115294, ClickHouse#116381):
`areTypesCompatibleForHasSetIndex` + `areSetAndKeyTypesCompatibleForHas`, called
from `tryPrepareSetIndexForHas`, plus the `Variant`/`Dynamic` in-use-alternatives
recovery `narrowVariantToOccupiedAlternatives`. That supersedes this branch's
`has` half, which reached the same property through a
`composite_field_identity_is_enough` flag inside `tryPrepareSetColumnsForIndex`.

Keeping both would be their conjunction, so it would silently narrow decisions
taken under review: master admits an `Enum8` element against an `Int8` key and
prunes it exactly (its comment cites `00674_has_array_enum`), which this
branch's rule declines. Taking "ours" in the conflicted region would delete
`narrowVariantToOccupiedAlternatives` outright.

So `src/` is reset to master's content verbatim here, together with the six
existing test files this branch had re-recorded for the `has` rule. The `IN`
half, which master has not fixed and which still drops rows, is re-applied on
top in a later commit.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 9, 2026
Index analysis builds an exact set atom out of constants it converted into the
key column's type, while runtime `IN` membership converts the key into the set
element's type. When those two conversions are not mutual, the atom names key
values the predicate does not match and misses ones it does, so single-point key
range pruning (partition pruning and minmax) drops the part holding a matching
row and the row silently disappears.

`tryPrepareSetColumnsForIndex` casts each element with `castColumnAccurateOrNull`
and drops only the elements whose cast produced NULL; whatever survives is
treated as exact. A conversion that succeeds without preserving equality was
never considered. Measured on master, against an `ENGINE = Memory` table holding
the same rows:

  UInt64 key,  k NOT IN (SELECT '01')                    -> [2]         vs [1,2]
  String key,  s IN (SELECT 1)          rows '01','1'    -> ['1']       vs ['01','1']
  String key,  PARTITION BY length(s), s IN (SELECT 1)   -> ['1']       vs ['01','1']
  UInt8 key,   k IN (SELECT CAST(5, 'Bool'))             -> [1]         vs [1,5]
  String key,  k NOT IN (a Variant(String, UInt8))       -> ['4']       vs ['3','4']
  (String, UInt64) key, (a, b) IN (SELECT (1, 1))        -> [('1',1)]   vs both rows

Marking the atom relaxed does not fix this: `relaxed` only forbids trusting
`can_be_false`, and four of the six cases prune through `can_be_true` instead -
the `PARTITION BY length(s)` case is an atom master already marks relaxed. So the
atom is declined outright, and the check is deliberately not gated on
`!out.relaxed` the way the `has` sibling is.

The rule mirrors the one master merged for `has` in ClickHouse#115294 and ClickHouse#116381: a
type-level gate at the caller, before the columns are prepared. It admits two
shapes, both sides first normalized with
`removeNullable(recursiveRemoveLowCardinality(...))`: `equals`-equal types that
also agree on custom names, and two plain integers. `equals` alone is not enough
because `Bool` is `equals`-equal to `UInt8` yet clamps every nonzero value to 1;
`getName()` equality is too strict in the other direction, since it would decline
a `DateTime('UTC')` element against a `DateTime('Europe/Moscow')` key, a pair that
prunes correctly today because a time zone is display metadata no `Field` carries.

It is narrower than `areTypesCompatibleForHasSetIndex` on purpose: that one also
admits `Enum`/native-integer, `Nothing` and container pairs, which are sound for a
raw `Field` comparison but not once `IN` casts the key into the set type, where a
narrowing conversion throws rather than nulling.

Rejected alternatives: gating on polarity (a pair can be unsound in either
direction, so it would need a directional injectivity analysis per type pair);
reusing the `has` predicate verbatim (strictly less safe here); a value-level
round-trip probe (catches the first case, but not the ones where the element
round-trips and a different key value collides with it).

The type-unpacking loop is extracted into `unpackSetTypesToKeyArity` and shared
with the `has` path; returning false where the arity is unreachable preserves that
caller's behaviour exactly.
raimannma pushed a commit to raimannma/ClickHouse that referenced this pull request Sep 15, 2026
… too

```sql
CREATE TABLE t (t Tuple(b UInt8, a UInt8)) ENGINE = MergeTree ORDER BY sipHash64(t)
SETTINGS index_granularity = 1, add_minmax_index_for_numeric_columns = 0;
INSERT INTO t VALUES ((1, 2)), ((3, 4)), ((5, 6));

SELECT sum(has([CAST((1, 2), 'Tuple(a UInt8, b UInt8)')], t)) FROM t;          -- 1
SELECT count() FROM t WHERE has([CAST((1, 2), 'Tuple(a UInt8, b UInt8)')], t); -- 0
```

`has` compares named tuples positionally, while the set index builder casts the
element to the key column type and a `CAST` between named tuples matches fields
by name. The transformed set therefore names a key value that no matching row
holds, and the granule - or the partition, with `PARTITION BY sipHash64(t)` -
that holds the matching row is pruned.

The compatibility rule of ClickHouse#115294 covers this, but it was applied only to atoms
that are not relaxed. Relaxing an atom merely allows `can_be_false`; the
positive direction still trusts `can_be_true`, which is sound only when the
transformed set over-approximates the runtime predicate - and a by-name cast
does not.

A relaxed atom is checked now as well, but only for the casts that make the
element stand for a *different* value: the by-name mappings of named tuples and
of `Enum` codes. The rest of the rule is about the set being an exact image of
the predicate rather than an over-approximation of it, which a relaxed atom does
not need - a `String` element against a `Dynamic` key keeps pruning, as
`03762_has_in_function_key_condition_deterministic_function_chain_explain` pins.

Closes: ClickHouse#118573

Co-Authored-By: Claude Opus 5 (1M context) <[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

comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... 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.

4 participants