Repository navigation
Fix notHas key type compatibility - #115294
Conversation
|
Workflow [PR], commit [9db14ac] Summary: ✅
AI ReviewSummaryThis PR tightens Findings
Final VerdictChanges requested: the remaining array case still contradicts the stated goal of retaining safe composite pruning. LLVM Coverage ReportMeasured on commit 9db14ac.
Changed lines: Changed C/C++ lines covered: 106/118 (89.83%) · Uncovered code |
| 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)); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
🕵 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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes2 object files changed (+27.01 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 20 s compile time in total, 7 of them have a recent master baseline. |
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.
…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.
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]>
… 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.
|
🕵 @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. |
|
Acknowledged. This is a defect in the integration-test helper, unrelated to this PR.
I will follow up here with a separate PR. |
|
It turned out to be a real gap in the test helper rather than only an infrastructure flake. |
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
`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]>
…constants to occupied alternatives
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.
|
🕵 Pushed 9db14ac: both AI-review findings are addressed (see the two review threads), plus a master merge and a new test On the reds of 3e159ce, neither of which this change can produce (it only touches
@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. |
|
No fix PR is in progress, and there is nothing newer in that report than what I have already measured. 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:
Which of the two is it? Either answer unblocks this immediately. |
|
📊 Cloud Performance Report 🟢 AI verdict: 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)
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
|
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.
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.
… 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]>
Prevent
KeyConditionfrom compilinghas/notHasconstant arrays into set atoms when rawFieldequality differs from conversion to the primary-key type. This avoids incorrect pruning for representable cross-type values such asStringagainstEnumor unpaddedStringliterals againstFixedStringkeys, 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,
hascompares them positionally), and aDynamicconstant that holds floating-point values (aDynamicnames 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
hasandnotHaswhen array element types differ from the key type, such asStringliterals againstEnumorFixedStringkeys.Workflow [PR]
Sync PR [sync-upstream/pr/115294]