Skip to content

Derive optimize_and_compare_chain ranges through a DateTime constant compared with DateTime64 - #123796

Merged
yariks5s merged 3 commits into
ClickHouse:masterfrom
groeneai:compare-chain-datetime-constant-widening
Oct 5, 2026
Merged

yariks5s merged 3 commits into
ClickHouse:masterfrom
groeneai:compare-chain-datetime-constant-widening

Conversation

@groeneai

@groeneai groeneai commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #123706
Related: #110621

Changelog category (leave one):

  • Performance Improvement

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

optimize_and_compare_chain again derives transitive conditions through a DateTime or lower-scale DateTime64 constant compared with a DateTime64 expression, as it did before 26.8. For example, t1.ts < toDateTime('2026-09-16 00:00:00') AND t1.ts >= t2.ts adds t2.ts < toDateTime('2026-09-16 00:00:00'), so the other side of a join can be pruned by its partition and primary key instead of being read in full. Closes #123706.

Description

Since #110621, optimize_and_compare_chain chains two comparisons only when both have the same order domain, and the DateTime64 domain is keyed by scale. A DateTime constant (scale 0) compared with a DateTime64(6) column has no domain, so in the query of #123706 (t1.c3 < e1 AND t1.c3 >= t2.c3 AND t1.c3 <= t2.c3 + INTERVAL 48 HOUR, e1 a DateTime) the edge is skipped and t2.c3 < e1 is no longer derived.

The comparison itself widens such a constant exactly to the column's scale. This PR does that once, before the chain is built, in the step that already retypes String constants: a DateTime or lower-scale DateTime64 constant compared with a DateTime64 expression is converted with tryConvertFieldToTypeExact. A higher-scale or overflowing constant stays out of the chain, so every derived comparison is between equal scales and cannot throw. Date constants are not included (their conversion depends on the time zone); Time64 and Decimal constants have the same scale-keyed exclusion and are left as they are.

Validation on the issue's synthetic data and settings: t2 Min-Max Parts: 29/29 -> 4/29, SelectedRows 20,998,859 -> 4,319,564, same result. With FINAL this needs defer_partition_pruning_after_final = 0 (the issue's compatibility = '25.4'); without FINAL it applies at defaults. The new test fails on master on 4 arms and passes with the fix.


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

Version info

  • Merged into: 26.10.1.1597-master (included in 26.10 and later)
  • Backported to: 26.9.18.4, 26.8.26.4

groeneai and others added 3 commits October 4, 2026 00:13
… DateTime64

Since ClickHouse#110621, `optimize_and_compare_chain` joins a comparison into a
transitive chain only when both sides share one `ComparisonOrderDomain`,
and `TimePoint` is keyed by scale (`DateTime` 0, `DateTime64(s)` s). A
`DateTime` constant compared with a `DateTime64(6)` column therefore has
no domain and the edge is skipped. In the query of ClickHouse#123706
(`t1.c3 < e1 AND t1.c3 >= t2.c3 AND t1.c3 <= t2.c3 + INTERVAL 48 HOUR`,
`e1` a `DateTime`) `t2.c3 < e1` is no longer derived and t2 is read in
full: 26.7 prunes it to 4/29 parts, 26.8 and master read 29/29.

The comparison itself widens such a constant exactly to the column's
scale. Do the same once, in the step that already retypes String
constants (`tryNormalizeConstStringEdge`, now `tryNormalizeConstEdge`):
a `DateTime` or lower-scale `DateTime64` constant compared with a
`DateTime64` expression is converted with `tryConvertFieldToTypeExact`,
which returns Null on overflow or loss. The edge then joins the
expression's own `TimePoint(s)` domain. Every derived comparison is
between equal `DateTime64` scales, so it cannot rescale or throw, and
the inferred-domain check holds. A higher-scale or overflowing constant
stays out of the chain as before. `Date` constants are not included,
their conversion to a time point depends on the time zone.

Closes ClickHouse#123706

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Within one source the derived bound is added as `indexHint`, which never
executes, and `values()` has no index, so those counts printed 1 whatever
the widened constant was. A one-row `MergeTree` table ordered by the hinted
column makes a shifted or truncated bound prune the row (count 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge the isLowerScaleTimePoint comment into one line and condense the tryNormalizeConstEdge comment to three lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 0 Gate B findings; 1 test-robustness item and 2 nits from my own review, all resolved
Finding Verdict
⚠️ The join arm's EXPLAIN indexes = 1 assertion had not been run under the stateless ParallelReplicas configuration AGREE, verified: passes there with and without random settings, parallel replicas used for every join query
💡 The result counts of the time-zone and lower-scale arms read values(), where the derived indexHint cannot change them AGREE, fixed: they read one-row indexed tables, so a shifted or truncated bound prunes the row
💡 Changelog example used an unmeasured now() shape AGREE, fixed: literal constant

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN indexes = 1 of the issue query on its synthetic data and settings: t2 Min-Max Parts: 29/29 on master, 4/29 with the fix. The new test fails on master on 4 arms on every run.
b Root cause explained? Since #110621 the DateTime64 comparison domain is keyed by scale, so DateTime64(6) < DateTime constant has no domain, the edge is skipped, the chain through t1.c3 is never walked and t2.c3 < e1 is not derived.
c Fix matches root cause? Yes. The constant is widened exactly to the expression's scale, as the comparison itself does, in the step that already retypes String constants. No setting, no guard elsewhere.
d Test intent preserved / new tests added? New test with positive arms (incl. another time zone and sub-second constants, whose counts read a one-row indexed table so a shifted or truncated bound prunes the row), negative arms (higher scale, overflow), a dedup arm, a remote() arm and a join pruning arm. Passes in the ParallelReplicas configuration too. Existing tests unchanged.
e Both directions demonstrated? Yes: master FAIL / fix OK on the test; SelectedRows 20,998,859 vs 4,319,564 on the repro, same result. Mutations: disabling the new branch, dropping the scale check, or using a throwing conversion each redden the arm that guards it.
f Fix is general across code paths? The constant retype is the single place an edge is admitted. Date constants are excluded on purpose (time-zone-dependent); Time64/Decimal keep their scale-keyed exclusion (noted in the description).
g Fix generalizes across inputs (params/datatypes/wrappers)? 21-query matrix (Nullable and LowCardinality, constant on either side, all comparison operators, pre-epoch, scales 0/1/3/6/9, near-max and overflowing constants, other time zones): results identical on master and with the fix.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; the derivation existed up to 26.7 and every added condition is implied by the original ones.
i Invariants and contracts preserved? Every chain edge is still within one order domain, so derived comparisons are between equal DateTime64 scales and the inferred-domain check holds. 321 related tests and 50 randomized runs of the new test on a debug build.

Session id: cron:clickhouse-impl-slot-7:20261004-004600

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d7148fd]

Summary: ✅


AI Review

Summary

This PR restores optimize_and_compare_chain inference through a DateTime or lower-scale DateTime64 constant compared with a DateTime64 expression by normalizing that constant to the expression type before the chain is built. The changed code and the new stateless test cover the core positive and negative cases, including cross-time-zone widening, non-lossless cases, remote execution, and join-side pruning, and I did not find an unresolved correctness or evidence gap in the current revision.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit d7148fd.

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

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 4, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d7148fdc8 with master 80f00c857 (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.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes one rewrite in the analyzer: optimize_and_compare_chain now also handles comparisons where a DateTime or lower-scale DateTime64 constant meets a DateTime64 expression. It only runs at query-planning time, and only for such comparisons. None of the three flagged ClickBench queries (Q18 at +12.2%, Q33 at +5.1%, Q34 at +8.9%) has a filter like that; all are heavy GROUP BY queries, so the rewrite is never triggered. All three stay inside master's normal range, and two ClickBench PR runs were scheduled on the same machine, which fits the similar CPU rise across these unrelated queries. Keeping them as not_sure rather than calling them PR effects matches the diff, and there is no performance concern for this change.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 905 1015 +12.2% <0.0001 aggregation: This is a high-cardinality GROUP BY with no DateTime64 comparison chain. The changed analyzer rewrite never fires here, so the +12.2% is unrelated to the PR.
⚠️ 33 not_sure 1177 1237 +5.1% <0.0001 aggregation: This is a GROUP BY-heavy scan with no DateTime64 constant comparisons, so the changed code path is not executed. The +5.1% falls inside master's normal range.
⚠️ 34 not_sure 1160 1263 +8.9% <0.0001 aggregation: This is a GROUP BY on a string column with no comparison chain that the PR could rewrite. The +8.9% falls inside master's normal range and is not attributable to the diff.

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: 51523a0d-6300-426b-8282-49c2c947cde1
  • MIRAI run: f21a9bc7-906c-4706-aff8-efaf9f8f6029
  • PR check IDs:
    • clickbench_3144380_1791083128
    • clickbench_3144391_1791083128
    • clickbench_3144399_1791083128
    • tpch_adapted_1_official_3144424_1791083128
    • tpch_adapted_1_official_3144438_1791083128
    • tpch_adapted_1_official_3144453_1791083128

@yariks5s yariks5s self-assigned this Oct 5, 2026
@yariks5s
yariks5s added this pull request to the merge queue Oct 5, 2026
Merged via the queue into ClickHouse:master with commit c920a28 Oct 5, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 5, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 5, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

@yariks5s, both backports (#124065 for 26.8, #124066 for 26.9) fail to compile because tryConvertFieldToTypeExact comes from #121078, which is on neither branch. That is the only error: all 14 build logs show 1 error generated in LogicalExpressionOptimizerPass.cpp. Could you apply these two changes to backport/26.8/123796 and backport/26.9/123796? I can't push there.

  1. src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp, tryNormalizeConstEdge:
-            converted = tryConvertFieldToTypeExact(constant_node->getValue(), *other_type, constant_type.get());
+            converted = tryConvertFieldToType(constant_node->getValue(), *other_type, constant_type.get(), {}, /*strict=*/true);

This gives the same result as master. tryConvertFieldToTypeExact is this strict conversion plus a round trip back to the constant's type. This call only widens a DateTime or lower-scale DateTime64 constant to a DateTime64. That widening is either exact or fails on overflow, so the round trip never rejects anything here.

  1. 05330_optimize_and_compare_chain_time_point_constant_scale.sql, case implied condition is not duplicated: in both of its queries, change a < toDateTime('2020-01-01 00:00:02', 'UTC') to a < toDateTime64('2020-01-01 00:00:02', 6, 'UTC'). Without this, that line prints 0 on the branches. The existing a < <DateTime> conjunct goes through tryConvertToColumnType, whose round trip from DateTime64 back to DateTime throws TYPE_MISMATCH there (TYPE_MISMATCH counted in system.errors during key condition analysis (regression in 26.7.1) #117903, fixed only on master by Convert a DateTime64 field back to DateTime #121078). The derived bound is therefore not seen as implied and is added as an extra indexHint; results are unaffected. On 26.9.6.6, that query raises TYPE_MISMATCH in system.errors by 2; on master it does not. The changed case still derives through the DateTime constant on b.

Backporting #121078 instead would not apply cleanly: it edits the Time64 conversion code from #106019, which is on neither branch.

I worked this out by reading the code and did not build the branches.

yariks5s pushed a commit that referenced this pull request Oct 12, 2026
…his branch

tryConvertFieldToTypeExact comes from #121078, which is not on this branch.
At this call site only a widening conversion (DateTime or lower-scale
DateTime64 to DateTime64) reaches it, which is exact or overflows to Null,
so the strict tryConvertFieldToType gives the same result.

In 05330, the "implied condition is not duplicated" case compares `a` with a
DateTime64 constant instead of a DateTime one: on this branch the existing
`a < <DateTime>` conjunct hits TYPE_MISMATCH in tryConvertToColumnType
(#117903, fixed on master by #121078), so it is not seen as implying the
derived bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
yariks5s pushed a commit that referenced this pull request Oct 12, 2026
…his branch

tryConvertFieldToTypeExact comes from #121078, which is not on this branch.
At this call site only a widening conversion (DateTime or lower-scale
DateTime64 to DateTime64) reaches it, which is exact or overflows to Null,
so the strict tryConvertFieldToType gives the same result.

In 05330, the "implied condition is not duplicated" case compares `a` with a
DateTime64 constant instead of a DateTime one: on this branch the existing
`a < <DateTime>` conjunct hits TYPE_MISMATCH in tryConvertToColumnType
(#117903, fixed on master by #121078), so it is not seen as implying the
derived bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #123796 to 26.8: Derive `optimize_and_compare_chain` ranges through a `DateTime` constant compared with `DateTime64`
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #123796 to 26.9: Derive `optimize_and_compare_chain` ranges through a `DateTime` constant compared with `DateTime64`
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 13, 2026
…n` ranges through a `DateTime` constant compared with `DateTime64`
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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Range condition derived from join inequalities no longer prunes the right table, up to 34x slower (26.6 -> 26.8)

5 participants