Skip to content

Reject a value-permuting cast of a has set element for a relaxed atom too - #118706

Merged
nihalzp merged 2 commits into
masterfrom
has-named-tuple-relaxed-atom-118573
Sep 15, 2026
Merged

nihalzp merged 2 commits into
masterfrom
has-named-tuple-relaxed-atom-118573

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Closes: #118573
Related: #115294

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

Fix rows silently dropped by index analysis for has(array_of_named_tuples, key) when the tuple fields are declared in another order and the key is a function of the column.

Description

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.

#115294 rejects such element/key pairs, but only for 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. So the compatibility rule is now applied to relaxed atoms as well, which is where the repro's pruning comes from (sipHash64(t) in 1-element set).


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

Version info

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

… 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 #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: #118573

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fe6464d]

Summary: ✅


AI Review

Summary

This PR tightens has set-index compatibility for relaxed atoms and fixes the reported named-tuple / exception-producing cast regression. The remaining problem is that the new Dynamic fallback is still broad enough to let key analysis prune away granules for queries whose runtime has over a Dynamic key would still throw.

Findings
  • ❌ src/Storages/MergeTree/KeyCondition.cpp:2842: accepting every unmatched pair on the relaxed path when the compared type is Dynamic is still unsound. has on a Dynamic key is executed per concrete variant, and the constant-array path still compares raw Fields with accurateEquals, so incompatible variants keep throwing at runtime. A key like ORDER BY d::String therefore still admits a case such as has(['[1]'], d) over rows where d stores Array(Int64): the relaxed set atom can prune those granules (or even all of them), but the unpruned query would raise BAD_TYPE_OF_FIELD. This is the same exception-suppression bug as the fixed IPv4/UInt32 case, just through Dynamic alternatives.
Tests
  • ⚠️ The added regression covers the named-tuple reorder case and the static IPv4/UInt32 exception case, but it does not exercise the new Dynamic-specific branch at src/Storages/MergeTree/KeyCondition.cpp:2842. A focused transformed-key repro with a Dynamic key that carries an incompatible concrete alternative is still needed.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Narrow or remove the relaxed Dynamic fallback at src/Storages/MergeTree/KeyCondition.cpp:2842 so key analysis cannot suppress runtime has exceptions for incompatible Dynamic alternatives.
  • Add a regression that covers a transformed Dynamic key with an incompatible concrete variant, for example ORDER BY d::String together with has(['[1]'], d) over Array(Int64) rows.

LLVM Coverage Report

Measured on commit fe6464d.

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: 40/45 (88.89%) · 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
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 8, 2026
@nihalzp nihalzp self-assigned this Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fe6464d41 with master 6bdba314e (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, 20 s compile time in total, 7 of them have a recent master baseline.

Job report

Accepting every pair outside the whitelist for a relaxed atom also let key
analysis answer a query whose runtime comparison raises: `has([toIPv4('1.2.3.4')],
x)` over a `UInt32` column under a transformed key could have every part pruned
and return an empty result instead of `Cannot compare DB::IPv4 with unsigned
long`. Relaxing an atom permits false positives in `can_be_true`; it does not
permit turning an exception into a successful answer.

Such a pair is accepted now only when the key side is a `Dynamic`, which carries
the element's value as it is - the case
`03762_has_in_function_key_condition_deterministic_function_chain_explain` pins,
where a `String` element is compared against a `JSON` subcolumn.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed: a pair outside the whitelist is now accepted for a relaxed atom only when the key side is a Dynamic, which carries the element's value as it is. Everything else is declined, so key analysis can no longer answer a query whose runtime comparison raises - has([toIPv4('1.2.3.4')], x) over a UInt32 column under a transformed key reports BAD_TYPE_OF_FIELD again, which the test now asserts.

03762_has_in_function_key_condition_deterministic_function_chain_explain still passes, so the String-element-against-a-JSON-subcolumn pruning it pins is unaffected.

* over a `UInt32` column reports `Cannot compare DB::IPv4 with unsigned long` once a granule
* reaches the filter - into an empty result.
*/
if (only_permuting_casts && WhichDataType(key_type).isDynamic())

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.

The Dynamic exception here is still too broad for relaxed has atoms. has on a Dynamic key is evaluated per concrete variant (FunctionDynamicAdaptor.cpp), and the constant-array path still compares raw Fields via accurateEquals (arrayIndex.h:1291), so incompatible variants still raise by default. For example, with ORDER BY d::String, WHERE has(['[1]'], d) over a Dynamic column that stores Array(Int64) rows still throws, but this fallback accepts the pair, builds a relaxed String set, and can now prune those granules away or even return 0 instead of the exception. That is the same semantics hole as the fixed IPv4/UInt32 case, just through Dynamic alternatives rather than a static key type.

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.

🕵 Verified against a master build that includes this PR (ORDER BY d::String, index_granularity = 1, rows [1], [2], 'x').

The observation holds for a set element that sorts past every row: has(['zzz'], d) returns 0 with the primary key (Granules: 0/3) and raises BAD_TYPE_OF_FIELD (Cannot compare String with Array) under use_primary_key = 0. For an element inside the sorted range, such as has(['[3]'], d), the boundary granule that survives pruning still holds an Array row and the query raises either way.

However, the same discrepancy exists on master independently of this PR for the plain comparison on that key: d = 'zzz' also returns 0 with the primary key and raises (Array does not start with '[' character: while converting 'zzz' to Array(Int64)) without it. Whether a comparison against a Dynamic column raises depends on which variants the scanned rows hold, not on the types alone, so any pruning - or even the order in which other filters are applied - can change it. The IPv4/UInt32 pair this PR now rejects is different: that comparison raises for every row, so pruning can only ever hide the error.

Narrowing the Dynamic fallback would make has stricter than = on the same key without removing the data-dependent behaviour, so I am leaving it as merged. Whether to change how key analysis treats Dynamic altogether is a separate design question; a follow-up would have to cover = as well.

@nihalzp
nihalzp added this pull request to the merge queue Sep 15, 2026
Merged via the queue into master with commit 25a638e Sep 15, 2026
174 checks passed
@nihalzp
nihalzp deleted the has-named-tuple-relaxed-atom-118573 branch September 15, 2026 11:34
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 15, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 15, 2026
Resolves a conflict in KeyCondition.cpp. Both sides added helper functions at
the same spot before checkInHyperrectangle, so the resolution keeps both: this
branch's setMayMatchHiddenNaN/anyBoundsMayHideNaN and master's
rangeOfKeyColumnMayHoldNull/atomIsNullForNullArgument plus the two
KeyCondition::mayReadNullKeyValue overloads from ClickHouse#118706.

The two widenings are independent. mayReadNullKeyValue is a separate pass the
caller runs over the RPN and only relaxes can_be_false for a NULL key value;
the bounds_may_hide_nan mask is threaded into checkInHyperrectangle and relaxes
contains/can_be_false for bounds that excluded NaN. Neither reads the other's
state.

The atom bodies inside checkInHyperrectangle merged without conflict and were
re-checked against master's restructured FUNCTION_IN_RANGE handling: master now
resolves the range through key_range_ptr/key_range_storage for a monotonic
function chain, while key_column stays element.getKeyColumn(), so the mask is
still indexed by the source key column position it is built for.
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov @nihalzp — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

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

Named-tuple field-order drift in has still causes wrong results (missing rows) through transformed key conditions after #115294

4 participants