Skip to content

Normalize a constant through the key column type before the key DAG - #118688

Merged
alexey-milovidov merged 6 commits into
masterfrom
key-condition-datetime64-scale-117813
Sep 19, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
key-condition-datetime64-scale-117813

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Closes: #117813

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 rows silently dropped by index analysis when a DateTime64 column is compared with a constant of another scale and the sorting or partition key contains a CAST of that column, such as ORDER BY d::String.

Description

CREATE TABLE t (d DateTime64(3, 'UTC')) ENGINE = MergeTree ORDER BY d::String;
INSERT INTO t VALUES (toDateTime64(1675252800, 3, 'UTC'));

SELECT count() FROM t WHERE d = toDateTime64(1675252800, 6, 'UTC'); -- 0, expected 1

EXPLAIN indexes = 1 shows Condition: (CAST(d, 'String') in ['2023-02-01 12:00:00.000000', ...]) - six fractional digits, while every key value in the part has the three of the column's scale, so the range check concludes the value is outside the part and prunes it. Under PARTITION BY d::String every partition's minimum equals its maximum, so every mismatched-scale lookup loses its row.

applyDeterministicDagToColumn preferred a fast path that applies the key DAG's CAST straight to the constant's own type, skipping the normalizing round trip through the key column's type. That fast path exists for round trips that cannot be done safely (String -> Dynamic -> String), where the normalizing cast refuses the target and returns false - so the normalizing cast is tried first now and the direct cast stays as the fallback only for a Dynamic key, the one type that keeps the constant in its own type so both renderings agree. For any other key type the normalizing cast cannot handle - containers such as Array(DateTime64(3)) under ORDER BY arr::String - the atom is declined and the reader reads more rather than pruning by a value in the wrong scale; test 05227_key_condition_datetime64_scale_array_cast_key covers Array and Tuple keys.

A constant that the key column's type cannot represent exactly (toDateTime64('...12:00:00.000001', 6) against a DateTime64(3) column) still declines: no value of the column can equal it, which is also what the row comparison computes.


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

Version info

  • Merged into: 26.10.1.126 (included in 26.10 and later)

```sql
CREATE TABLE t (d DateTime64(3, 'UTC')) ENGINE = MergeTree ORDER BY d::String;
INSERT INTO t VALUES (toDateTime64(1675252800, 3, 'UTC'));

SELECT count() FROM t WHERE d = toDateTime64(1675252800, 6, 'UTC'); -- 0, expected 1
```

`EXPLAIN indexes = 1` shows the condition over
`['2023-02-01 12:00:00.000000', ...]` - six fractional digits, while every key
value in the part has the three of the column's scale - so the range check
concludes the value lies outside the part and prunes it. Under
`PARTITION BY d::String` every partition's minimum equals its maximum, so every
lookup with a mismatched scale loses its row.

`applyDeterministicDagToColumn` preferred a fast path that applies the `CAST` of
the key DAG straight to the constant's own type, skipping the normalizing round
trip through the key column's type. That fast path is for round trips that
cannot be done safely - `String` -> `Dynamic` -> `String`, where the normalizing
cast refuses the target and returns false - so the normalizing cast is tried
first now, and the direct cast remains the fallback for exactly those cases.

A constant the key column's type cannot represent exactly (a
`DateTime64(6)` value with a microsecond part against a `DateTime64(3)` column)
still declines: no value of the column can equal it, which is what the row
comparison computes as well.

Closes: #117813

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6a44b78]

Summary: ✅


AI Review

Summary

This PR fixes the DateTime64 mismatched-scale key-pruning bug by normalizing constants through the key column type before applying the deterministic key CAST, and it adds stateless coverage for scalar and container keys. The earlier container/set issues now look resolved in the current code, but the new scalar regression test still does not prove that pruning remains active rather than silently falling back to a full scan.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/05149_key_condition_datetime64_scale_cast_key.sql:1] The new test only checks final row counts. If convertColumnForDeterministicDag started declining the mismatched-scale scalar case, the query would still return the same results by scanning the whole table, so this would no longer guard the behavior the PR is promising: normalized key/partition pruning instead of over-read. Suggested fix: add at least one SETTINGS force_primary_key = 1 assertion for the ORDER BY d::String path and an EXPLAIN indexes = 1 assertion for the PARTITION BY d::String path, similar to 04846_tounixtimestamp_datetime64_key_pruning.sql.
Final Verdict
  • ⚠️ Needs a test update before merge: the scalar regression coverage should prove the normalized key condition is still used, not only that a full scan returns the right rows.

LLVM Coverage Report

Measured on commit 6a44b78.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 8/8 (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 Sep 8, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6a44b78e6 with master e6019455e (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

24 object files changed (+79.76 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/QueryPipeline/RemoteQueryExecutor.cpp.o 525.84 KiB 579.27 KiB +53.44 KiB (+10.16%)

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

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

Job report

The same helper transforms whole set columns, so falling back to the direct
`CAST` whenever the normalizing cast fails let one unrepresentable element of a
set drag the representable ones into the constant's own value space: a mixed
`IN (toDateTime64(..., 6), toDateTime64('...000001', 6))` against a
`DateTime64(3)` key with `ORDER BY d::String` rendered six fractional digits for
both and could prune the row that matches.

The fallback now applies only when the target cannot be probed by
`castColumnAccurateOrNull` at all - the `String` -> `Dynamic` -> `String` case it
exists for. When the target can be probed and the cast still failed, the value
is simply not representable in the key column's type, so the atom is declined
and the caller reads more instead of pruning by a value the key space does not
hold.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed: the direct-CAST fallback now applies only when the target cannot be probed by castColumnAccurateOrNull at all - the String -> Dynamic -> String case it exists for. When the target can be probed and the cast still failed, the value is not representable in the key column's type, so the atom is declined rather than rendered from its own type; that is what the set path needs, since one unrepresentable element would otherwise drag the representable ones along.

05149 now covers the mixed set through IN, NOT IN and has (1, 0, 1), and 03762_has_in_function_key_condition_deterministic_function_chain_explain still passes, so the Dynamic-key pruning it pins is unchanged.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 3 commits September 9, 2026 17:23
…` to `Dynamic` keys

The fallback used to fire for every key type that `castColumnAccurateOrNull`
cannot probe, which includes containers: for `ORDER BY arr::String` over
`Array(DateTime64(3))`, the constant `[toDateTime64(..., 6)]` was rendered
from its own scale and the part holding the row was pruned. Only a `Dynamic`
key keeps the value in the constant's own type, so only there the direct
`CAST` equals the normalized round trip; every other key type declines and
the caller reads more instead.

Adds test `05227_key_condition_datetime64_scale_array_cast_key` covering
`Array` and `Tuple` keys with mismatched-scale constants.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@@ -0,0 +1,63 @@
-- A `DateTime64` constant of a scale other than the column's must not change which parts and

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

These assertions are weaker than the contract in the header comment and PR description. If convertColumnForDeterministicDag regressed to return false for the mismatched-scale scalar case, every count() here would still pass by full-scanning the table, so we would stop testing that the normalized key condition is actually built.

Can we add at least one pruning assertion for the scalar path, e.g. SETTINGS force_primary_key = 1 on the ORDER BY d::String block and an EXPLAIN indexes = 1 check for the PARTITION BY d::String block, along the lines of 04846_tounixtimestamp_datetime64_key_pruning.sql?

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 18, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 18, 2026
Merged via the queue into master with commit f6cd2e6 Sep 19, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the key-condition-datetime64-scale-117813 branch September 19, 2026 00:22
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
@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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

2 participants