Repository navigation
Conversation
…ys wrapped in `tuple` `InverseDictionaryLookupPass` reused the `dictGet` key expression verbatim as the left-hand side of the rewritten comparison, while `dictGetKeys` and the `dictionary` table function subquery produce bare key values. For a complex-key dictionary with a single key column called as `dictGet(..., tuple(k))`, this pitted `Tuple(T)` against `T` and the query failed with `ILLEGAL_TYPE_OF_ARGUMENT`. Normalize the key expression for single-column complex keys before building the rewrite: unwrap a syntactic `tuple(k)` into `k`, and extract `tupleElement(expr, 1)` for other one-element-tuple-typed expressions. Simple-key dictionaries are not affected: for them `dictGet` rejects the tuple form even without the optimization.
|
Workflow [PR], commit [81189e8] Summary: ✅
AI ReviewSummaryThis PR broadens Findings❌ Blockers
Final VerdictStatus: Minimum required action: preserve the original exception behavior for signed simple-key probes even when the rewritten predicate's dictionary-side match set is empty, and update LLVM Coverage ReportMeasured on commit 81189e8.
Changed lines: Changed C/C++ lines covered: 98/98 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes5 object files changed (+17.02 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 units79 translation units recompiled, 527 s compile time in total, 79 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
|
@groeneai help investigate why CI fails |
|
None of the 7 red jobs are caused by your change. They are all the same known trunk bug: a use-after-free on a borrowed The five distinct crash signatures across your jobs are STID
Both read counters through raw pointers into a parent Your diff is 3 files: The owning fix is #114940 ("Fix possible crash due to ThreadGroup use-after-free (for async INSERTs/MVs/EXPLAIN ANALYZE)"), merged 2026-08-15 as That fix is not in what CI actually built for you. Your base So a plain re-run will keep failing. Merge master (or rebase) to pick up Report for reference: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114865&sha=bc4e93a29c669b370ea4df6ae40bc4109f7897dc&name_0=PR |
…okup-single-key-tuple
A one-element tuple key expression can be `Nullable`, e.g. produced by `if(cond, tuple(k), NULL)`. `dictGet` accepts such a key and returns `NULL` for `NULL` rows, but the normalization only recognized a plain `Tuple`, so the rewrite still failed with `ILLEGAL_TYPE_OF_ARGUMENT` for this shape. Detect the one-element tuple through `removeNullable`. The `tupleElement` branch handles the `Nullable` case: it propagates `NULL` to the extracted element, and a `NULL` key behaves the same on both sides of the rewrite (`dictGet` returns `NULL`, so the comparison is `NULL`; `NULL IN (...)` is `NULL` as well). A literal `tuple(...)` call is never `Nullable`, so the syntactic-unwrap branch is unaffected. Addresses the review finding in ClickHouse#114865 (comment)
`dictGet` converts the key expression to the dictionary key type via `IDictionary::convertKeyColumns` (using `castColumnAccurate`), so e.g. a `String` key expression is a valid lookup key for a `UUID` key column. The rewrite compared the key expression with values of the key column type directly, so any single-column key whose type has no common supertype with the key column type failed with `NO_COMMON_TYPE`: with the tuple wrapper, bare on a complex-key dictionary, and on simple-key dictionaries alike (the latter two forms were broken this way before this PR as well). Wrap such key expressions in `accurateCast` to the key column type, which matches `castColumnAccurate` semantics. When a common supertype exists (e.g. a narrow integer column against a wide key type), the comparison is already equivalent to the converted lookup and is left untouched, which also keeps the key expression usable for index analysis. A `Nullable` expression that needs such a conversion makes `dictGet` itself throw (at NULL rows the nested column holds default values, and e.g. an empty string does not parse as `UUID`), so the rewrite is skipped there to keep the behavior of the unoptimized query. Multi-column composite keys with a mistyped component have the same pre-existing issue and are intentionally not covered here. Addresses the review finding in ClickHouse#114865 (comment)
`IDictionary::convertKeyColumns` converts the key expression with `castColumnAccurate`, which throws on values the key column type cannot represent: with a `UInt8` key column, `dictGet(..., toInt16(x))` throws on `x = -1` or `x = 300`. The previous commit inserted the mirroring `accurateCast` only when the comparison had no common supertype to work in, so for such lossy-but-comparable type pairs the rewritten comparison was evaluated in the supertype and silently returned false instead of throwing. Narrow the no-cast fast path to total conversions: the key expression is left untouched only when the key column type is itself the least supertype of the two types (a plain widening, e.g. a narrow integer column against a wide key type - also the criterion `canReplaceWithDictGetKeys` uses for the attribute side). Any other mismatch now goes through `accurateCast`, which throws the same `CANNOT_CONVERT_TYPE` as the unoptimized `dictGet`. Addresses the review finding in ClickHouse#114865 (comment)
Two clarifications after probing the fast-path totality: The no-cast fast path (key column type is the least supertype) is total for integer-to-float pairs as well: `getLeastSupertype` refuses e.g. `Int64` with `Float64` (not enough mantissa bits), so an integer expression stays uncast only when the float key type represents every its value exactly. `Date`-family widenings behave identically under `accurateCast` and under the comparison conversion (both follow the date overflow behavior), so no divergence there either. Comment only, no code change. The zero-match constant fold replaces the predicate with `0` without evaluating the key expression, so a conversion error that unoptimized `dictGet` would throw for unconvertible rows disappears together with the lookup. This is pre-existing behavior (bare mistyped keys behave the same on master, like any constant fold that eliminates evaluation) - now stated in a comment and pinned by the test.
When the attribute value belongs to the NULL-keyed row of a dictionary with a `Nullable` key column, the single-match constant fold produced `key_expr = NULL`, which is NULL for every row. `dictGet` misses the NULL row for non-NULL keys and returns the attribute default, so the predicate must be false there. The difference is observable under `NOT`, `isNull`, or in a projection. Skip the equals fold for a NULL key and fall through to the `IN` form: `x IN [NULL]` is false for non-NULL `x` and NULL for NULL `x`, matching `dictGet` (a NULL key expression gives a NULL result, verified for both the outer-Nullable tuple carrier and the bare form). The defect predates this PR: a bare `Nullable` key expression (e.g. `toNullable(id)`) hit the same fold on master, while the tuple spelling used to fail with `ILLEGAL_TYPE_OF_ARGUMENT` and reaches the fold only after the normalization introduced here. Addresses the review findings in ClickHouse#114865 (comment) ClickHouse#114865 (comment)
…itHub incident on 2026-08-17)
|
Hi @yariks5s What's the real flow of getting issue be merged and released in any of future versions? or do I need to do something more here to move forward |
|
This PR will be eventually reviewed and merged by one of the maintainers. If you want it to be merged asap (if reasonable) or need it to be starting from some specific version you can ping the most suitable maintainer for these changes |
|
@artbeglaryan do you think this issue is related? #116399 |
|
@SaltTan yup, it's the same. I discovered it during clickhouse server version upgrade and implement the fix. Hope the team will merge and include into any of release as it's broken since 25.12. We decided for now to turn the flag off and enable only after the fix will be released |
|
@groeneai how we can enforce this fix to be merged into production? |
|
Nothing is blocking it. Measured on head
So there is no gate left to satisfy. What remains is a maintainer with write access choosing to review and merge, which is the ping
Optional and your call: the source change is 96 lines while the test is 430 lines of SQL plus 190 of reference. The implicit key conversion and the NULL-key fold are things I raised on 2026-08-17, and they are a separable defect; splitting them out would leave the tuple unwrap as a small single-cause fix. The size is not a defect, just review latency. On the release half of your question: merging lands it in the next 26.x, not in anything already shipped. Backports to the supported branches need a maintainer to apply Master still has the bug, and the last commit to that pass is from 2026-06-26, so nothing is fixing it in parallel. |
|
@nihalzp Do you think we can merge this? |
|
Your read on docker is right, and neither red on
MinIO deleted
The fix is on master since today 14:42 UTC (#119999): the compose pins now point at |
…re probes Review of the simple-key conversion mirroring asked for three changes. The zero-match fold is applied with an inserted conversion as well, instead of comparing the converted probe with a never-matching `UInt64` value: that sentinel rested on the converted range of native signed integers, which only a comment tied to the value, and it gave up the constant fold, the best case of this optimization, to preserve an error the fold already skips for any other expression in the probe. For the same reason the subquery form is used again with an inserted conversion: `IN` over the empty set built by the dictionary subquery is decided without evaluating the probe, exactly like the fold. The conversion is now the only special handling of a signed simple-key probe, and the fold's comment names it among the expressions the fold skips. The gate on the key component type runs before `unwrapSingleColumnTupleKey`, which used to build and resolve a `tupleElement` node that the gate then discarded for every probe needing a conversion. `singleColumnKeyProbeType` returns the element type of the tuple wrapper without building anything, and the wrapper is removed only once the rewrite is known to proceed. The test gains the cases review asked for. A `MergeTree` table ordered by the probe with one row per granule, where the converted probe is a candidate for index analysis: the row holding the value that does not convert is still read, and `CANNOT_CONVERT_TYPE` fires with the optimization on and off for the single match, several matches and the dictionary subquery. A `LowCardinality(Nullable)` probe: `dictGet` receives it as a full column through the default `LowCardinality` implementation, strips the `Nullable` and yields `NULL` for `NULL` rows, as the rewrite's conversion to `Nullable(UInt64)` does, so the lookup does not throw there and neither does the rewrite. And the no-match predicates on a negative probe, which return `0` with the optimization on while the lookup throws, pinned so the fold's documented behavior is visible in the reference.
The `Fast test` on the previous head showed the rewritten query returning a result where the test expected `CANNOT_CONVERT_TYPE`: the probe `if(id > 0, id, NULL)` over a row with `id = -1`, whose negative value sits in the nested column under the `NULL`. Whether that hidden value is converted at all depends on how the probe column was produced and executed, in the lookup and in the rewrite alike, so the test no longer asserts it, and the comment on `convertSimpleKeyProbe` says so instead of claiming the conversion. The rows the two sides agree on stay pinned: every non-`NULL` row, and `NULL` rows as missed lookups, for `Nullable` and `LowCardinality(Nullable)` probes.
…okup-single-key-tuple
…`05217` Master ClickHouse#120674 made `castColumnAccurate` reject a text value a `Nullable` target cannot represent instead of returning `NULL`, and `IDictionary::convertKeyColumns` converts key expressions with it. `dictGet('conversion_null_scalar', 'attr', s)` for `s = 'bad'` now throws `CANNOT_PARSE_TEXT` with `optimize_inverse_dictionary_lookup` off, and with it on too, since the pass leaves a `String` probe of a `Nullable(UInt8)` key alone. The `nullable conversion results` section asserted the old behaviour, that `'bad'` becomes `NULL` and finds the `NULL`-keyed row. Split the section: the unparsable string asserts the exception with the setting off and on, and the parsable rows keep the result comparison between the two settings. The `Fast test` on `e01a39b7` ran on the merge with that master and failed exactly there: https://github.com/ClickHouse/ClickHouse/actions/runs/35542885571/job/106163846437 Related: ClickHouse#120674
|
@Ergus the description is rewritten to match what is actually shipped (the gate, the single mirrored simple-key conversion, the @nihalzp the two |
…ionary_lookup` builds The pass inserts `tupleElement` and `accurateCast` into the query tree, and a remote shard re-analyzes the rewritten query. Pin that the results over a `Distributed` table are the same with the optimization on and off, with `prefer_localhost_replica` 0 and 1, for the unwrapped `tuple(k)` probe (the reproducer of ClickHouse#121913), a `Tuple(UUID)` column, a signed simple-key probe, and constant and materialized constant probes.
…y_lookup` for floating-point `NaN` and zero keys When the predicate matches a single dictionary key, the pass folds it into `key_expr = key`. A dictionary lookup, like membership in a set, matches floating-point keys by their representation, while `equals` compares them numerically: `NaN` equals nothing, so a probe of a `NaN` key found nothing, and `0` equals `-0`, so a `0.0` probe matched a `-0.0` key the lookup misses. Such keys now keep the `key_expr IN [key]` form, like keys containing `NULL`. The multi-key `IN` fold and the dictionary subquery were already correct.
…okup-single-key-tuple # Conflicts: # src/Analyzer/Passes/InverseDictionaryLookupPass.cpp
Head branch was pushed to by a user without write access
…e_dictionary_lookup` `keyDiffersUnderEquality` only looked at top-level `Float64` values and immediate tuple elements, so a single matched key like `[-0.0]` of type `Array(Float64)` was folded into `key_expr = key`, which also matches `[0.0]`. Recurse through `Array`, `Map` and nested `Tuple` values. Review: ClickHouse#114865 (comment)
|
@Ergus could you please review this and allow the merge? |
|
@artbeglaryan @Ergus @nihalzp @fm4v — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Master now converts a signed simple-key probe with `accurateCast` to `UInt64` before either rewrite arm sees it (ClickHouse#114865), so a `Nullable(Int64)` key reaches `canRestoreNullForKey` already typed `Nullable(UInt64)` and takes the restored-NULL rewrite under `transform_null_in = 1`, as it takes the plain `in` rewrite with the setting off. The conversion stays inside both the restored NULL test and the `nullIn` node, so a negative key still throws `CANNOT_CONVERT_TYPE` like `dictGet`. `int64 key not rewritten` therefore reads 1 now. The row existed to pin the type-equality conjunct, which only a key that reaches the rewrite unconverted can exercise: a `Nullable(UInt32)` probe of the `UInt64` key. Measured on the merged tree: the `UInt32` row reads 0, and 1 on a build without the conjunct; the `Int64` row reads 1, and 0 on master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ted job ClickHouse#122111 made the targeted stateless and integration jobs SKIP instead of ERROR when a test-selection CIDB request times out on every attempt (`CIDBTimeoutError`). The first selection read, the strict previously-failed lookup in `Targeting.get_previously_failed_tests_with_info`, re-wrapped any exception as a plain `RuntimeError`, so a timeout there lost its class before reaching either `except CIDBTimeoutError` handler and the shard still ERRORed ("Failed to load test selection" in the stateless job, an uncaught exception in the integration job). On a `pr-bugfix` PR that drops `Bugfix validation` and fails `Finish Workflow / Post Hooks`. Re-raise `CIDBTimeoutError` unchanged in strict mode. Every other failure (a refused connection, an answered non-OK response) stays wrapped and keeps failing the job, as ClickHouse#114730 intends. Best-effort mode is unchanged. CIDB shows 3 such errors, all on 2026-09-24/25 during the CIDB overload ClickHouse#122111 targets (PRs ClickHouse#118823, ClickHouse#117436, ClickHouse#114865). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since 25.12, the analyzer pass
InverseDictionaryLookupPass(settingoptimize_inverse_dictionary_lookup, enabled by default) rewritesdictGet(dict, attr, key_expr) <op> constinto a comparison of the key expression against dictionary keys: either constants folded fromdictGetKeys(key_expr = const,key_expr IN [consts], or0), or the subquery formkey_expr IN (SELECT <key columns> FROM dictionary(dict) WHERE attr <op> const).The key expression is reused verbatim as the left-hand side, while all rewrite shapes produce bare key values on the right-hand side. A complex-key dictionary with a single key column accepts (and much existing SQL uses) the
tuple()-wrapped call formdictGet(..., tuple(k))— for it, the rewrite pits a one-elementTupleagainst a scalar, and a query that works on every release before 25.12 fails withILLEGAL_TYPE_OF_ARGUMENT. Multi-column keys are unaffected:(k1, k2) IN (SELECT k1, k2 ...)is the standard SQL form and the types line up.How to reproduce
On master the query fails in the constant-fold path:
On 26.3 (before the
dictGetKeysconstant fold existed) the same query fails in the subquery path withIllegal type Tuple(UUID) of argument of function toUUID. The workaround on affected releases isSETTINGS optimize_inverse_dictionary_lookup = 0, which returns the correct result. The bare-key formdictGet(..., k)and multi-column keys work on all versions.The fix
Normalize the key expression once, before both rewrite paths, when the dictionary key is composite with exactly one key column and the key expression resolves to a one-element tuple (including a
Nullableone, e.g. produced byif(cond, tuple(k), NULL)):tuple(k)call is replaced by its argument;Tuple(UUID)) is wrapped intupleElement(expr, 1), which propagatesNULLwith the same semanticsdictGethas forNULLkeys.The rewrite still fires for these queries — the new test asserts the rewritten plans via
EXPLAIN SYNTAX run_query_tree_passes=1for all three constant-fold shapes and both subquery shapes.Simple-key dictionaries are deliberately not unwrapped:
dictGet(simple_dict, attr, tuple(id))is rejected (Illegal type Tuple(UInt64) of argument of function toUInt64) even with the optimization disabled, so normalizing there would make otherwise-invalid queries succeed only while the optimization is on. ATuple-typed dictionary key column cannot conflict with the unwrapping because dictionaries rejectTupleattribute types (Unknown type Tuple(UUID) for dictionary attribute).Implicit key type conversion
Review pointed out a second gap in the same rewrite:
dictGetimplicitly converts the key expression to the key column type (IDictionary::convertKeyColumns, which usescastColumnAccurate— see also02176_dict_get_has_implicit_key_cast), so e.g. aStringkey expression is a valid lookup key for aUUIDkey column, and a lossy expression such asInt16over aUInt8key column throwsCANNOT_CONVERT_TYPEfor values that do not fit. The rewritten comparison converts via a common supertype instead, so a key expression whose type has no common supertype with the key column type failed withNO_COMMON_TYPE, and a lossy one silently compared in the supertype wheredictGetthrows — with the tuple wrapper, bare on a complex-key dictionary, on simple-key dictionaries, and per element of a multi-column composite key alike (every form except the tuple wrapper was broken this way before this PR as well).Behavior change: the rewrite is now applied only where a comparison needs no cast. A key component is compared without one only when the key column type is itself the least supertype of the two types — a provably total widening, e.g. a narrow integer expression against a wide key type, which keeps the expression usable for index analysis (this is the same criterion
canReplaceWithDictGetKeysalready uses for the attribute side, and it is total for integer-to-float pairs as well, sincegetLeastSupertyperefuses e.g.Int64withFloat64). Whenever a component would need a cast — aStringfor aUUIDcolumn, a lossy integer, any element of a composite key — the query keeps thedictGetlookup and behaves exactly as with the optimization off, including its errors, also when no dictionary row matches the predicate. Such queries were rewritten before, with the wrong results or errors described above; they are no longer optimized. Rebuilding the key expression with a publicaccurateCastwas tried and rejected for the general case: the function's analysis-time preparation and settings do not match the lookup's behavior for empty inputs and unselected branches, and a new internal cast function cannot be shipped to remote servers of an older version.The one mirrored conversion is a simple-key dictionary probed with a native signed integer. Its lookup type is always
UInt64whatever type the key is declared with, so with the rule above a dictionary declaredid Int64and probed with anInt64column — the common case — would never be rewritten, which turns the optimization off for every such dictionary (03906_dict_case_distributed_predicate_pushdowndepends on it firing). For that probe the conversion is mirrored withaccurateCast(probe, 'UInt64')(Nullable(UInt64)for aNullableorLowCardinality(Nullable)probe, requested explicitly so thatcast_keep_nullablecannot change it): for integer types it is the same conversioncastColumnAccurateperforms, no setting takes part in it, it prepares for every integer pair, it is evaluated lazily likedictGet, and it is not a new function. A negative probe therefore throwsCANNOT_CONVERT_TYPEwith the optimization on and off wherever the rewritten predicate evaluates the probe — the single-match equality, theINover several keys, the dictionary subquery — including on aMergeTreetable ordered by the probe, where the converted probe is a candidate for index analysis. Like any other expression in the probe, the conversion is not evaluated where the predicate is decided without looking at the probe: the zero-match constant fold and anINover a set that turns out empty replace the predicate with0, and the conversion error disappears together with the lookup, exactly as an error from a user-written cast in the probe does (this is the pre-existing constant-fold behavior, documented in the pass).Review also caught a related pre-existing defect in the single-match constant fold, fixed here since the tuple normalization newly routes the wrapped spelling into it (it used to throw instead): when the attribute value belongs to a key containing
NULL— theNULLkey of a dictionary with aNullablekey column, or a composite key with aNULLcomponent — the fold producedkey_expr = <that key>, which isNULLfor every row, whiledictGetmisses that key for non-NULLprobes and the predicate must be false there (observable underNOT,isNull, or in a projection; a bareNullablekey expression liketoNullable(id)hits the same fold on master). Such a key keeps theIN [key]form, which is false for non-matching probes andNULLforNULLprobes — matchingdictGet. The same fold compared floating-point keys withequals, while the lookup, like a set, matches them by representation: aNaNkey was never matched and a0.0probe matched a-0.0key. A singleNaNor zero key keeps theIN [key]form as well.Finally, a key expression whose shape
dictGetrejects — a tuple with the wrong number of elements, a bare expression for a multi-column key, a tuple for a simple-key dictionary — is not rewritten at all:dictGetvalidates the shape only when the query executes, so such a probe reaches the pass, and the constant fold used to turn theTYPE_MISMATCHorILLEGAL_TYPE_OF_ARGUMENTit raises into a result.The tests
04891_optimize_inverse_dictionary_lookup_single_key_tuple,05217_inverse_dictionary_lookup_conversion_semantics,05218_inverse_dictionary_lookup_key_comparison,05219_inverse_dictionary_lookup_key_type_boundariesand05220_inverse_dictionary_lookup_simple_key_declared_typepin the rewritten plans, the kept lookups, the preserved errors, and result equality with the optimization on and off for all of the above.05237_inverse_dictionary_lookup_distributedchecks the same result equality over aDistributedtable withprefer_localhost_replica0 and 1, where remote shards re-analyze the insertedtupleElementandaccurateCast.05238_inverse_dictionary_lookup_float_keyscovers the floating-point keys. All existingoptimize_inverse_dictionary_lookuptests pass unchanged.Backport
This is a regression in an official stable release (25.12) affecting all later releases, including 26.3 LTS. Please consider labeling for backport to 26.3 (
v26.3-must-backport).Closes: #116399
Closes: #121913
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
optimize_inverse_dictionary_lookuprewritingdictGetcomparisons incorrectly: complex-key dictionaries with a single key column called with atuple()-wrapped (possiblyNullable) key expression failed withILLEGAL_TYPE_OF_ARGUMENT; key expressions that rely ondictGet's implicit key type conversion (e.g. aStringexpression for aUUIDkey) failed withNO_COMMON_TYPE, and lossy ones silently returned results wheredictGetthrows; a match on a dictionary key containingNULLproducedNULLinstead of false; a single matching floating-pointNaNor zero key produced wrong results; and mismatched key shapes were folded to a result instead of thedictGeterror. Key expressions that would need a conversion are no longer rewritten and keep thedictGetlookup, except a signed integer probe of a simple-key dictionary, which is converted to theUInt64lookup type the waydictGetconverts it.Workflow [PR]
Sync PR [sync-upstream/pr/114865]
Version info
26.10.1.1769-master(included in26.10and later)