Skip to content

Extend InverseDictionaryLookupPass to support IN and notIn operators for dictionary lookups - #100001

Merged
alexey-milovidov merged 45 commits into
ClickHouse:masterfrom
euvre:resolve-issue-99500
Nov 1, 2026
Merged

alexey-milovidov merged 45 commits into
ClickHouse:masterfrom
euvre:resolve-issue-99500

Conversation

@euvre

@euvre euvre commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

Extends InverseDictionaryLookupPass (optimize_inverse_dictionary_lookup) to dictGet*(...) IN (constants) and NOT IN. Before, only comparisons (=, <, LIKE, ...) were rewritten.

A key missing from the dictionary makes dictGet return the attribute DEFAULT. So for all missing keys the predicate has the same, known value, and the rewrite picks the form that gets it right:

original DEFAULT in the list rewrite
dictGet(d, 'a', k) IN L no k IN (SELECT key FROM dictionary(d) WHERE a IN L)
dictGet(d, 'a', k) IN L yes k NOT IN (SELECT key FROM dictionary(d) WHERE a NOT IN L)
dictGet(d, 'a', k) NOT IN L yes k IN (SELECT key FROM dictionary(d) WHERE a NOT IN L)
dictGet(d, 'a', k) NOT IN L no k NOT IN (SELECT key FROM dictionary(d) WHERE a IN L)

To decide whether DEFAULT is in the list, the pass uses getSetElementsForConstantValue, the same conversion the planner uses to build the set. The rewrite goes through the same checks as the comparison rewrite: in-memory layouts only; attribute type must match the dictGet* type; no Nullable attribute, Nullable complex-key component or dictGetOrNull; set_overflow_mode = 'break', rewrite_in_to_join, Cascades and a missing CREATE TEMPORARY TABLE grant all skip it. A NULL in the list or a Nullable result also skips it.

In the performance test the IN/NOT IN queries got 20-38% faster (see the comment with measurements).

Closes: #99500

Changelog category (leave one):

  • Performance Improvement

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

optimize_inverse_dictionary_lookup now also rewrites dictGet(...) IN (...) and dictGet(...) NOT IN (...) with constant lists into a lookup of the matching dictionary keys, e.g. WHERE dictGetString('dict', 'status', id) IN ('active', 'pending') into WHERE id IN (SELECT id FROM dictionary('dict') WHERE status IN ('active', 'pending')). This lets the primary key be used for filtering.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1032-master (included in 26.11 and later)

@CLAassistant

CLAassistant commented Mar 19, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@nihalzp nihalzp self-assigned this Mar 19, 2026
@nihalzp nihalzp added the can be tested Allows running workflows for external contributors label Mar 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1489f1d]

Summary: ✅


AI Review

Summary

Extends InverseDictionaryLookupPass to optimize constant IN and NOT IN predicates over dictGet*, preserving missing-key defaults. No unresolved actionable findings remain at commit 1489f1d5876c95e304555b903b10de04d205d4a1. The focused CI results include all four new regression tests, and the PR discussion provides before/after performance measurements.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 19, 2026
@nihalzp

nihalzp commented Mar 19, 2026

Copy link
Copy Markdown
Member

Thanks for working on this! Let's also write a performance test to ensure the rewrite has performance improvements.

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Mar 24, 2026
@euvre
euvre marked this pull request as draft March 24, 2026 12:36
@nihalzp nihalzp added manual approve Manual approve required to run CI and removed manual approve Manual approve required to run CI labels Mar 24, 2026
@nihalzp

nihalzp commented Mar 24, 2026

Copy link
Copy Markdown
Member

There are some submodules changed which are not needed for the PR. Let's revert them.

@euvre
euvre marked this pull request as ready for review March 27, 2026 13:32
@euvre
euvre marked this pull request as draft March 27, 2026 13:47
@nihalzp nihalzp removed the manual approve Manual approve required to run CI label Apr 2, 2026
@euvre

euvre commented Apr 23, 2026

Copy link
Copy Markdown
Contributor Author

The performance comparison between this branch and master (0fe7ab9) on inverse_dictionary_lookup.xml is as follows:

# Query Baseline Median (s) Optimized Median (s) Change p-value
0 dictGetString(...) = '4' 0.003520 0.003371 -4.23% 0.037
1 dictGetString(...) != '4' 0.007278 0.006983 -4.05% 0.998
2 dictGetUInt64(...) > 5 0.005293 0.005319 +0.50% 0.808
3 dictGetUInt64(...) <= 5 0.006518 0.006282 -3.62% 0.135
4 dictGetString(...) < '5' 0.005753 0.005226 -9.15% 0.023
5 dictGetString(...) >= '5' 0.005633 0.005722 +1.58% 0.349
6 dictGetString(...) > '5' 0.005504 0.005265 -4.34% 0.271
7 dictGetString(...) <= '5' 0.005634 0.005614 -0.36% 0.274
8 dictGetUInt64(...) < 4 0.004916 0.004881 -0.71% 0.671
9 dictGetUInt64(...) >= 4 0.006376 0.006316 -0.94% 0.747
10 dictGetString(...) LIKE '5%' 0.003440 0.003515 +2.17% 0.666
11 dictGetString(...) NOT LIKE '5%' 0.007295 0.007023 -3.74% 0.977
12 dictGetString(...) IN ('0','1','2','3','4') 0.009265 0.005856 -36.80% 7.4e-29
13 dictGetString(...) NOT IN ('0','1','2','3','4') 0.008672 0.005437 -37.31% 1.3e-36
14 dictGetString(...) IN ('1','2','3','4','5') 0.009147 0.005606 -38.71% 7.5e-31
15 dictGetString(...) NOT IN ('1','2','3','4','5') 0.008649 0.005453 -36.95% 2.0e-24
16 dictGetUInt64(...) IN (0,1,2,3,4) 0.007391 0.005797 -21.57% 7.3e-10
17 dictGetUInt64(...) NOT IN (0,1,2,3,4) 0.007257 0.005814 -19.88% 4.0e-10
18 dictGetUInt64(...) IN (1,2,3,4,5) 0.007331 0.005771 -21.28% 1.4e-11
19 dictGetUInt64(...) NOT IN (1,2,3,4,5) 0.008142 0.006017 -26.10% 9.4e-15
20 dictGetString(...) IN (...) AND dictGetUInt64(...) < 4 0.007638 0.006290 -17.64% 2.2e-05
21 dictGetString(...) NOT IN (...) OR dictGetString(...) >= '4' 0.010401 0.007323 -29.59% 2.5e-24

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

This PR changes only the analyzer's inverse dictionary lookup pass. It adds a rewrite for dictGet(...) [NOT] IN (constants) and moves existing logic into helper functions. Neither benchmark calls dictGet, so no ClickBench or TPC-H query runs the new rewrite. The only extra cost is a cheap check on in/notIn nodes while the query is analyzed. The two flagged ClickBench rows are both inconclusive and do not come from this diff: Q18 (+17.1%) falls within master's recent range for that query and is noisy on master, and Q28 (+8.2%) got mixed results from the two tests on a very noisy baseline. Their higher CPU time looks like run-to-run variance, not a PR effect.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 844 988 +17.1% <0.0001 This query has no dictGet calls, so the changed inverse-dictionary-lookup rewrite never fires here. The +17.1% median sits inside master's recent range, and this query is noisy on master.
⚠️ 28 not_sure 1001 1083 +8.2% <0.0001 The two tests disagree on this +8.2% shift, and the baseline measurements were very noisy. The query uses no dictGet, so the changed analyzer rewrite does not touch it.

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.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 20fcb732-6e74-447d-a70e-1285334cae7a
  • MIRAI run: 579d0ac3-fdc6-4558-bcee-952054f6c59a
  • PR check IDs:
    • clickbench_1156237_1791850988
    • clickbench_1156337_1791851016
    • clickbench_1156445_1791851046
    • tpch_adapted_1_official_1156557_1791851075
    • tpch_adapted_1_official_1156670_1791851090
    • tpch_adapted_1_official_1156807_1791851109

alexey-milovidov and others added 3 commits October 5, 2026 13:24
Resolve the conflict in `InverseDictionaryLookupPass.cpp`: master added the
`keyTypeBreaksInverseLookupEquivalence` guards (probe type and declared key
types) to the code that this PR moved into `tryGetDictionaryLookup`. Apply
both guards inside `tryGetDictionaryLookup`, so they cover the new `IN` /
`notIn` rewrite as well.
`groupArray` over a subquery with `ORDER BY` does not guarantee the order
of elements, and CI produced e.g. `[1,3,4,6,7,8,9,0]` instead of
`[0,1,3,4,6,7,8,9]`. Sort the arrays explicitly instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `transform_null_in = 1`, user-written `IN` / `NOT IN` are resolved as
`nullIn` / `notNullIn` before query tree passes run, so the new `IN`
rewrite never fired in that mode. `rewriteIn` already requires a
non-`Nullable` left-hand side and a constant set without `NULL`, where both
spellings agree, and the nodes it creates already go through
`getInFunctionNameForPassCreatedNode`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflict in `InverseDictionaryLookupPass.cpp`: master added
key-shape and key-conversion checks (`keyExpressionMatchesDictionaryStructure`,
`canCompareKeysWithoutCasts`, `convertSimpleKeyProbe`,
`unwrapSingleColumnTupleKey`) inline in the comparison path, while this PR
moved that part of the code into `tryGetDictionaryLookup`. The new checks are
moved into `tryGetDictionaryLookup`, which now takes `DictGetFunctionInfo` by
reference and updates its `key_expr_node`, so both the comparison and the
`IN` rewrites use the converted probe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1489f1d58 with master a018bd2bb (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dcccc2b59; 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 (+47.79 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Passes/InverseDictionaryLookupPass.cpp.o 298.73 KiB 346.51 KiB +47.79 KiB (+16.00%)

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

Compile time of recompiled translation units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100001&sha=e69ba3fc1c6&name_0=PR&name_1=Integration%20tests%20(arm_binary%2C%201%2F4) (test_storage_iceberg_concurrent/test_concurrent_reads.py::test_concurrent_reads: The metadata file for Iceberg table ... doesn't exist right after the table is written, unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

This is fixed by #125448 (mine), merged 2026-10-13 01:47 UTC. The failed job is a re-run (attempt 2, started 02:11 UTC), and a re-run keeps the workflow's original merge ref: it tested e69ba3f merged into master af433c1 (2026-10-12 21:12 UTC), which is 37 commits behind the fix.

It is the #125448 mechanism: test_storage_delta/test_writes_interop.py ran first on xdist worker gw0 (02:35-02:38 UTC), then test_concurrent_reads on gw0 reused that Spark JVM with a stale cached s3a:// filesystem bound to the other module's MinIO, so Spark wrote the table elsewhere and CREATE TABLE found no metadata file. The retry in a fresh pytest session passed.

It has not failed on any tree that contains the fix: 0 failures on master or in any PR since 2026-10-15 (1532 passing master runs since 2026-10-14), and every earlier failure tested a master behind it. The current head bdf7ba0 contains the fix, so nothing more is needed here.

alexey-milovidov and others added 2 commits October 28, 2026 21:26
…okupPass`

`IColumn::compareAt` considers `-0.0` and `+0.0` equal, but `IN` sets compare
floating-point keys by their binary representation. So a `+0.0` attribute
`DEFAULT` was classified as present in a list containing only `-0.0`, and the
`IN` / `NOT IN` rewrite picked the wrong form for keys missing from the
dictionary. Build a `Set` from the converted elements and probe it with the
`DEFAULT`, like `IN` itself does.

Address review: ClickHouse#100001

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai. Confirmed: the branch contains #125448. I merged the latest master again in 1c58068. The only red check on the previous head was 02317_distinct_in_order_optimization (ParallelReplicas, s3 storage). It is labeled flaky, did not reproduce on rerun with the same randomized settings, and does not touch dictionaries. I also pushed a fix for the signed-zero DEFAULT membership finding: 7832b25.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only red check on f0e653c was 03134_positional_arguments (Stateless tests (arm_binary, parallel)): clickhouse-local failed with Cannot lock file /home/.local/share/clickhouse-local/status. That has nothing to do with this PR. It is fixed on master by #128197, so I merged the latest master in 1489f1d. The PR diff is unchanged, and InverseDictionaryLookupPass.cpp builds on the merged tree.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Acceptable.

@alexey-milovidov alexey-milovidov self-assigned this Nov 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 1, 2026
Merged via the queue into ClickHouse:master with commit a3681e7 Nov 1, 2026
179 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 Nov 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

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

Close anything that's wrong or already addressed.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 2, 2026
…ryLookupPass again

Since `in` / `notIn` over a `dictGet` became rewritable (ClickHouse#100001), the
`key IN (keys)` node that the pass creates for a comparison matching several
dictionary keys is itself a rewrite candidate when the key is a `dictGet`.
A shared alias node (`GROUP BY r ORDER BY r` with the identifier resolve cache)
is visited once per reference, so the second visit inverted one more level of a
nested `dictGet` chain and the `GROUP BY` key and the projection differed
again (NOT_FOUND_COLUMN_IN_BLOCK). Register that node as final, as already done
for the single-key `equals`.

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-performance Pull request with some performance improvements 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.

optimize_inverse_dictionary_lookup does not work for conditions IN

8 participants