Repository navigation
Fix loss of primary-key pruning for DateTime64 columns under a toUnixTimestamp sorting key - #114413
Conversation
`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]>
|
Workflow [PR], commit [8b447a7] Summary: ✅
AI ReviewSummaryThis PR restores Final VerdictStatus: ✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 51/58 (87.93%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units1245 translation units recompiled, 9389 s compile time in total, 1245 of them have a recent master baseline. |
|
📊 Cloud Performance Report 🟢 AI verdict: 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 · Flagged queries (3 of 43)
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)
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
|
…-datetime64-key-pruning
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]>
`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]>
…-datetime64-key-pruning
|
🕵 @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.
|
|
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
So this is a lost SYN, not a slow start and not a query result. Nothing in The host-side cause is in 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. I checked the subnet-collision theory and it is wrong: What makes this fatal rather than invisible is the test side. 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). |
|
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 What was wrong is the explanation. I blamed the I then looked for any real disturbance of that network inside the connect window. Filtering the daemon log for 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: 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. |
Backport #114413 to 26.7: Fix loss of primary-key pruning for `DateTime64` columns under a `toUnixTimestamp` sorting key
Closes: #114407
Related: #79977
Related: #101814
For a
MergeTreetable withORDER BY toUnixTimestamp(ts)wheretsisDateTime64, a plain range filter onts(e.g.WHERE ts >= '2026-06-15') stopped using the primary key in 26.7:EXPLAIN indexes = 1showsPrimaryKey Condition: trueand every granule of the matched parts is read.The regression came from #101814, which correctly changed the monotonicity gate in
KeyCondition::extractMonotonicFunctionsChainFromKeyto askgetMonotonicityForRangeover the function's argument type instead of its result type. That exposed a gap:ToNumberMonotonicity(the monotonicity implementation behindtoUnixTimestampand thetoInt*/toUInt*family) did not supportDateTime64arguments at all and answered "unknown", so the monotonic chain was rejected and the pruning was silently lost. Keys liketoDate(ts)ortoStartOfHour(ts)were unaffected because their monotonicity classes handleDateTime64explicitly, andtoUnixTimestampover a plainDateTimecolumn was unaffected becauseDateTimeis on the whitelist ofToNumberMonotonicity.This PR teaches
ToNumberMonotonicityto answer forDateTime64arguments. The conversion takes the whole number of seconds, truncating the fractional part toward zero, and throws aDECIMAL_OVERFLOWexception instead of wrapping around (seeDecimalUtils::convertTo), so it preserves order everywhere it is defined:toInt64), the conversion is total — the whole number of seconds of anyDateTime64fits — so it is reported asis_always_monotonic, for concrete ranges as well. As a bonus, the mirror-image filtertoInt64(ts) >= coverORDER BY tsnow prunes too (the batched application over columns of index values can never throw), and stays consistent with the exact-rangescount()optimization.toUnixTimestamp, whose result isUInt32), the conversion throws for a part of the domain, so it must not claimis_always_monotonic:matchesExactContinuousRangetakes 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 "InconsistentKeyConditionbehavior" (a logical error, so the stateless runs on the debug build also showed "Server died"). Instead, the conversion now reports a new flagMonotonicity::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 incanConstantBeWrappedByMonotonicFunctions. 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 inapplyFunctionChainToColumn.Per the review findings, those guards are also fixed: the pre-execution range checks are extended from
Date/DateTime/UInt32to 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 aDECIMAL_OVERFLOWexception 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-01filters.For partial conversions like
toUnixTimestamp, the mirror-image case #79977 (WHERE toUnixTimestamp(ts) >= coverORDER BY ts, a full scan since 23.1) remains out of scope: index analysis applies chain functions to whole columns of index values (seeapplyFunctioninKeyCondition.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 liketoInt64it 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 theUInt32range,toInt64sorting keys including pre-1970-01-01filters, out-of-range constants over a narrowtoUInt8key, the mixed-part case where index analysis must not throw an exception, and the exact-rangescount()optimization over a total conversion.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a regression in 26.7: for a
MergeTreetable ordered bytoUnixTimestamp(or another integer conversion) of aDateTime64column, a plain range filter on that column no longer used the primary key and read all granules of the matched parts. Additionally, a filter liketoInt64(ts) >= cover a table ordered by the rawDateTime64column now uses the primary key.Version info
26.7.38.17