Skip to content

Fix optimize_inverse_dictionary_lookup for single-column complex keys wrapped in tuple - #114865

Merged
fm4v merged 36 commits into
ClickHouse:masterfrom
artbeglaryan:fix-inverse-dict-lookup-single-key-tuple
Oct 7, 2026
Merged

fm4v merged 36 commits into
ClickHouse:masterfrom
artbeglaryan:fix-inverse-dict-lookup-single-key-tuple

Conversation

@artbeglaryan

@artbeglaryan artbeglaryan commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Since 25.12, the analyzer pass InverseDictionaryLookupPass (setting optimize_inverse_dictionary_lookup, enabled by default) rewrites dictGet(dict, attr, key_expr) <op> const into a comparison of the key expression against dictionary keys: either constants folded from dictGetKeys (key_expr = const, key_expr IN [consts], or 0), or the subquery form key_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 form dictGet(..., tuple(k)) — for it, the rewrite pits a one-element Tuple against a scalar, and a query that works on every release before 25.12 fails with ILLEGAL_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

CREATE TABLE dict_source (k UUID, k2 String, attr String) ENGINE = MergeTree ORDER BY k;
INSERT INTO dict_source VALUES
    ('11111111-1111-1111-1111-111111111111', 'a', 'paywall'),
    ('22222222-2222-2222-2222-222222222222', 'b', 'onboarding');

CREATE DICTIONARY single_key_dict (k UUID, attr String DEFAULT '')
PRIMARY KEY k
SOURCE(CLICKHOUSE(TABLE 'dict_source'))
LIFETIME(0)
LAYOUT(COMPLEX_KEY_HASHED());

CREATE TABLE data (k UUID, k2 String) ENGINE = MergeTree ORDER BY k;
INSERT INTO data VALUES
    ('11111111-1111-1111-1111-111111111111', 'a'),
    ('33333333-3333-3333-3333-333333333333', 'c');

-- Must return 1, but fails since 25.12:
SELECT count() FROM data WHERE dictGet('single_key_dict', 'attr', tuple(k)) = 'paywall';

On master the query fails in the constant-fold path:

Code: 43. DB::Exception: Illegal types of arguments (`Tuple(UUID)`, `UUID`) of function `equals`. (ILLEGAL_TYPE_OF_ARGUMENT)

On 26.3 (before the dictGetKeys constant fold existed) the same query fails in the subquery path with Illegal type Tuple(UUID) of argument of function toUUID. The workaround on affected releases is SETTINGS optimize_inverse_dictionary_lookup = 0, which returns the correct result. The bare-key form dictGet(..., 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 Nullable one, e.g. produced by if(cond, tuple(k), NULL)):

  • a syntactic tuple(k) call is replaced by its argument;
  • any other tuple-typed expression (e.g. a column of type Tuple(UUID)) is wrapped in tupleElement(expr, 1), which propagates NULL with the same semantics dictGet has for NULL keys.

The rewrite still fires for these queries — the new test asserts the rewritten plans via EXPLAIN SYNTAX run_query_tree_passes=1 for 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. A Tuple-typed dictionary key column cannot conflict with the unwrapping because dictionaries reject Tuple attribute types (Unknown type Tuple(UUID) for dictionary attribute).

Implicit key type conversion

Review pointed out a second gap in the same rewrite: dictGet implicitly converts the key expression to the key column type (IDictionary::convertKeyColumns, which uses castColumnAccurate — see also 02176_dict_get_has_implicit_key_cast), so e.g. a String key expression is a valid lookup key for a UUID key column, and a lossy expression such as Int16 over a UInt8 key column throws CANNOT_CONVERT_TYPE for 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 with NO_COMMON_TYPE, and a lossy one silently compared in the supertype where dictGet throws — 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 canReplaceWithDictGetKeys already uses for the attribute side, and it is total for integer-to-float pairs as well, since getLeastSupertype refuses e.g. Int64 with Float64). Whenever a component would need a cast — a String for a UUID column, a lossy integer, any element of a composite key — the query keeps the dictGet lookup 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 public accurateCast was 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 UInt64 whatever type the key is declared with, so with the rule above a dictionary declared id Int64 and probed with an Int64 column — the common case — would never be rewritten, which turns the optimization off for every such dictionary (03906_dict_case_distributed_predicate_pushdown depends on it firing). For that probe the conversion is mirrored with accurateCast(probe, 'UInt64') (Nullable(UInt64) for a Nullable or LowCardinality(Nullable) probe, requested explicitly so that cast_keep_nullable cannot change it): for integer types it is the same conversion castColumnAccurate performs, no setting takes part in it, it prepares for every integer pair, it is evaluated lazily like dictGet, and it is not a new function. A negative probe therefore throws CANNOT_CONVERT_TYPE with the optimization on and off wherever the rewritten predicate evaluates the probe — the single-match equality, the IN over several keys, the dictionary subquery — including on a MergeTree table 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 an IN over a set that turns out empty replace the predicate with 0, 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 — the NULL key of a dictionary with a Nullable key column, or a composite key with a NULL component — the fold produced key_expr = <that key>, which is NULL for every row, while dictGet misses that key for non-NULL probes and the predicate must be false there (observable under NOT, isNull, or in a projection; a bare Nullable key expression like toNullable(id) hits the same fold on master). Such a key keeps the IN [key] form, which is false for non-matching probes and NULL for NULL probes — matching dictGet. The same fold compared floating-point keys with equals, while the lookup, like a set, matches them by representation: a NaN key was never matched and a 0.0 probe matched a -0.0 key. A single NaN or zero key keeps the IN [key] form as well.

Finally, a key expression whose shape dictGet rejects — 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: dictGet validates the shape only when the query executes, so such a probe reaches the pass, and the constant fold used to turn the TYPE_MISMATCH or ILLEGAL_TYPE_OF_ARGUMENT it 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_boundaries and 05220_inverse_dictionary_lookup_simple_key_declared_type pin 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_distributed checks the same result equality over a Distributed table with prefer_localhost_replica 0 and 1, where remote shards re-analyze the inserted tupleElement and accurateCast. 05238_inverse_dictionary_lookup_float_keys covers the floating-point keys. All existing optimize_inverse_dictionary_lookup tests 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):

  • 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 optimize_inverse_dictionary_lookup rewriting dictGet comparisons incorrectly: complex-key dictionaries with a single key column called with a tuple()-wrapped (possibly Nullable) key expression failed with ILLEGAL_TYPE_OF_ARGUMENT; key expressions that rely on dictGet's implicit key type conversion (e.g. a String expression for a UUID key) failed with NO_COMMON_TYPE, and lossy ones silently returned results where dictGet throws; a match on a dictionary key containing NULL produced NULL instead of false; a single matching floating-point NaN or zero key produced wrong results; and mismatched key shapes were folded to a result instead of the dictGet error. Key expressions that would need a conversion are no longer rewritten and keep the dictGet lookup, except a signed integer probe of a simple-key dictionary, which is converted to the UInt64 lookup type the way dictGet converts it.


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

Version info

  • Merged into: 26.10.1.1769-master (included in 26.10 and later)

…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.
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [81189e8]

Summary: ✅


AI Review

Summary

This PR broadens optimize_inverse_dictionary_lookup substantially: it fixes the single-column complex-key tuple(...) regression, tightens key-shape checks, preserves more conversion semantics, and adds strong stateless/distributed coverage for the new cases. One user-visible semantic hole remains, though: after mirroring simple-key signed probes with accurateCast, the optimization still turns some dictGet conversion exceptions into 0 whenever the rewritten predicate can prove the dictionary-side match set is empty. That is still a behavior change, so the patch is not ready to merge as-is.

Findings

❌ Blockers

  • [src/Analyzer/Passes/InverseDictionaryLookupPass.cpp:623-629, 718-727, 798-845] The new simple-key conversion mirror is still not semantics-preserving when the attribute predicate matches no dictionary rows. dictGet('simple_signed', 'attr', id) converts id to the lookup type before the lookup and throws CANNOT_CONVERT_TYPE on id = -1 regardless of dictionary contents, but the optimized forms now skip that conversion in exactly the empty-match cases: the dictGetKeys path folds to constant 0, and the fallback accurateCast(id, 'UInt64') IN (SELECT ... FROM dictionary(...) ...) path returns constant false on an empty set before touching the left operand. The new test at tests/queries/0_stateless/05220_inverse_dictionary_lookup_simple_key_declared_type.sql:101-110 now pins that divergence instead of catching it. This makes optimize_inverse_dictionary_lookup change a query from an exception to a result based solely on whether any rows satisfy the dictionary-side predicate.
    Suggested fix: when convertSimpleKeyProbe ran, do not use rewrites that can decide false without evaluating the probe (dictGetKeys empty-result folding and the dictionary(...) IN rewrite), or otherwise force the mirrored cast to execute before the empty-set fast path so the conversion error is preserved.
Final Verdict

Status: ⚠️ Request changes

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 05220_inverse_dictionary_lookup_simple_key_declared_type to assert the same result or exception with the optimization on and off for those no-match cases.

LLVM Coverage Report

Measured on commit 81189e8.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 98/98 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 81189e886 with master 5353f5fc0 (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

5 object files changed (+17.02 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Passes/InverseDictionaryLookupPass.cpp.o 274.75 KiB 295.84 KiB +21.09 KiB (+7.68%)

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

79 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.
The matched translation units cost +43.6 s (+9%) in total before that adjustment.

Job report

@artbeglaryan

Copy link
Copy Markdown
Contributor Author

@groeneai help investigate why CI fails

@groeneai

Copy link
Copy Markdown
Collaborator

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 ThreadGroup's parent, which kills the server ("Server died"), so the one named test failure (04233_right_utf8_invalid_utf8_determinism) is just collateral from the shutdown.

The five distinct crash signatures across your jobs are STID 3361-3475, 3718-42fb, 4105-1b04, 3361-4063 and 4105-3be4. All of them bottom out in the same two frames:

  • MemoryTracker::setParent (MemoryTracker.cpp:803) from ThreadStatus::attachToGroupImpl (ThreadStatusExt.cpp:382), and
  • ProfileEvents::Counters::increment (ProfileEvents.cpp:1983), reached from WriteBufferFromS3::makeSinglepartUpload's async callback.

Both read counters through raw pointers into a parent ThreadGroup that has already been freed, which is why it only shows on the s3-storage and TSan jobs.

Your diff is 3 files: InverseDictionaryLookupPass.cpp plus the new stateless test. It does not touch ThreadGroup, MemoryTracker, ProfileEvents, the S3 write path or any thread pool, so an analyzer-pass rewrite cannot produce this.

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 3afb5f7. It makes the nested ThreadGroup hold a ThreadGroupPtr parent, so the raw memory_tracker/performance_counters pointers stay alive.

That fix is not in what CI actually built for you. Your base 639ed3d0 is from 08-14 and is 393 commits behind the fix. The re-run on 08-16 did not help because it reused the merge commit computed on 08-14 (14980f7, parents 639ed3d0 + bc4e93a), so the fix is absent from that build.

So a plain re-run will keep failing. Merge master (or rebase) to pick up 3afb5f7 and push, and these should go green without any change to your diff.

Report for reference: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114865&sha=bc4e93a29c669b370ea4df6ae40bc4109f7897dc&name_0=PR

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

Copy link
Copy Markdown
Contributor Author

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

@yariks5s

Copy link
Copy Markdown
Member

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

@SaltTan

SaltTan commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

@artbeglaryan do you think this issue is related? #116399

@artbeglaryan

artbeglaryan commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor Author

@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

@artbeglaryan

Copy link
Copy Markdown
Contributor Author

@groeneai how we can enforce this fix to be merged into production?

@groeneai

Copy link
Copy Markdown
Collaborator

Nothing is blocking it. Measured on head 4904578d just now:

  • combined commit status success across all four contexts (Style check, PR, Mergeable Check, CH Inc sync); 177 check runs, 160 success, 17 skipped, 0 failed;
  • mergeable: MERGEABLE, mergeStateStatus: CLEAN;
  • master's ruleset requires exactly two status checks, Mergeable Check and CH Inc sync, with required_approving_review_count: 0.

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 @ yariks5s pointed you at on 2026-08-19. Two things make that likelier:

  1. Ask the pass author. InverseDictionaryLookupPass.cpp is @ nihalzp's file: 55 of its 65 commits are his, including the original ones from 2025-10-24. He wrote "Fix it" on Exception when optimize_inverse_dictionary_lookup for single-column complex keys wrapped in tuple #116399 on 2026-08-26, and @ PedroTadim asked me there to confirm your PR is the fix, which I did the same day, so both of them already know it exists. @ vdimir is the other listed owner for the dictionary and analyzer areas.

  2. Add a visible Closes #116399 line to the description. The body currently has no issue link, so this PR does not show up in that issue's timeline and merging it will not close the issue.

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 v26.3-must-backport to the merged PR (26.3 is the oldest active release branch right now, and a version label covers that branch plus every newer active one, currently 26.3, 26.6, 26.7, 26.8). Contributors cannot apply it and it only takes effect after merge, so it is worth asking for in the same message as the review request.

Master still has the bug, and the last commit to that pass is from 2026-06-26, so nothing is fixing it in parallel.

@artbeglaryan

Copy link
Copy Markdown
Contributor Author

@nihalzp Do you think we can merge this?

@nihalzp nihalzp self-assigned this Sep 1, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Your read on docker is right, and neither red on 83fab063 comes from your diff.

Integration tests (amd_asan_ubsan, db disk, 7/8) never ran a test. It died in the image pre-fetch, 3/3 attempts on minio/mc:RELEASE.2025-04-16T18-13-26Z:

pull access denied for minio/mc, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
ERROR: Failed to pull the following image(s) after 3 attempt(s): minio/mc:RELEASE.2025-04-16T18-13-26Z

MinIO deleted minio/mc and minio/minio from Docker Hub, so any branch that still pins those names fails this way. Only shard 7/8 pre-fetches mc (it owns the Iceberg REST + Trino compose file), which is why the other seven shards are green.

Finish Workflow / Post Hooks is a consequence of that job, not a separate problem: with the shard failed, praktika dropped Bugfix validation (functional tests, amd64) and (aarch64), and new_tests_check.py then fails a pr-bugfix PR with "A bug fix is validated when at least one per-arch Bugfix validation job reports OK or XFAIL; none did".

The fix is on master since today 14:42 UTC (#119999): the compose pins now point at clickhouse/minio-minio and clickhouse/minio-mc, mirrored from quay.io. Your head predates it, so merging master and re-running clears both reds. No other check on 83fab063 is red, Stateless tests (amd_debug, parallel) included, so the 03906_dict_case_distributed_predicate_pushdown failure from the previous head is gone.

alexey-milovidov and others added 5 commits September 19, 2026 18:00
…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.
…`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
@artbeglaryan

Copy link
Copy Markdown
Contributor Author

@Ergus the description is rewritten to match what is actually shipped (the gate, the single mirrored simple-key conversion, the NULL-key fold), and the changelog entry lists the behavior changes. On the tests: 05220 now repeats the simple_signed_negative cases on MergeTree ORDER BY id with index_granularity = 1 and one row per insert, so -1, 1 and 2 sit in separate granules. The exception fires in every shape with the optimization on and off; KeyCondition can't drop the -1 granule because the sign change sits inside the key range. The LowCardinality(Nullable) probe is covered as well, see the thread.

@nihalzp the two Fast test reds on e01a39b7 came from master, not from the branch. CI builds the merge with master, and master had just taken #120674, which makes the accurate String to Nullable cast throw instead of returning NULL, and skips NULL rows when the source is Nullable. So in 05217, dictGet('conversion_null_scalar', 'attr', 'bad') now throws CANNOT_PARSE_TEXT with the optimization off, and on as well since the gate leaves that probe alone. I split that section: the unparsable row asserts the exception both ways, the parsable rows keep the result comparison. It's your test, so shout if you'd shape it differently. The hidden-negative assertion in 05220 went for the same reason. Master is merged in and the related tests pass on it.

…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.
@fm4v
fm4v enabled auto-merge September 24, 2026 16:41
fm4v and others added 2 commits September 24, 2026 18:46
…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
auto-merge was automatically disabled September 30, 2026 07:58

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

Copy link
Copy Markdown
Contributor Author

@Ergus could you please review this and allow the merge?

@fm4v
fm4v enabled auto-merge October 7, 2026 17:35
@fm4v
fm4v dismissed Ergus’s stale review October 7, 2026 17:35

Looks good

@fm4v
fm4v disabled auto-merge October 7, 2026 17:35
@fm4v
fm4v added this pull request to the merge queue Oct 7, 2026
Merged via the queue into ClickHouse:master with commit 8710ea8 Oct 7, 2026
149 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@artbeglaryan @Ergus @nihalzp @fm4v — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@artbeglaryan

Copy link
Copy Markdown
Contributor Author

@fm4v could this one and #117355 be backported into 26.8? It is a regression since 25.12 (a dictGet(..., tuple(k)) query that worked on every earlier release fails with ILLEGAL_TYPE_OF_ARGUMENT with the default settings), and 26.8 is the LTS we run.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 2, 2026
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]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 24, 2026
…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]>
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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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

10 participants