Skip to content

Use indexes when an Interval column is compared with an Interval constant of a coarser unit - #126263

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:interval-constant-unit-conversion-for-index-analysis
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:interval-constant-unit-conversion-for-index-analysis

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #126218

Changelog category (leave one):

  • Performance Improvement

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

The primary key and minmax skip indexes are now used when a column of an Interval type is compared with an Interval constant of a coarser unit, e.g. time >= INTERVAL 510 MINUTE for an IntervalNanosecond column. IN with such constants is now accepted instead of failing with TYPE_MISMATCH. Closes #126218.

Description

On master, WHERE time BETWEEN INTERVAL 510 MINUTE AND INTERVAL 515 MINUTE over an IntervalNanosecond sorting key reads every granule (Condition: true), and time IN (INTERVAL 510 MINUTE, INTERVAL 1 HOUR) fails with TYPE_MISMATCH. The comparison results themselves are correct.

Root cause: index analysis converts the constant to the comparison's common type, the finer unit, with convertFieldToType, which had no conversion between two different Interval units. The exception was swallowed, so no condition was built; building an IN set hit the same exception.

Change: convertFieldToType converts an Interval value of a coarser unit to a finer unit of the same family (Nanosecond to Week, or Month/Quarter/Year) when the product fits in Int64. That is the value the comparison's own cast produces, so the bound is exact. A finer constant, one that overflows the column's unit, and units of different families are still not converted: the comparison then casts the column, wraps, or has no common type, so no bound computed from the constant alone would match it. A Nullable interval source type is now unwrapped like the temporal ones, which also makes toIntervalMinute(1) IN [NULL, toIntervalMinute(1)] work.

Validation: the new test covers IntervalNanosecond, IntervalMicrosecond, IntervalMillisecond and IntervalSecond keys and minmax indexes against SECOND to YEAR constants, for BETWEEN, <, >=, IN, NOT IN and PREWHERE, plus the cases that must stay rejected. It fails on master and passes 50/50 randomized runs. The converted bound is identical to the one built from a literal in the column's unit.

x IN (SELECT <interval>) and has() with mixed interval units are a separate, pre-existing problem and are not changed here.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 16, 2026 09:39
… unit

Index analysis converts the constant of `time >= INTERVAL 510 MINUTE` to the
comparison's common type, the finer `IntervalNanosecond` of the key, with
`convertFieldToType`. It had no conversion between two different interval
units, so the conversion threw, `KeyCondition` built no atom and every granule
was read. Building an `IN` set hit the same exception and failed the query with
`TYPE_MISMATCH`.

Convert a coarser interval value to a finer unit of the same family when the
product fits in `Int64`. That is the value the comparison's own cast produces,
so the bound is exact and is used by the primary key, `PREWHERE`, `minmax`
skip indexes, partition pruning and `IN` sets. A finer constant, one that
overflows the column's unit and units of different families stay rejected:
the comparison casts the column side with a wrapping multiplication, or has no
common type, so no bound computed from the constant alone would agree with it.

Unwrap a `Nullable` / `LowCardinality` interval source type like the temporal
ones, so an Array constant with `NULL` reaches the new branch, and the same
unit takes the early return instead of failing.

Closes ClickHouse#126218

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Hint-unwrap comment: an unwrapped interval hint avoids a type mismatch, not only a raw-number reinterpretation.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings over 3 runs; 1 fix round + 1 delta recheck with 0 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ The changelog entry named partition pruning, which the test does not cover AGREE, fixed Removed from the changelog entry.
2 ⚠️ The test pinned that the constant is converted, not that the converted value is exact AGREE, fixed @ 15aab81 The test now prints the exact Condition: bound of every index case and the rows matched by every IN; a conversion factor off by 1/60 turns it red.
3 💡 The hint unwrap comment does not describe the Interval case AGREE, fixed Comment reworded before publishing.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-9:20261016-094100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test on unfixed master: every EXPLAIN indexes = 1 shows Granules: 100/100 and every coarser-unit IN fails with TYPE_MISMATCH, on every run.
b Root cause explained? Index analysis converts the constant to the finer unit with convertFieldToType, which had no Interval to Interval (different unit) conversion; the swallowed exception left no condition, and IN set building hit the same exception.
c Fix matches root cause? Yes. The missing conversion is added in convertFieldToType, producing the same value as the cast the comparison applies; KeyCondition is unchanged.
d Test intent preserved / new tests added? New stateless test: four key units and minmax indexes, constants from MINUTE to YEAR, BETWEEN, <, >=, IN, NOT IN, PREWHERE, plus refusal cases. It pins the exact converted bound (the Condition: line, identical to the one from a literal in the column's unit) and the exact rows matched by each IN.
e Both directions demonstrated? Fails on master, passes with the fix, 50/50 randomized runs. Six mutations of the change (no conversion, finer-to-coarser division, no overflow check, no family check, no Nullable hint unwrap, a conversion factor off by 1/60) each turn the test red.
f Fix is general across code paths? One conversion serves the primary key, PREWHERE, minmax indexes, partition pruning (measured Parts: 10/10 to 1/10) and IN sets.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked Nullable key and constant, Array with NULL, Tuple, negative values, Int64 overflow, calendar units, cross-family units.
h Backward compatible? (maintainer-approved exception only) Yes. Only inputs that failed with TYPE_MISMATCH before now succeed; no setting or format change.
i Invariants and contracts preserved? The converted value equals the comparison's own cast for every column value. Finer, overflowing and cross-family constants stay rejected, so no bound can disagree with =.

Session id: cron:clickhouse-impl-slot-7:20261016-092600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @Algunenano, could you review this? convertFieldToType gains an exact, overflow-checked coarser-to-finer conversion between Interval units of the same family, so KeyCondition can build a bound for IntervalNanosecond keys compared with INTERVAL n MINUTE constants instead of Condition: true.

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [021fc5a]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 3/4) FAIL
Build ClickHouse FAIL cidb
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_binary) DROPPED
Build (amd_release) DROPPED
Build (arm_release) DROPPED

AI Review

Summary

Adds exact, overflow-checked conversion from coarser to finer Interval units within the same family, enabling primary-key and minmax pruning and constant IN sets. No actionable correctness or safety findings at commit 021fc5aec64ffee2744d8aac74c0bb8e0db7d083.

Missing context / blind spots
  • ⚠️ Runtime validation was not independently repeated: this checkout has no built ClickHouse binary, and the current Praktika report shows a failed tidy build and dropped stateless jobs. The author supplies before/after results and reduced granule counts; a successful stateless CI run would independently confirm them.
Final Verdict

Status: ✅ Approve. No new inline findings.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Oct 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 021fc5a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 3/4) / Build ClickHouse master build break, not from this PR (it does not touch the file): unit_tests_dbms does not compile, gtest_functions_stress.cpp:2367: error: value of type 'const ResolvedAddress' is not contextually convertible to 'bool'; the tested merge commit predates the fix #126269 (external, merged)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above #126269 (the owner of the first row)

The build failure dropped 93 dependent jobs, so no functional test has run on this head yet.

Session id: cron:our-pr-ci-monitor:20261017-033003

@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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Primary key is not used when an Interval column is compared with an Interval literal of a different unit

2 participants