Skip to content

Fix loss of primary-key pruning for DateTime64 columns under a toUnixTimestamp sorting key - #114413

Merged
alexey-milovidov merged 10 commits into
masterfrom
fix-tounixtimestamp-datetime64-key-pruning
Aug 15, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
fix-tounixtimestamp-datetime64-key-pruning

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Closes: #114407
Related: #79977
Related: #101814

For a MergeTree table with ORDER BY toUnixTimestamp(ts) where ts is DateTime64, a plain range filter on ts (e.g. WHERE ts >= '2026-06-15') stopped using the primary key in 26.7: EXPLAIN indexes = 1 shows PrimaryKey Condition: true and every granule of the matched parts is read.

The regression came from #101814, which correctly changed the monotonicity gate in KeyCondition::extractMonotonicFunctionsChainFromKey to ask getMonotonicityForRange over the function's argument type instead of its result type. That exposed a gap: ToNumberMonotonicity (the monotonicity implementation behind toUnixTimestamp and the toInt*/toUInt* family) did not support DateTime64 arguments at all and answered "unknown", so the monotonic chain was rejected and the pruning was silently lost. Keys like toDate(ts) or toStartOfHour(ts) were unaffected because their monotonicity classes handle DateTime64 explicitly, and toUnixTimestamp over a plain DateTime column was unaffected because DateTime is on the whitelist of ToNumberMonotonicity.

This PR teaches ToNumberMonotonicity to answer for DateTime64 arguments. The conversion takes the whole number of seconds, truncating the fractional part toward zero, and throws a DECIMAL_OVERFLOW exception instead of wrapping around (see DecimalUtils::convertTo), so it preserves order everywhere it is defined:

  • For a signed target of at least 64 bits (e.g. toInt64), the conversion is total — the whole number of seconds of any DateTime64 fits — so it is reported as is_always_monotonic, for concrete ranges as well. As a bonus, the mirror-image filter toInt64(ts) >= c over ORDER BY ts now prunes too (the batched application over columns of index values can never throw), and stays consistent with the exact-ranges count() optimization.
  • For narrower or unsigned targets (e.g. toUnixTimestamp, whose result is UInt32), the conversion throws for a part of the domain, so it must not claim is_always_monotonic: matchesExactContinuousRange takes that claim as a promise that the per-range analysis can confirm every granule of a found range, while a part may hold out-of-range values, for which the per-range analysis has to answer "unknown". The first version of this PR made exactly that inconsistent claim, and the AST fuzzer found the debug assertion "Inconsistent KeyCondition behavior" (a logical error, so the stateless runs on the debug build also showed "Server died"). Instead, the conversion now reports a new flag Monotonicity::is_always_monotonic_where_defined — monotonic over the subset of the domain where the evaluation succeeds — which is consumed only by the constant-pushdown gate in canConstantBeWrappedByMonotonicFunctions. It is sound there: stored keys cannot correspond to out-of-range values, because computing the sorting key at insert time would have thrown, and an unrepresentable constant is rejected gracefully by the guards in applyFunctionChainToColumn.

Per the review findings, those guards are also fixed: the pre-execution range checks are extended from Date/DateTime/UInt32 to the whole native integer family, so an out-of-range constant pushed through e.g. ORDER BY toUInt8(ts) is rejected gracefully instead of throwing a DECIMAL_OVERFLOW exception during index analysis, and the negative-value fast reject is now unsigned-specific, so signed integer keys (e.g. ORDER BY toInt64(ts)) keep pruning for pre-1970-01-01 filters.

For partial conversions like toUnixTimestamp, the mirror-image case #79977 (WHERE toUnixTimestamp(ts) >= c over ORDER BY ts, a full scan since 23.1) remains out of scope: index analysis applies chain functions to whole columns of index values (see applyFunction in KeyCondition.cpp), and a part may contain out-of-range values next to the checked range, for which the batched conversion would throw an exception. For total conversions like toInt64 it is fixed here.

The test covers the restored pruning (with force_primary_key), sub-second bounds of the relaxed atom (positive and negative), constants outside the UInt32 range, toInt64 sorting keys including pre-1970-01-01 filters, out-of-range constants over a narrow toUInt8 key, the mixed-part case where index analysis must not throw an exception, and the exact-ranges count() optimization over a total conversion.

Changelog category (leave one):

  • Performance Improvement

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

Fixed a regression in 26.7: for a MergeTree table ordered by toUnixTimestamp (or another integer conversion) of a DateTime64 column, a plain range filter on that column no longer used the primary key and read all granules of the matched parts. Additionally, a filter like toInt64(ts) >= c over a table ordered by the raw DateTime64 column now uses the primary key.

Version info

  • Backported to: 26.7.38.17

`ORDER BY toUnixTimestamp(ts)` with `ts DateTime64` lost primary-key
pruning for plain filters on `ts` in 26.7: PR #101814 correctly started
asking `getMonotonicityForRange` over the function's argument type, but
`ToNumberMonotonicity` had no support for `DateTime64` arguments and
answered "unknown", so `KeyCondition::extractMonotonicFunctionsChainFromKey`
rejected the monotonic chain.

Teach `ToNumberMonotonicity` to answer for `DateTime64` arguments: the
conversion truncates the fractional part toward zero and throws a
`DECIMAL_OVERFLOW` exception instead of wrapping around, so it preserves
order everywhere it is defined. Only the unbounded question is answered
positively: index analysis applies chain functions to whole columns of
index values, which may contain values outside the target type's range,
so claiming monotonicity over concrete ranges would make the analysis
throw an exception on parts with such values.

Issue: #114407

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8b447a7]

Summary: ✅


AI Review

Summary

This PR restores MergeTree primary-key pruning for DateTime64 values wrapped by integer-conversion sorting keys and carries through the follow-up fixes for overflow handling, signed and unsigned boundary cases, wide integer targets, and nullable wrappers. I reviewed the current code and the full prior discussion, and I did not find any remaining correctness, safety, or evidence gaps in the current head.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.70% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 51/58 (87.93%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 12, 2026
Comment thread src/Functions/FunctionsConversion.h Resolved
Comment thread src/Functions/FunctionsConversion.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8b447a705 with master 6d0a17390 (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
Binary Master PR Δ
programs/clickhouse-stripped 693.26 MiB 690.23 MiB -3.02 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 35 analysed

This PR is a targeted correctness fix that restores key pruning through numeric conversions of DateTime64 sorting keys (e.g. ORDER BY toUnixTimestamp(ts)); none of the ClickBench or TPC-H benchmark tables use that pattern. The clickbench Q17 (-11.8%) and Q30 (+18.3%, with flat CPU) deltas are off-path and read as run-to-run variance, so they are downgraded. The large, consistent improvements on tpch Q7 (×8.1 faster) and Q8 (×2.2 faster) and clickbench Q23 (×2.2 faster) are strong enough to stand on the measurements, but this diff does not obviously touch those query paths, so their cause should be verified separately.

clickbench

🟢 1 improved · ⚠️ 2 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 23 improvement 167 76 ×2.2 faster <0.0001 The ×2.2 faster delta is large and consistent, but this PR's DateTime64 key-pruning fix doesn't touch this query's path and its history is flaky, so treat the cause as unconfirmed.
⚠️ 17 not_sure 556 490 -11.8% <0.0001 aggregation: Q17 is a plain GROUP BY aggregation that never touches this PR's DateTime64 key-pruning change, so the -11.8% reads as run-to-run variance, not a PR effect.
⚠️ 30 not_sure 279 330 +18.3% <0.0001 cpu: Q30 is a wide arithmetic SUM; source CPU is flat versus base (2751 vs 2772 ms) despite the +18.3% wall-clock bump, and the diff can't touch this path, so it's environmental variance.

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

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 574 71 ×8.1 faster <0.0001 plan_change: ×8.1 faster with an 18x CPU drop is a large, consistent shift. This PR's key-pruning change targets DateTime64 sorting keys, which this join query doesn't use, so confirm the cause separately.
🟢 8 improvement 175 80 ×2.2 faster <0.0001 plan_change: ×2.2 faster and consistent across both tests. Like Q7, this PR's DateTime64 key-pruning fix doesn't obviously map to this query, so the improvement's cause is unconfirmed.

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.

Debug info
  • StressHouse run: f96cac8f-ea65-441b-a909-108a83af49d0
  • MIRAI run: eacfbf93-e194-4c73-9298-de862b608c14
  • PR check IDs:
    • clickbench_1419148_1786805970
    • clickbench_1419162_1786805971
    • clickbench_1419168_1786805971
    • tpch_adapted_1_official_1419179_1786805970
    • tpch_adapted_1_official_1419205_1786805971
    • tpch_adapted_1_official_1419220_1786805971

@yariks5s yariks5s self-assigned this Aug 12, 2026
alexey-milovidov and others added 2 commits August 13, 2026 09:33
The previous approach answered "always monotonic" for the unbounded question
and "unknown" for any concrete range. That asymmetry is unsound:
`matchesExactContinuousRange` takes the unbounded answer as a promise that
per-range analysis can confirm every granule of the found range, and the
consistency assertion in `MergeTreeDataSelectExecutor` fires a logical error
in debug builds ("Inconsistent KeyCondition behavior", found by the AST
fuzzer and by the new test itself on the previous CI run:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114413&sha=1cda145c7aee25ba8ae8c46e79f29595b64d39d2&name_0=PR).

Now the answers are consistent:

- For a signed target of at least 64 bits (e.g. `toInt64`), the conversion
  is total (the whole number of seconds of any `DateTime64` fits), so it is
  genuinely `is_always_monotonic` - on any range. As a bonus, a filter like
  `toInt64(ts) >= c` over `ORDER BY ts` now prunes too, and the exact-ranges
  `count()` optimization stays consistent.
- For narrower or unsigned targets (e.g. `toUnixTimestamp`), the conversion
  throws a `DECIMAL_OVERFLOW` exception for a part of the domain, so it must
  not claim `is_always_monotonic`. Instead it sets a new flag
  `is_always_monotonic_where_defined`, which only the constant-pushdown gate
  in `canConstantBeWrappedByMonotonicFunctions` consumes: stored key values
  always belong to the defined subset (computing the sorting key at insert
  time would have thrown otherwise), and out-of-range constants are rejected
  by the guards in `applyFunctionChainToColumn`.

Also address the review findings on those guards:
- extend the pre-execution range checks from `Date`/`DateTime`/`UInt32` to
  the whole native integer family, so an out-of-range constant pushed through
  e.g. `ORDER BY toUInt8(ts)` is rejected gracefully instead of throwing
  a `DECIMAL_OVERFLOW` exception during index analysis;
- make the negative-value fast reject unsigned-specific, so signed integer
  keys (e.g. `ORDER BY toInt64(ts)`) keep pruning for pre-1970 filters.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 3 commits August 14, 2026 15:53
`DecimalUtils::convertToImpl` rejects an unsigned integer target by the
truncated whole number of seconds, not by the raw `DateTime64` tick value.
A pre-epoch sub-second value such as `1969-12-31 23:59:59.500` therefore
converts to `0` and is inside the domain of `toUnixTimestamp`, so a sorting
key `ORDER BY toUnixTimestamp(ts)` can legitimately contain that boundary
slice. The raw `value < 0` fast reject in `applyFunctionChainToColumn` was
stricter than the conversion itself and lost pruning for predicates such as
`ts < '1970-01-01 00:00:00'` on valid data.

Compare `seconds < 0` instead, which is exactly what the conversion checks.
The `Date`/`DateTime` branch keeps the raw check: `toDateTime` of a negative
sub-second value wraps around to `2106-02-07`, so those targets must still
reject the whole negative side.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The `EXPLAIN indexes = 1` lines are printed with a query-plan tree prefix
when the plan has sibling branches, which happens in the `ParallelReplicas`
CI configuration. `trimLeft` does not remove the box-drawing characters of
that prefix, so the test failed there; strip everything before the first
letter instead.

Also add the cases requested by the review: a pre-epoch sub-second constant
on an unsigned key (`toUInt8` and `toUnixTimestamp`) must still be pushed
through the key.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114413&sha=a8f3ba22628243038378b93d3392440a636395dc&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%201%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

test_backward_compatibility/test_convert_ordinary.py::test_convert_ordinary_to_atomic failed with Code: 209. DB::NetException: Timeout: connect timed out: 172.16.2.5:9000 while querying the old-version node, i.e. the node was not accepting connections, not a query result mismatch. This PR only changes KeyCondition constant pushdown and ToNumberMonotonicity, so it cannot affect server startup; the harness also labelled the failure retry_ok. There is no other occurrence of this test failing in the last 21 days in the CI database, so no tracking issue exists yet.

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

Copy link
Copy Markdown
Collaborator

I read the job artifacts. Your reading is right, and the node was not even the problem: it was up and accepting connections the whole time.

The old node is clickhouse/clickhouse-server:25.3 (CLICKHOUSE_CI_MIN_TESTED_VERSION), 25.3.14.14. From its own log:

  • 12:27:04.452 Application: Ready for connections. and Listening for native protocol (tcp): 0.0.0.0:9000
  • it served DROP DATABASE, CREATE DATABASE default2, CREATE TABLE and both INSERTs over TCP
  • the 1M-row INSERT finished fine (12:27:06.704 executeQuery: Read 1000000 rows, 7.63 MiB in 0.069819 sec.), then a clean logout
  • the harness issued the failing SELECT count() FROM default2.t at 12:27:06.926, and after that there is no TCPHandlerFactory: TCP Request line at all. The SYN never reached the server process.
  • the server stayed alive and idle, flushed system logs at 12:27:11.9, and exited only on the harness docker compose stop (12:27:18.325 Received signal 15). No crash, no coredump.

So this is a lost SYN, not a slow start and not a query result. Nothing in KeyCondition or ToNumberMonotonicity can reach it.

The host-side cause is in docker-in-docker.log. Inside the 10 second connect window another worker (test_threadpool_readers-gw0) was tearing its cluster down and rewriting globally shared chains:

12:27:07.878  -D FORWARD -j DOCKER-ISOLATION-STAGE-1
12:27:07.887  -I FORWARD -j DOCKER-ISOLATION-STAGE-1
12:27:07.907  -D FORWARD -j DOCKER-USER
12:27:07.920  -I FORWARD -j DOCKER-USER

139 iptables calls in that window, 11 on the DOCKER-ISOLATION chains, plus new embedded-DNS DNAT/SNAT rules as two other clusters came up. Every container-to-container packet traverses FORWARD, so those delete/reinsert gaps drop traffic belonging to other tests. 172.16.2.5 is also hot-recycled: 5 owner changes in the 7 minutes before this test got it, the previous holder releasing it 7 seconds earlier.

I checked the subnet-collision theory and it is wrong: 172.16.2.0/24 is reused by 39 bridges across the job but never by two at once, and the relevant MASQUERADE rule was in place for the whole window.

What makes this fatal rather than invisible is the test side. q() calls plain node.query(), so the connect budget is the bare default (DBMS_DEFAULT_CONNECT_TIMEOUT_SEC = 10) with no retry: helpers/client.py get_answer() raises on the first non-zero client exit. cluster.py already has query_with_retry, which retries this while still re-raising immediately on "No route to host", so a genuinely dead container keeps failing fast. This test does not use it, and the first query after setup and after restart_with_latest_version is exactly where a transient hurts.

I am preparing the fix in a separate PR along those lines and will link it here. I found no existing PR for it (#114527 is a different test).

@groeneai

Copy link
Copy Markdown
Collaborator

I have to correct my earlier comment: the host-side cause I gave was wrong, and I am not sending the fix I described.

The part that holds is the node itself. It was up, listening and serving: the 1M-row INSERT completed at 12:27:06.704, and after the clean logout at 12:27:06.731 there is no further TCPHandlerFactory: TCP Request line, so the SYN for the failing SELECT count() never reached the server process. Nothing in KeyCondition or ToNumberMonotonicity is involved.

What was wrong is the explanation. I blamed the FORWARD -j DOCKER-ISOLATION-STAGE-1 / -j DOCKER-USER delete-and-reinsert by a sibling worker. That chain is not on this path. node.query() runs clickhouse client as a host process (helpers/client.py sp.Popen, host-side client_bin_path), so the connection is host namespace to container across the bridge and traverses INPUT/OUTPUT, not FORWARD. The server's own log agrees: the peer was 172.16.2.1, which is the gateway address of its own bridge br-c5f16f7ee0ce. Those gaps were also only 9 ms and 13 ms, and a 10 s connect budget covers SYN retransmissions at roughly 1, 2, 4 and 8 s, so even on-path they would not produce this.

I then looked for any real disturbance of that network inside the connect window. Filtering the daemon log for c5f16f7ee0ce, 172.16.2. and the test's own network between 12:27:06.9 and 12:27:17 returns one line, a sibling's pool request that explicitly excludes 172.16.2.0/24. The bridge, the veth and the subnet were untouched, and the MASQUERADE rule stood from 12:26:57.677 to 12:27:20.093. The conntrack purges are before the INSERT that then succeeded, the vethf5a0107 collision belongs to another test's teardown, and DNS is not used since the client is handed an IP.

So I cannot say why the SYN was lost. My planned fix was to widen the client connect timeout, and since the timeout's exhaustion is unexplained that is a band-aid on an unknown mechanism, so I am not opening it. Two things I would have got wrong anyway: q() also wraps the two INSERTs, so wrapping it in query_with_retry risks re-running a completed 1M-row insert and turning a connect blip into a 2000001 count mismatch, and a readiness wait would be pointless because the node was already serving.

This is one occurrence in 30 days of CI database history and none on master, and I cannot reproduce it, so I would rather leave the test alone than change it on a guess. If it recurs I will pick it up with a second data point. Sorry for the noise in the first comment.

Comment thread src/Functions/FunctionsConversion.h Resolved

@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 Aug 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 15, 2026
Merged via the queue into master with commit 877a8fc Aug 15, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-tounixtimestamp-datetime64-key-pruning branch August 15, 2026 21:21
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 15, 2026
@CheSema CheSema added v26.6-must-backport and removed pr-synced-to-cloud The PR is synced to the cloud repo labels Oct 23, 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 23, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 23, 2026
Backport #114413 to 26.7: Fix loss of primary-key pruning for `DateTime64` columns under a `toUnixTimestamp` sorting key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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 v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

toUnixTimestamp() in ORDER BY silently loses primary-key pruning starting in 26.7 (regression from 26.6)

7 participants