Skip to content

Use many key columns per condition for pruning - #96225

Merged
nihalzp merged 173 commits into
ClickHouse:masterfrom
nihalzp:support-one-condition-multiple-keys
Oct 15, 2026
Merged

nihalzp merged 173 commits into
ClickHouse:masterfrom
nihalzp:support-one-condition-multiple-keys

Conversation

@nihalzp

@nihalzp nihalzp commented Feb 6, 2026 •

Copy link
Copy Markdown
Member

If we have,

CREATE TABLE test ( dt DateTime )
ENGINE = MergeTree
ORDER BY (toYYYYMM(dt), toDate(dt), toStartOfHour(dt), dt)
SETTINGS index_granularity = 1;

INSERT INTO test SELECT toDateTime('2026-01-01 00:00:00') + number * 3600 FROM numbers(24 * 40);

Then, for query such as:

EXPLAIN indexes = 1
SELECT count() FROM test WHERE dt = toDateTime('2026-01-10 00:00:00');

Currently, we use only one primary key column:

Keys:
    dt
  Condition: (dt in [1768003200, 1768003200])
  Parts: 1/1
  Granules: 960/960

PR will use all the keys applicable:

Keys:
    toYYYYMM(dt)
    toDate(dt)
    toStartOfHour(dt)
    dt
  Condition: and((toStartOfHour(dt) in [1768003200, 1768003200]), and((toDate(dt) in [20463, 20463]), and((toYYYYMM(dt) in [202601, 202601]), (dt in [1768003200, 1768003200]))))
  Parts: 1/1
  Granules: 2/960
image

The behavior is controlled by the new setting analyze_index_with_multiple_key_columns_per_condition (enabled by default). When it is disabled, each condition constrains at most one key column, matching the scope of the analysis before this change.

Closes: #33056
Closes: #99960

Changelog category (leave one):

  • Performance Improvement

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

Allow a single condition to constrain multiple key columns during index analysis. For example, if the primary key is (toYYYYMMDD(dt), toDate(dt), dt) and the query has WHERE dt >= toDateTime('2026-01-10 00:00:00'), all three key columns are now used for pruning, instead of only one of them as before. This behavior is controlled by the setting analyze_index_with_multiple_key_columns_per_condition (enabled by default).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Feb 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [975594c]

Summary: ✅


AI Review

Summary

This PR lets one predicate constrain multiple key expressions, controlled by analyze_index_with_multiple_key_columns_per_condition, enabled by default. ❌ Block: five incorrect-result cases still reproduce with the current PR binary, and redundant constraints cause a measurable slowdown. All six findings already have review threads; no duplicate inline comments were posted. The author has deferred these issues as existing bugs or an accepted tradeoff; the findings below explain why the expanded default behavior remains problematic.

Findings

❌ Blockers

  1. Wrapped membership must preserve the probe-to-set conversion. KeyCondition.cpp:3986: IN converts the probe into the set's type, but the extra atom transforms one set member back into the probe's domain. For DateTime64(6) values ending in .123456 and a DateTime64(3) set member ending in .123, the predicate matches while the added toString atom expects .123000. Current-head counts are 0 enabled / 8 disabled. Reject transformations that do not preserve the full match set, or represent its preimage; relaxing the atom cannot repair false exclusions.

    [dismissed by author -- https://github.com/Use many key columns per condition for pruning #96225#discussion_r4271877379] The newly added atom makes a previously safe query return the wrong result when the default setting is enabled.

  2. Tuple normalization must preserve padded string equality. KeyCondition.cpp:3154: the padding guard recognizes only a top-level FixedString. For a Tuple(String, UInt8) compared with (toFixedString('abc', 8), toUInt8(1)), both 'abc' and 'abc\0' match, but the transformed hash represents only one spelling. Current-head counts are 257 enabled / 512 disabled. Inspect constant and input types recursively and reject transformations that lose padded comparison semantics.

    [dismissed by author -- https://github.com/Use many key columns per condition for pruning #96225#discussion_r4271877392] The extra hash constraint still discards matching rows; the top-level guard does not cover the tuple carrier.

  3. Scalar tuple equality must remain positional. KeyCondition.cpp:3166: named-tuple casts map fields by name, while equality compares positions. Comparing a stored Tuple(b UInt8, a UInt8) value (1, 2) with a constant Tuple(a UInt8, b UInt8) transforms the constant into (2, 1), so the added cityHash64 constraint excludes every matching row. Current-head counts are 0 enabled / 8 disabled. Normalize positionally or reject differing explicit layouts recursively.

    [dismissed by author -- https://github.com/Use many key columns per condition for pruning #96225#discussion_r4271877412] A successful round trip does not establish comparison equivalence, and the default extra atom changes the result.

  4. Tuple date-time text must use comparison-time timezone semantics. KeyCondition.cpp:3158: tryNormalizeTextConstantForZonelessDateTimeInput skips tuple constants. A table created under UTC with Tuple(DateTime, UInt8) therefore hashes tuple text using its captured timezone, although equality parses that text using the current session_timezone. With America/New_York at query time, current-head counts are 0 enabled / 8 disabled. Normalize tuple elements recursively using the comparison's timezone, or decline the candidate.

    [dismissed by author -- https://github.com/Use many key columns per condition for pruning #96225#discussion_r4275114686] The additional hash constraint excludes the instant that the row-level comparison matches.

  5. Inferred bounds require monotonicity over stored values. KeyCondition.cpp:5749: with date_time_overflow_behavior = 'ignore', toDate(Date32) wraps pre-epoch dates. For PARTITION BY (toDate(d), d) and d <= '1970-01-01', the new toDate(d) <= 0 atom excludes the matching 1969-12-31 partition, whose converted day is 65535. Current-head counts are 1 enabled / 2 disabled / 2 full scan. Correct the monotonicity metadata or reject this inference across the overflow boundary.

    [dismissed by author -- https://github.com/Use many key columns per condition for pruning #96225#discussion_r4264006423] The PR exposes the existing conversion defect through an additional partition constraint where the direct constraint was safe.

⚠️ Majors

  1. Additional constraints need bounded cost when they provide no additional pruning. KeyCondition.cpp:7718: the original long-key workload evaluates 21 constraints for key = '1' without reducing the selected ranges. On the current-head binary, a local one-million-row workload with 20 derived key expressions took median 308 ms enabled / 211 ms disabled across three warm runs, about 46% slower, with identical results. This compares the setting on/off, not separate master/PR binaries. long_primary_key.xml:48 now derives filler expressions from unfiltered pad, removing this workload from that benchmark. Preserve performance coverage for the original shape and avoid redundant evaluation, or keep the optimization opt-in until its cost is bounded.

    [dismissed by author -- https://github.com/Use many key columns per condition for pruning #96225#discussion_r4264111985] The accepted tradeoff remains a measured regression under the new default, and the modified benchmark no longer detects it.

Tests
  • ⚠️ Add focused stateless regressions for the five incorrect-result cases, comparing enabled analysis with disabled analysis and a full scan. Each reproduced with the CI Fast-test binary for PR head 975594c68cdee8fcd9c2ba82042cef921a29ef7c; the relevant source files match the reviewed checkout.
  • ⚠️ Keep the original long-key shape in performance coverage alongside the revised benchmark.
Final Verdict

Status: ❌ Block. Prevent the five unsafe inferences before enabling this behavior by default, cover their reproductions, and retain performance coverage for redundant derived-key constraints. No existing thread was replied to, resolved, or reopened.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Feb 6, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

The test_database_iceberg_nessie_catalog and test_database_iceberg_lakekeeper_catalog failures in this PR's CI are false positives caused by a bug in PR #100583 (merged to master on 2026-04-09 at 11:19 UTC). That PR broke the metadata file path resolution in getMetadataLocation for Iceberg catalog tests — it produced a doubled S3 key like table_path/warehouse-rest/table_path/metadata/... instead of table_path/metadata/..., causing MinIO to return 403.

The bug was reverted by PR #102247 (merged at ~14:48 UTC). All nessie/lakekeeper test failures between these two merges are unrelated to this PR.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@pmusa

pmusa commented Jun 1, 2026

Copy link
Copy Markdown
Member

Hi team, this would be a great feature to have. Not sure if it is a heavy lifting, but adding my +1.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 32 queries analysed

No query in either benchmark has a verdict that should block this PR. Only clickbench Q33 (-14.3%) and Q34 (-13.7%) were flagged, and both stay not_sure because master's own timings for them jumped during the comparison window. Both are full-scan GROUP BY queries with no WHERE filter, so they never run the code this PR changes: primary-key analysis that lets one condition narrow several key columns. Their lower CPU time (about 16.2 s to 14.4 s) follows master's shift rather than anything in the diff, and tpch_adapted_1_official shows no changes.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1143 979 -14.3% <0.0001 aggregation: This query is a full-scan GROUP BY with no WHERE filter, so the primary-key analysis code changed by this PR is not on its path. The -14.3% comes from master's own step change.
⚠️ 34 not_sure 1141 984 -13.7% <0.0001 aggregation: Like Q33, this is a full-scan GROUP BY that never uses primary-key analysis. Master's baseline shifted during the comparison window, which explains the -13.7%.

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: 32022348-5be3-4e80-8eae-2550c0f921e6
  • MIRAI run: de1a25c1-7ea8-4e3f-8f1b-2f1d188e7831
  • PR check IDs:
    • clickbench_393085_1791477048
    • clickbench_393091_1791477048
    • clickbench_393097_1791477048
    • tpch_adapted_1_official_393122_1791477048
    • tpch_adapted_1_official_393129_1791477048
    • tpch_adapted_1_official_393568_1791477060

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm going through the remaining review findings to confirm which ones reproduce on master with a single key column query; I'll follow up here with the classification and a PR that fixes them.

@groeneai

Copy link
Copy Markdown
Collaborator

I checked the threads that are not marked fixed here against master (d245b78), each with a single key column.

Finding On master Fix
NOT IN over toFixedString does not reproduce -
toDate wrap reproduces, also on 26.3 and 26.8 none open, I'm preparing one
atoms evaluated before dedup PR-only (performance) -
DateTime64 scale in IN (SELECT ...) reproduces, even with ORDER BY x #112966 (mine, open) declines a set whose element type is not the key type
FixedString in a tuple constant reproduces #123868 (open)
named tuple cast reproduces #123868 (open)
date-time text in a tuple constant reproduces, also on 26.3 and 26.8 none open, I'm preparing one

The toDate one is the limitation left open in #117394 (thread): the wrapped key values are stored, so pushing a range constant through toDate over DateTime64/Date32 is unsound. I'll open one PR for the two without a fix and link it here.

Single-key repros (comment: master result, full scan result)
SET use_query_condition_cache = 0;

-- toDate wrap
CREATE TABLE t_date (ts DateTime64(3, 'UTC')) ENGINE = MergeTree ORDER BY toDate(ts) SETTINGS index_granularity = 1;
INSERT INTO t_date VALUES ('1969-12-31 12:00:00'), ('1970-01-01 12:00:00');
SELECT count() FROM t_date WHERE ts <= '1970-01-02 00:00:00'; -- 1, 2

-- DateTime64 scale
CREATE TABLE t_scale (x DateTime64(6, 'UTC')) ENGINE = MergeTree ORDER BY x SETTINGS index_granularity = 1;
INSERT INTO t_scale SELECT toDateTime64('2026-01-01 00:00:00.123456', 6, 'UTC') FROM numbers(8);
SELECT count() FROM t_scale WHERE x IN (SELECT toDateTime64('2026-01-01 00:00:00.123', 3, 'UTC')); -- 0, 8

-- FixedString in a tuple
CREATE TABLE t_pad (t Tuple(String, UInt8)) ENGINE = MergeTree ORDER BY cityHash64(t) SETTINGS index_granularity = 1;
INSERT INTO t_pad SELECT (if(number % 2, 'abc', 'abc\0'), 1) FROM numbers(512);
SELECT count() FROM t_pad WHERE t = (toFixedString('abc', 8), toUInt8(1)); -- 257, 512

-- named tuple
CREATE TABLE t_named (t Tuple(b UInt8, a UInt8)) ENGINE = MergeTree ORDER BY cityHash64(t) SETTINGS index_granularity = 1;
INSERT INTO t_named SELECT (1, 2) FROM numbers(8);
SELECT count() FROM t_named WHERE t = CAST((1, 2), 'Tuple(a UInt8, b UInt8)'); -- 0, 8

-- date-time text in a tuple
SET session_timezone = 'UTC';
CREATE TABLE t_zone (t Tuple(DateTime, UInt8)) ENGINE = MergeTree ORDER BY cityHash64(t) SETTINGS index_granularity = 1;
INSERT INTO t_zone SELECT (toDateTime('2026-01-01 12:00:00', 'America/New_York'), 1) FROM numbers(8);
SET session_timezone = 'America/New_York';
SELECT count() FROM t_zone WHERE t = ('2026-01-01 12:00:00', toUInt8(1)); -- 0, 8

@nihalzp

nihalzp commented Oct 15, 2026

Copy link
Copy Markdown
Member Author

NOT IN over toFixedString is fixed in master and also does not reproduce in this PR.

@nihalzp

nihalzp commented Oct 15, 2026 •

Copy link
Copy Markdown
Member Author

@yariks5s Thanks for the thorough review. I think it's safe to keep it enabled by default because existing master bugs are either very rare edge case or known limitation.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix for the toDate wrap and the date-time text in tuple constants: #125960. It needs the can be tested label to start CI.

Merged via the queue into ClickHouse:master with commit 4ade3cb Oct 15, 2026
178 checks passed
@nihalzp
nihalzp deleted the support-one-condition-multiple-keys branch October 15, 2026 07:42
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 15, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
…rapping-todate-tuple-text-timezone

Resolve the conflict with ClickHouse#96225 in `KeyCondition.cpp`: the zone-less date-time text
normalization now takes the constant as a `ColumnWithTypeAndName`. The tuple recursion
moves into a `Field`-level helper, and the column is rebuilt only when a text element
was converted, so other constants keep their original columns as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
…ments

The comparison pairs tuple elements by position, while the cast of a constant
to the key's tuple type pairs two named tuples by name. Converting the text
elements of such a constant by position made that cast succeed on swapped
values: with `t Tuple(d DateTime, n UInt8)` and
`t = CAST(('2026-01-01 12:00:00', 1), 'Tuple(n String, d UInt8)')` the index
skipped all 8 matching rows, and a nested `Nullable(Tuple)` element made the
cast throw `TYPE_MISMATCH`, where master declines the transform because the
text does not parse as `UInt8`. A tuple level whose text was converted and whose
names differ from the key's is now declined, so the constant pairs with the key
as on master; named constants with the key's own names are still normalized.
05402 covers a same-order, a reordered and a nested reordered named constant.

A named constant without text whose names reorder the key's elements is left
as it is: its name-mapped cast is the separate finding of ClickHouse#96225 that ClickHouse#123868
addresses.

Found by the second-model review of the merge with master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
…ues apart

`keyToSetConversionMayCollapse` is now fail-closed: the index uses a set
only for conversions of the key into the set's type that are known to keep
distinct key values apart (the same type, integers and floats, widenings,
element-wise composites); every other pair declines.

This also covers a number key against an `Enum` set: the lookup cast has no
context, so it uses `static_cast`, and an `Int64` key holding 257 matches an
`Enum8` element of value 1.

The 05331 and 03991 expectations are taken from Nihal Z. Miaji's
2818b87 and 0efe8bc on ClickHouse#96225.

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

Copy link
Copy Markdown
Collaborator

@nihalzp The DateTime64 scale in IN (SELECT ...) row of my table above is fixed by #112890, not #112966. Its index check is fail-closed, like the Set::lookupCastMayMergeValues reverted in 2bd8a0e (with your 2026-10-14 follow-ups and the same 05331/03991 expectations), and it keeps pruning for widenings such as a DateTime key against a DateTime64 subquery. One case it covers is new on master: a Nullable(DateTime64(3)) key against a DateTime subquery in a tuple IN or under transform_null_in = 1 is right on 26.8.21.12 and on 2cb89c8, and wrong on 1d85cfe (I did not bisect it).

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 17, 2026
04330 and 05245 (added by ClickHouse#96225) create tables with an alias in
ORDER BY, which this PR now rejects at CREATE ("Alias 'd' / 'bucket'
is not allowed in ORDER BY"); this kicked the PR out of the merge queue.

05245: drop `AS bucket`. The alias is not referenced anywhere, and the
reference is unchanged on master and on this branch.

04330: delete the `test_det_alias` case. Its subject is an ALIAS node in
the key expression, which a new table can no longer have; without the
alias it is the `ORDER BY (toDate(ts), ts)` shape already covered by
other multi-atom tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... pr-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.

Automatically Optimize Queries on Time-Partitioned Tables Performance with functions in primary index

9 participants