From a45a481cc47cb8adb28410e3acf52d9220943f77 Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Fri, 20 Nov 2026 10:05:29 +0000 Subject: [PATCH 1/2] perf: preserve `date_trunc` ordering for timezone-aware timestamps at minute and finer granularities (#27547) ## Which issue does this PR close? - Part of #25464. ## Rationale for this change #25409 stopped `date_trunc` from propagating its input ordering for every timezone-aware timestamp, because truncating in local time can go backwards across a timezone transition (#25353). That is broader than it needs to be. For `minute` and finer granularities `date_trunc` never consults the timezone: it rounds the epoch value down to a multiple of the granularity (`truncates_in_input_unit`), and rounding down cannot reorder values. So since 56, sorting or grouping timezone-aware timestamps by `date_trunc('minute', ts)` or `date_trunc('second', ts)` over input ordered on `ts` adds a sort, or keeps every group in the hash table until the input ends, where 55 streamed. Time-bucketed aggregation over sorted, timezone-aware data is the common shape for this. #25464 asks to restore the safe timezone-aware cases and notes that particular granularities can be evaluated separately. #25635 covers one axis (UTC and fixed offsets, every granularity). This PR covers the other (every timezone, `minute` and finer). They are independent; both change the same `match` arm, so whichever lands second needs a one-line merge. ## What changes are included in this PR? `DateTruncFunc::output_ordering` now propagates the input ordering for a timezone-aware timestamp when the precision is a known constant and `truncates_in_input_unit` holds for it. It uses the predicate that selects the arithmetic kernel, so ordering is claimed exactly when that kernel runs. If a granularity is ever moved to the local-time path (for example to make `minute` exact for historical sub-minute offsets, which the kernel ignores today), the ordering claim goes away with it. Hour and coarser granularities in a timezone, and precisions whose value is not known, stay unordered. ## What is the testing strategy for this PR? - `timestamps.slt` extends the existing `America/Goose_Bay` regression from #25353. Across the same transition, `date_trunc('minute', ..)` returns correctly ordered rows without a `SortExec`, and `GROUP BY` runs with `group_clustering_mode=Full`. The existing `hour` case keeps its sort. The two new `EXPLAIN` cases fail without the change. - A unit test covers what is impractical to reach from SQL: each granularity for each time unit, the literal's string type and case, and a constant precision whose value is unknown. As a check outside the test suite, I ran the kernel over every UTC-offset transition between 1800 and 2037 of all 597 zones in the tz database, with a few hundred instants around each one. `minute` and finer never reversed. `hour` reversed in 43 zones and `day` in 21. ### Benchmarks 20M rows, one per second, in a `Timestamp(ns, "America/New_York")` column, one Parquet file declared `WITH ORDER (ts ASC)`. `datafusion-cli` release build on an Apple M4 Pro (12 cores), median of 5 runs, wall time and peak RSS of the whole process. | Query | `main` | This PR | | --- | --- | --- | | `SELECT date_trunc('minute', ts) AS d FROM t ORDER BY d` (`EXPLAIN ANALYZE`) | 0.35 s, 333 MiB | 0.24 s, 106 MiB | | `GROUP BY` minute, `ORDER BY m LIMIT 1` | 0.06 s, 144 MiB | 0.08 s, 119 MiB | | `GROUP BY` minute (333k groups) | 0.06 s, 142 MiB | 0.24 s, 131 MiB | | `GROUP BY` second (20M groups) | 0.17 s, 1172 MiB | 0.51 s, 151 MiB | | `GROUP BY` minute, `target_partitions = 1` | 0.24 s, 66 MiB | 0.23 s, 36 MiB | | `GROUP BY` second, `target_partitions = 1` | 0.80 s, 1454 MiB | 0.46 s, 37 MiB | | `GROUP BY` hour (plan unchanged) | 0.37 s, 120 MiB | 0.36 s, 119 MiB | The full `GROUP BY` queries are the part to look at. Memory no longer grows with the number of groups, and on one partition the clustered aggregation is as fast or faster. With 12 partitions it is slower in wall time, because the order-preserving plan drains the sorted file ranges one after another and so does not scale with cores the way the hash aggregation does. This is the effect described in https://github.com/apache/datafusion/pull/25635#discussion_r4176172834. This is not a new trade-off: it is the plan `main` already picks for the same queries over a timezone-less timestamp column, with the same numbers (0.24 s, 126 MiB for minute and 0.52 s, 151 MiB for second). The PR makes the timezone-aware case consistent with it. Whether the planner should prefer the clustered plan when it costs parallelism is a separate question, and not one this PR changes.
Benchmark setup ```sql COPY ( SELECT arrow_cast( arrow_cast(arrow_cast(value * 1000000000, 'Timestamp(Nanosecond, None)'), 'Timestamp(Nanosecond, Some("UTC"))'), 'Timestamp(Nanosecond, Some("America/New_York"))') AS ts FROM generate_series(0, 19999999) ORDER BY value ) TO 'ny.parquet'; CREATE EXTERNAL TABLE t STORED AS PARQUET LOCATION 'ny.parquet' WITH ORDER (ts ASC); EXPLAIN ANALYZE SELECT date_trunc('minute', ts) AS d FROM t ORDER BY d; SELECT date_trunc('minute', ts) AS m, count(*) FROM t GROUP BY m ORDER BY m LIMIT 1; SELECT count(*), max(c) FROM (SELECT date_trunc('minute', ts) AS m, count(*) AS c FROM t GROUP BY m); SELECT count(*), max(c) FROM (SELECT date_trunc('second', ts) AS s, count(*) AS c FROM t GROUP BY s); SELECT count(*), max(c) FROM (SELECT date_trunc('hour', ts) AS h, count(*) AS c FROM t GROUP BY h); ```
## Are there any user-facing changes? Queries that sort or group timezone-aware timestamps by `date_trunc` at `minute` or finer granularity, over input ordered on the timestamp, no longer add a sort and aggregate with clustered aggregation. Results are unchanged. No API changes. (cherry picked from commit 477c7b9ebc88b879d5b8c8d60b21ba4a80593b9d) --- .../functions/src/datetime/date_trunc.rs | 100 +++++++++++++++++- .../test_files/datetime/timestamps.slt | 40 +++++++ 2 files changed, 136 insertions(+), 4 deletions(-) diff --git a/datafusion/functions/src/datetime/date_trunc.rs b/datafusion/functions/src/datetime/date_trunc.rs index d5cf186bc14de..e1cf374efb3bb 100644 --- a/datafusion/functions/src/datetime/date_trunc.rs +++ b/datafusion/functions/src/datetime/date_trunc.rs @@ -547,10 +547,21 @@ impl ScalarUDFImpl for DateTruncFunc { let precision = &input[0]; let date_value = &input[1]; - let order_safe_input = matches!( - date_value.range.data_type(), - Timestamp(_, None) | Time32(_) | Time64(_) - ); + let order_safe_input = match date_value.range.data_type() { + Timestamp(_, None) | Time32(_) | Time64(_) => true, + // A timezone transition can reverse the order of timestamps + // truncated in local time, but not of those truncated on the + // epoch value. + Timestamp(_, Some(tz)) => { + match (constant_granularity(precision), parse_tz(Some(&tz))) { + (Some(granularity), Ok(tz)) => { + truncates_in_input_unit(granularity, tz.as_ref()) + } + _ => false, + } + } + _ => false, + }; if precision.sort_properties == SortProperties::Singleton && order_safe_input { Ok(date_value.sort_properties) @@ -710,6 +721,16 @@ where 1 + 3 * ((date.month() - 1) / 3) } +/// The granularity `precision` always evaluates to, if that is known. +fn constant_granularity(precision: &ExprProperties) -> Option { + let range = &precision.range; + if range.lower() != range.upper() { + return None; + } + let granularity = range.lower().try_as_str().flatten()?; + parse_granularity(granularity).ok() +} + /// Returns true if `tz` explicitly names UTC (`"UTC"` or `"+00:00"`) fn is_utc(tz: &str) -> bool { tz.eq_ignore_ascii_case("utc") || tz == "+00:00" @@ -1233,6 +1254,9 @@ fn general_date_trunc_array_fine_granularity( /// Both datafusion and arrow are ignoring historical timezone's non-minute granularity /// bias (e.g., Asia/Kathmandu before 1919 is UTC+05:41:16). /// In UTC, "hour" and "day" have uniform durations and can be truncated with simple arithmetic +/// +/// Rounding down never reorders values, whatever the timezone, which +/// [`DateTruncFunc::output_ordering`] relies on. fn truncates_in_input_unit(granularity: DatePart, tz: Option<&Tz>) -> bool { granularity.is_fine_granularity() || (tz.is_none() && granularity.is_fine_granularity_utc()) @@ -1400,6 +1424,74 @@ mod tests { ); } + #[test] + fn output_ordering_with_timezone_depends_on_granularity() { + let constant = |value: ScalarValue| { + ExprProperties::new_unknown() + .with_order(SortProperties::Singleton) + .with_range(Interval::try_new(value.clone(), value).unwrap()) + }; + let ordered = SortProperties::Ordered(SortOptions::default()); + let function = DateTruncFunc::new(); + let output_ordering = |precision: ExprProperties, unit| { + let data_type = DataType::Timestamp(unit, Some("America/Goose_Bay".into())); + let timestamp = ExprProperties::new_unknown() + .with_order(ordered) + .with_range(Interval::make_unbounded(&data_type).unwrap()); + function.output_ordering(&[precision, timestamp]).unwrap() + }; + + for unit in [ + TimeUnit::Second, + TimeUnit::Millisecond, + TimeUnit::Microsecond, + TimeUnit::Nanosecond, + ] { + for granularity in ["microsecond", "millisecond", "second", "minute"] { + assert_eq!( + output_ordering(constant(ScalarValue::from(granularity)), unit), + ordered, + "{granularity} {unit:?}" + ); + } + for granularity in ["hour", "day", "week", "month", "quarter", "year"] { + assert_eq!( + output_ordering(constant(ScalarValue::from(granularity)), unit), + SortProperties::Unordered, + "{granularity} {unit:?}" + ); + } + } + + for precision in [ + ScalarValue::Utf8(Some("MINUTE".into())), + ScalarValue::Utf8View(Some("minute".into())), + ScalarValue::LargeUtf8(Some("minute".into())), + ] { + assert_eq!( + output_ordering(constant(precision), TimeUnit::Nanosecond), + ordered + ); + } + + // A constant whose value is not known, such as a column that holds a + // single value, may name any granularity. + let unknown_constant = ExprProperties::new_unknown() + .with_order(SortProperties::Singleton) + .with_range(Interval::make_unbounded(&DataType::Utf8).unwrap()); + assert_eq!( + output_ordering(unknown_constant, TimeUnit::Nanosecond), + SortProperties::Unordered + ); + assert_eq!( + output_ordering( + constant(ScalarValue::from("not a granularity")), + TimeUnit::Nanosecond + ), + SortProperties::Unordered + ); + } + #[test] fn range_key_locality_analysis_requires_timezone_less_timestamp() { let date_trunc = DateTruncFunc::new(); diff --git a/datafusion/sqllogictest/test_files/datetime/timestamps.slt b/datafusion/sqllogictest/test_files/datetime/timestamps.slt index ba2def1c055a6..ec1bdbbe7e9f9 100644 --- a/datafusion/sqllogictest/test_files/datetime/timestamps.slt +++ b/datafusion/sqllogictest/test_files/datetime/timestamps.slt @@ -1973,6 +1973,46 @@ physical_plan 04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true 05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/timestamps/goose_bay_epochs.csv]]}, projection=[c], output_ordering=[c@0 ASC NULLS LAST], file_type=csv, has_header=true +# Minute and finer granularities are truncated on the epoch value, so the +# same transition does not reorder them and no sort is needed. +query II +SELECT + c, + arrow_cast( + date_trunc('minute', from_unixtime(c, 'America/Goose_Bay')), + 'Int64' + ) AS truncated +FROM goose_bay_epochs +ORDER BY date_trunc('minute', from_unixtime(c, 'America/Goose_Bay')); +---- +562129259 562129200 +562129260 562129260 + +query TT +EXPLAIN SELECT date_trunc('minute', from_unixtime(c, 'America/Goose_Bay')) AS bucket +FROM goose_bay_epochs +ORDER BY bucket; +---- +physical_plan +01)SortPreservingMergeExec: [bucket@0 ASC NULLS LAST] +02)--ProjectionExec: expr=[date_trunc(minute, from_unixtime(c@0, America/Goose_Bay)) as bucket] +03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/timestamps/goose_bay_epochs.csv]]}, projection=[c], output_ordering=[c@0 ASC NULLS LAST], file_type=csv, has_header=true + +# The aggregation can then emit each bucket as soon as the next one starts. +query TT +EXPLAIN SELECT date_trunc('minute', from_unixtime(c, 'America/Goose_Bay')) AS bucket, count(*) +FROM goose_bay_epochs +GROUP BY bucket; +---- +physical_plan +01)ProjectionExec: expr=[date_trunc(Utf8("minute"),from_unixtime(goose_bay_epochs.c,Utf8("America/Goose_Bay")))@0 as bucket, count(Int64(1))@1 as count(*)] +02)--AggregateExec: mode=FinalPartitioned, gby=[date_trunc(Utf8("minute"),from_unixtime(goose_bay_epochs.c,Utf8("America/Goose_Bay")))@0 as date_trunc(Utf8("minute"),from_unixtime(goose_bay_epochs.c,Utf8("America/Goose_Bay")))], aggr=[count(Int64(1))], group_clustering_mode=Full +03)----RepartitionExec: partitioning=Hash([date_trunc(Utf8("minute"),from_unixtime(goose_bay_epochs.c,Utf8("America/Goose_Bay")))@0], 4), input_partitions=4, preserve_order=true, sort_exprs=date_trunc(Utf8("minute"),from_unixtime(goose_bay_epochs.c,Utf8("America/Goose_Bay")))@0 ASC NULLS LAST +04)------AggregateExec: mode=Partial, gby=[date_trunc(minute, from_unixtime(c@0, America/Goose_Bay)) as date_trunc(Utf8("minute"),from_unixtime(goose_bay_epochs.c,Utf8("America/Goose_Bay")))], aggr=[count(Int64(1))], group_clustering_mode=Full +05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +06)----------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/timestamps/goose_bay_epochs.csv]]}, projection=[c], output_ordering=[c@0 ASC NULLS LAST], file_type=csv, has_header=true + statement ok DROP TABLE goose_bay_epochs; From ca89ab455f7d630f8690926bdbdd287dfaa87a8f Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Tue, 24 Nov 2026 09:28:07 +0800 Subject: [PATCH 2/2] perf: preserve `date_trunc` ordering for timezone-aware timestamps at day and coarser granularities `date_trunc` truncates day and coarser granularities in local time, and DataFusion stopped propagating its input ordering for every named zone because a transition can move local time back across a bucket boundary. While the UTC offset is constant, truncating to a day or longer is monotone: consecutive buckets start at least 24 hours apart and no offset change is that large. So the order can only break at a transition. For each zone, find every transition between 1800 and 2200 (daily steps plus bisection) and compare the kernel's output just before and at each one. Hour stays limited to zones without transitions. The result is cached per timezone name. An all-zone cross-check against dense sampling around every transition agreed exactly for day through year: 21 zones reverse at day (for example America/Goose_Bay), while America/New_York and UTC keep the order. (cherry picked from commit b32121fdd5ff7b2bab420b30050a41f2bdef0fab) --- .../functions/src/datetime/date_trunc.rs | 207 +++++++++++++++++- .../test_files/datetime/timestamps.slt | 26 +++ 2 files changed, 225 insertions(+), 8 deletions(-) diff --git a/datafusion/functions/src/datetime/date_trunc.rs b/datafusion/functions/src/datetime/date_trunc.rs index e1cf374efb3bb..08e4921f7d754 100644 --- a/datafusion/functions/src/datetime/date_trunc.rs +++ b/datafusion/functions/src/datetime/date_trunc.rs @@ -2,10 +2,11 @@ // SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements +use std::collections::HashMap; use std::num::NonZeroI64; use std::ops::{Add, Sub}; use std::str::FromStr; -use std::sync::Arc; +use std::sync::{Arc, LazyLock, Mutex, PoisonError}; use crate::datetime::common::parse_tz; use arrow::array::temporal_conversions::{ @@ -41,7 +42,7 @@ use datafusion_macros::user_doc; use chrono::{ DateTime, Datelike, Duration, LocalResult, Months, NaiveDate, NaiveDateTime, Offset, - TimeDelta, Timelike, Weekday, + TimeDelta, TimeZone, Timelike, Weekday, }; fn parse_granularity(value: &str) -> Result { @@ -552,10 +553,17 @@ impl ScalarUDFImpl for DateTruncFunc { // A timezone transition can reverse the order of timestamps // truncated in local time, but not of those truncated on the // epoch value. - Timestamp(_, Some(tz)) => { - match (constant_granularity(precision), parse_tz(Some(&tz))) { + Timestamp(_, Some(tz_name)) => { + match (constant_granularity(precision), parse_tz(Some(&tz_name))) { (Some(granularity), Ok(tz)) => { truncates_in_input_unit(granularity, tz.as_ref()) + || tz.is_some_and(|tz| { + local_truncation_preserves_order( + &tz_name, + tz, + granularity, + ) + }) } _ => false, } @@ -1262,6 +1270,121 @@ fn truncates_in_input_unit(granularity: DatePart, tz: Option<&Tz>) -> bool { || (tz.is_none() && granularity.is_fine_granularity_utc()) } +/// Whether truncating to `granularity` in the local time of `tz` never reverses +/// two instants. Computed once per timezone name. +fn local_truncation_preserves_order( + tz_name: &str, + tz: Tz, + granularity: DatePart, +) -> bool { + static CACHE: LazyLock>> = + LazyLock::new(Default::default); + let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner); + let order = match cache.get(tz_name) { + Some(order) => *order, + None => { + let order = LocalTruncationOrder::new(tz); + cache.insert(tz_name.to_owned(), order); + order + } + }; + order.preserves(granularity) +} + +/// Granularities coarser than minute whose local-time truncation keeps the order +/// in one zone. Day and longer buckets outlast any offset change, so only the +/// instants around each transition can go backwards; `hour` needs no transitions. +#[derive(Clone, Copy)] +struct LocalTruncationOrder { + hour: bool, + day: bool, + week: bool, + month: bool, + quarter: bool, + year: bool, +} + +impl LocalTruncationOrder { + fn new(tz: Tz) -> Self { + let Some(transitions) = utc_offset_transitions(&tz) else { + return Self::from_fn(|_| false); + }; + Self::from_fn(|granularity| match granularity { + DatePart::Hour => transitions.is_empty(), + _ => transitions.iter().all(|&transition| { + let at = transition * NANOS_PER_SECOND; + matches!( + ( + date_trunc_coarse(granularity, at - 1, Some(tz)), + date_trunc_coarse(granularity, at, Some(tz)), + ), + (Ok(before), Ok(after)) if before <= after + ) + }), + }) + } + + fn from_fn(preserves: impl Fn(DatePart) -> bool) -> Self { + Self { + hour: preserves(DatePart::Hour), + day: preserves(DatePart::Day), + week: preserves(DatePart::Week), + month: preserves(DatePart::Month), + quarter: preserves(DatePart::Quarter), + year: preserves(DatePart::Year), + } + } + + fn preserves(&self, granularity: DatePart) -> bool { + match granularity { + DatePart::Hour => self.hour, + DatePart::Day => self.day, + DatePart::Week => self.week, + DatePart::Month => self.month, + DatePart::Quarter => self.quarter, + DatePart::Year => self.year, + _ => false, + } + } +} + +/// 1800-01-01 and 2200-01-01 in epoch seconds; chrono-tz has no transitions +/// outside this window. +const TRANSITION_SCAN_START: i64 = -5_364_662_400; +const TRANSITION_SCAN_END: i64 = 7_258_118_400; +const SECONDS_PER_DAY: i64 = 86_400; + +/// The epoch seconds at which the UTC offset of `tz` changes. Daily steps catch +/// every transition, since tz database transitions are days apart. +fn utc_offset_transitions(tz: &Tz) -> Option> { + let offset_at = |seconds: i64| { + let utc = DateTime::from_timestamp(seconds, 0)?.naive_utc(); + Some(tz.offset_from_utc_datetime(&utc).fix().local_minus_utc()) + }; + let mut transitions = vec![]; + let mut day = TRANSITION_SCAN_START; + let mut offset = offset_at(day)?; + while day < TRANSITION_SCAN_END { + let next_day = day + SECONDS_PER_DAY; + let next_offset = offset_at(next_day)?; + if next_offset != offset { + let (mut before, mut after) = (day, next_day); + while after - before > 1 { + let middle = before + (after - before) / 2; + if offset_at(middle)? == offset { + before = middle; + } else { + after = middle; + } + } + transitions.push(after); + } + offset = next_offset; + day = next_day; + } + Some(transitions) +} + /// The length of `granularity` in `tu`, or `None` when `granularity` is no /// coarser than `tu`, so a value in `tu` is already truncated to it. fn fine_granularity_unit(tu: TimeUnit, granularity: DatePart) -> Option { @@ -1361,11 +1484,13 @@ mod tests { use std::sync::Arc; use crate::datetime::date_trunc::{ - DateTruncFunc, NANOS_PER_MICROSECOND, date_trunc_coarse, general_date_trunc, + DateTruncFunc, NANOS_PER_MICROSECOND, SECONDS_PER_DAY, TRANSITION_SCAN_END, + TRANSITION_SCAN_START, date_trunc_coarse, general_date_trunc, general_date_trunc_array_fine_granularity, parse_granularity, }; use arrow::array::cast::as_primitive_array; + use arrow::array::timezone::Tz; use arrow::array::types::{ ArrowTimestampType, TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType, TimestampSecondType, @@ -1384,6 +1509,8 @@ mod tests { use datafusion_expr::sort_properties::{ExprProperties, SortProperties}; use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl}; + use chrono::{DateTime, Offset, TimeZone}; + #[test] fn output_ordering_respects_timestamp_timezone() { let precision_value = ScalarValue::Utf8(Some("hour".into())); @@ -1433,13 +1560,16 @@ mod tests { }; let ordered = SortProperties::Ordered(SortOptions::default()); let function = DateTruncFunc::new(); - let output_ordering = |precision: ExprProperties, unit| { - let data_type = DataType::Timestamp(unit, Some("America/Goose_Bay".into())); + let output_ordering_in = |tz: &str, precision: ExprProperties, unit| { + let data_type = DataType::Timestamp(unit, Some(tz.into())); let timestamp = ExprProperties::new_unknown() .with_order(ordered) .with_range(Interval::make_unbounded(&data_type).unwrap()); function.output_ordering(&[precision, timestamp]).unwrap() }; + let output_ordering = |precision: ExprProperties, unit| { + output_ordering_in("America/Goose_Bay", precision, unit) + }; for unit in [ TimeUnit::Second, @@ -1454,13 +1584,48 @@ mod tests { "{granularity} {unit:?}" ); } - for granularity in ["hour", "day", "week", "month", "quarter", "year"] { + // Goose_Bay fell back from 00:01 to 23:01 the previous day. + for granularity in ["hour", "day"] { assert_eq!( output_ordering(constant(ScalarValue::from(granularity)), unit), SortProperties::Unordered, "{granularity} {unit:?}" ); } + // New York changes its offset at 02:00, away from midnight. + for granularity in ["day", "week", "month", "quarter", "year"] { + assert_eq!( + output_ordering_in( + "America/New_York", + constant(ScalarValue::from(granularity)), + unit + ), + ordered, + "{granularity} {unit:?}" + ); + } + assert_eq!( + output_ordering_in( + "America/New_York", + constant(ScalarValue::from("hour")), + unit + ), + SortProperties::Unordered, + "{unit:?}" + ); + for tz in ["UTC", "+05:30"] { + for granularity in ["hour", "day", "year"] { + assert_eq!( + output_ordering_in( + tz, + constant(ScalarValue::from(granularity)), + unit + ), + ordered, + "{tz} {granularity} {unit:?}" + ); + } + } } for precision in [ @@ -1492,6 +1657,32 @@ mod tests { ); } + #[test] + fn timezone_offsets_are_constant_outside_transition_scan_window() { + const HALF_YEAR: i64 = 183 * SECONDS_PER_DAY; + let offset_at = |tz: &Tz, seconds: i64| { + let utc = DateTime::from_timestamp(seconds, 0).unwrap().naive_utc(); + tz.offset_from_utc_datetime(&utc).fix().local_minus_utc() + }; + for zone in chrono_tz::TZ_VARIANTS { + let tz: Tz = zone.name().parse().unwrap(); + for step in 1..=2_000 { + assert_eq!( + offset_at(&tz, TRANSITION_SCAN_START - step * HALF_YEAR), + offset_at(&tz, TRANSITION_SCAN_START), + "{}", + zone.name() + ); + assert_eq!( + offset_at(&tz, TRANSITION_SCAN_END + step * HALF_YEAR), + offset_at(&tz, TRANSITION_SCAN_END), + "{}", + zone.name() + ); + } + } + } + #[test] fn range_key_locality_analysis_requires_timezone_less_timestamp() { let date_trunc = DateTruncFunc::new(); diff --git a/datafusion/sqllogictest/test_files/datetime/timestamps.slt b/datafusion/sqllogictest/test_files/datetime/timestamps.slt index ec1bdbbe7e9f9..11a20d81dd908 100644 --- a/datafusion/sqllogictest/test_files/datetime/timestamps.slt +++ b/datafusion/sqllogictest/test_files/datetime/timestamps.slt @@ -2013,6 +2013,32 @@ physical_plan 05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true 06)----------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/timestamps/goose_bay_epochs.csv]]}, projection=[c], output_ordering=[c@0 ASC NULLS LAST], file_type=csv, has_header=true +# Day buckets keep the order in zones whose transitions never cross local +# midnight, such as New York, so no sort is needed. +query TT +EXPLAIN SELECT date_trunc('day', from_unixtime(c, 'America/New_York')) AS bucket +FROM goose_bay_epochs +ORDER BY bucket; +---- +physical_plan +01)SortPreservingMergeExec: [bucket@0 ASC NULLS LAST] +02)--ProjectionExec: expr=[date_trunc(day, from_unixtime(c@0, America/New_York)) as bucket] +03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/timestamps/goose_bay_epochs.csv]]}, projection=[c], output_ordering=[c@0 ASC NULLS LAST], file_type=csv, has_header=true + +# Goose_Bay fell back from 00:01 to 23:01 the previous day, so the sort stays. +query TT +EXPLAIN SELECT date_trunc('day', from_unixtime(c, 'America/Goose_Bay')) AS bucket +FROM goose_bay_epochs +ORDER BY bucket; +---- +physical_plan +01)SortPreservingMergeExec: [bucket@0 ASC NULLS LAST] +02)--SortExec: expr=[bucket@0 ASC NULLS LAST], preserve_partitioning=[true] +03)----ProjectionExec: expr=[date_trunc(day, from_unixtime(c@0, America/Goose_Bay)) as bucket] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/timestamps/goose_bay_epochs.csv]]}, projection=[c], output_ordering=[c@0 ASC NULLS LAST], file_type=csv, has_header=true + statement ok DROP TABLE goose_bay_epochs;