alamb commented on code in PR #27883:
URL: https://github.com/apache/datafusion/pull/27883#discussion_r4760061886


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -1262,6 +1273,169 @@ fn truncates_in_input_unit(granularity: DatePart, tz: 
Option<&Tz>) -> bool {
         || (tz.is_none() && granularity.is_fine_granularity_utc())
 }
 
+/// Truncates `array` to a granularity coarser than minute in the local time of
+/// `tz`, with integer arithmetic between the UTC offset transitions of `tz`.
+///
+/// Like [`general_date_trunc`], it returns the instant that has the truncated
+/// local time and the input's UTC offset, when one exists. If the instant
+/// `truncated local time - offset` lies in the input's offset span, it has 
that
+/// local time and offset, so it is the result. Otherwise a transition falls
+/// between the bucket start and the input, and the value takes the chrono 
path.
+/// That result depends only on the offset and the truncated local time, so the
+/// last one is reused, which sorted input hits for the rest of the bucket.
+fn date_trunc_coarse_with_spans<T: ArrowTimestampType>(
+    array: &PrimitiveArray<T>,
+    granularity: DatePart,
+    tz: Tz,
+    spans: &UtcOffsetSpans,
+) -> Result<PrimitiveArray<T>> {
+    let scale = match T::UNIT {
+        Second => NANOS_PER_SECOND,
+        Millisecond => NANOS_PER_MILLISECOND,
+        Microsecond => NANOS_PER_MICROSECOND,
+        Nanosecond => 1,
+    };
+    // Sorted input stays in one span for long runs, so look it up only on a 
change.
+    let span = Cell::new(UtcOffsetSpan::EMPTY);
+    let last_chrono_result = Cell::new(None::<(i32, i64, i64)>);
+    array.try_unary(|value| {
+        let Some(nanos) = value.checked_mul(scale) else {
+            return general_date_trunc(T::UNIT, value, Some(tz), granularity);
+        };
+        let seconds = nanos.div_euclid(NANOS_PER_SECOND);
+        let mut current = span.get();
+        if !current.contains(seconds) {
+            current = spans.span(seconds);
+            span.set(current);
+        }
+        let offset = i64::from(current.offset) * NANOS_PER_SECOND;
+        let Some(local) = nanos
+            .checked_add(offset)
+            .and_then(|local| _date_trunc_coarse_without_tz(granularity, 
local))
+        else {
+            return general_date_trunc(T::UNIT, value, Some(tz), granularity);
+        };
+        if let Some(truncated) = local.checked_sub(offset)
+            && current.start <= truncated.div_euclid(NANOS_PER_SECOND)
+        {
+            // `truncated` is a whole number of seconds, so dividing is exact.
+            return Ok(truncated / scale);
+        }
+        match last_chrono_result.get() {
+            Some((offset, truncated_local, result))
+                if offset == current.offset && truncated_local == local =>
+            {
+                Ok(result)
+            }
+            _ => {
+                let result = general_date_trunc(T::UNIT, value, Some(tz), 
granularity)?;
+                last_chrono_result.set(Some((current.offset, local, result)));
+                Ok(result)
+            }
+        }
+    })
+}
+
+/// The UTC offsets of a timezone over time: `offsets[i]` holds from
+/// `transitions[i - 1]` (inclusive) to `transitions[i]` (exclusive), both in
+/// epoch seconds, with the first and last spans unbounded.
+#[derive(Debug)]
+struct UtcOffsetSpans {
+    transitions: Vec<i64>,
+    offsets: Vec<i32>,
+}
+
+/// The epoch seconds `[start, end)` over which a timezone has `offset`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct UtcOffsetSpan {
+    start: i64,
+    end: i64,
+    offset: i32,
+}
+
+impl UtcOffsetSpan {
+    const EMPTY: Self = Self {
+        start: i64::MAX,
+        end: i64::MIN,
+        offset: 0,
+    };
+
+    fn contains(&self, seconds: i64) -> bool {
+        self.start <= seconds && seconds < self.end
+    }
+}
+
+impl UtcOffsetSpans {
+    /// Finds every UTC offset transition of `tz` between 1800 and 2200 by
+    /// stepping a day at a time and bisecting to the second. Steps of a day 
catch
+    /// every transition, since tz database transitions are days apart.
+    fn new(tz: &Tz) -> Option<Self> {
+        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 offsets = vec![offset_at(TRANSITION_SCAN_START)?];
+        let mut day = TRANSITION_SCAN_START;
+        let mut offset = offsets[0];
+        while day < TRANSITION_SCAN_END {
+            let next_day = day + SECONDS_PER_DAY;
+            if offset_at(next_day)? == offset {
+                day = next_day;
+                continue;
+            }
+            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;
+                }
+            }
+            // Continue from the transition, so a second one in the same day is
+            // found too.
+            offset = offset_at(after)?;
+            transitions.push(after);
+            offsets.push(offset);
+            day = after;
+        }

Review Comment:
   Since these vectors never change,  a `shrink_to_fit` here would save some 
memory (agent says 30% for NYC)
   



##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -1262,6 +1273,169 @@ fn truncates_in_input_unit(granularity: DatePart, tz: 
Option<&Tz>) -> bool {
         || (tz.is_none() && granularity.is_fine_granularity_utc())
 }
 
+/// Truncates `array` to a granularity coarser than minute in the local time of
+/// `tz`, with integer arithmetic between the UTC offset transitions of `tz`.
+///
+/// Like [`general_date_trunc`], it returns the instant that has the truncated
+/// local time and the input's UTC offset, when one exists. If the instant
+/// `truncated local time - offset` lies in the input's offset span, it has 
that
+/// local time and offset, so it is the result. Otherwise a transition falls
+/// between the bucket start and the input, and the value takes the chrono 
path.
+/// That result depends only on the offset and the truncated local time, so the
+/// last one is reused, which sorted input hits for the rest of the bucket.
+fn date_trunc_coarse_with_spans<T: ArrowTimestampType>(
+    array: &PrimitiveArray<T>,
+    granularity: DatePart,
+    tz: Tz,
+    spans: &UtcOffsetSpans,
+) -> Result<PrimitiveArray<T>> {
+    let scale = match T::UNIT {
+        Second => NANOS_PER_SECOND,
+        Millisecond => NANOS_PER_MILLISECOND,
+        Microsecond => NANOS_PER_MICROSECOND,
+        Nanosecond => 1,
+    };
+    // Sorted input stays in one span for long runs, so look it up only on a 
change.
+    let span = Cell::new(UtcOffsetSpan::EMPTY);
+    let last_chrono_result = Cell::new(None::<(i32, i64, i64)>);
+    array.try_unary(|value| {
+        let Some(nanos) = value.checked_mul(scale) else {
+            return general_date_trunc(T::UNIT, value, Some(tz), granularity);
+        };
+        let seconds = nanos.div_euclid(NANOS_PER_SECOND);
+        let mut current = span.get();
+        if !current.contains(seconds) {
+            current = spans.span(seconds);
+            span.set(current);
+        }
+        let offset = i64::from(current.offset) * NANOS_PER_SECOND;
+        let Some(local) = nanos
+            .checked_add(offset)
+            .and_then(|local| _date_trunc_coarse_without_tz(granularity, 
local))
+        else {
+            return general_date_trunc(T::UNIT, value, Some(tz), granularity);
+        };
+        if let Some(truncated) = local.checked_sub(offset)
+            && current.start <= truncated.div_euclid(NANOS_PER_SECOND)
+        {
+            // `truncated` is a whole number of seconds, so dividing is exact.
+            return Ok(truncated / scale);
+        }
+        match last_chrono_result.get() {
+            Some((offset, truncated_local, result))
+                if offset == current.offset && truncated_local == local =>
+            {
+                Ok(result)
+            }
+            _ => {
+                let result = general_date_trunc(T::UNIT, value, Some(tz), 
granularity)?;
+                last_chrono_result.set(Some((current.offset, local, result)));
+                Ok(result)
+            }
+        }
+    })
+}
+
+/// The UTC offsets of a timezone over time: `offsets[i]` holds from
+/// `transitions[i - 1]` (inclusive) to `transitions[i]` (exclusive), both in
+/// epoch seconds, with the first and last spans unbounded.
+#[derive(Debug)]
+struct UtcOffsetSpans {
+    transitions: Vec<i64>,
+    offsets: Vec<i32>,
+}
+
+/// The epoch seconds `[start, end)` over which a timezone has `offset`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct UtcOffsetSpan {
+    start: i64,
+    end: i64,
+    offset: i32,
+}
+
+impl UtcOffsetSpan {
+    const EMPTY: Self = Self {
+        start: i64::MAX,
+        end: i64::MIN,
+        offset: 0,
+    };
+
+    fn contains(&self, seconds: i64) -> bool {
+        self.start <= seconds && seconds < self.end
+    }
+}
+
+impl UtcOffsetSpans {
+    /// Finds every UTC offset transition of `tz` between 1800 and 2200 by
+    /// stepping a day at a time and bisecting to the second. Steps of a day 
catch
+    /// every transition, since tz database transitions are days apart.
+    fn new(tz: &Tz) -> Option<Self> {
+        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 offsets = vec![offset_at(TRANSITION_SCAN_START)?];
+        let mut day = TRANSITION_SCAN_START;
+        let mut offset = offsets[0];
+        while day < TRANSITION_SCAN_END {
+            let next_day = day + SECONDS_PER_DAY;
+            if offset_at(next_day)? == offset {
+                day = next_day;
+                continue;
+            }
+            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;
+                }
+            }
+            // Continue from the transition, so a second one in the same day is
+            // found too.
+            offset = offset_at(after)?;
+            transitions.push(after);
+            offsets.push(offset);
+            day = after;
+        }
+        Some(Self {
+            transitions,
+            offsets,
+        })
+    }
+
+    /// The span that contains `seconds`.
+    fn span(&self, seconds: i64) -> UtcOffsetSpan {
+        let i = self.transitions.partition_point(|&t| t <= seconds);
+        UtcOffsetSpan {
+            start: i.checked_sub(1).map_or(i64::MIN, |i| self.transitions[i]),
+            end: self.transitions.get(i).copied().unwrap_or(i64::MAX),
+            offset: self.offsets[i],
+        }
+    }
+}
+
+/// [`UtcOffsetSpans`] of `tz`, computed once per timezone name.
+fn cached_utc_offset_spans(tz_name: &str, tz: Tz) -> 
Option<Arc<UtcOffsetSpans>> {
+    static CACHE: LazyLock<Mutex<HashMap<String, 
Option<Arc<UtcOffsetSpans>>>>> =

Review Comment:
   I am not sure putting a global variable here is a great idea
   
   That being said, I had my agent measure the size, and it was:
   ```
   
┌──────────────────┬─────────────┬──────────────────────────┬──────────────────────────┬─────────────────┐
   │       Zone       │ Transitions │    transitions (i64)     │      offsets 
(i32)       │ Allocated total │
   
├──────────────────┼─────────────┼──────────────────────────┼──────────────────────────┼─────────────────┤
   │ UTC              │ 0           │ 0 bytes                  │ 4 bytes        
          │ 4 bytes         │
   
├──────────────────┼─────────────┼──────────────────────────┼──────────────────────────┼─────────────────┤
   │ +05:30           │ 0           │ 0 bytes                  │ 4 bytes        
          │ 4 bytes         │
   
├──────────────────┼─────────────┼──────────────────────────┼──────────────────────────┼─────────────────┤
   │ America/New_York │ 359         │ 4,096 bytes (2,872 used) │ 2,048 bytes 
(1,440 used) │ 6,144 bytes     │
   
└──────────────────┴─────────────┴──────────────────────────┴──────────────────────────┴─────────────────┘
   ```
   
   - Largest zone: Africa/Cairo and New York tie at the 6,144-byte maximum.
   - Whole cache: if every one of the 597 zones were cached, the total would be 
about 1.2 MB.
   
   
   
   



##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -1262,6 +1273,169 @@ fn truncates_in_input_unit(granularity: DatePart, tz: 
Option<&Tz>) -> bool {
         || (tz.is_none() && granularity.is_fine_granularity_utc())
 }
 
+/// Truncates `array` to a granularity coarser than minute in the local time of
+/// `tz`, with integer arithmetic between the UTC offset transitions of `tz`.
+///
+/// Like [`general_date_trunc`], it returns the instant that has the truncated
+/// local time and the input's UTC offset, when one exists. If the instant
+/// `truncated local time - offset` lies in the input's offset span, it has 
that
+/// local time and offset, so it is the result. Otherwise a transition falls
+/// between the bucket start and the input, and the value takes the chrono 
path.
+/// That result depends only on the offset and the truncated local time, so the
+/// last one is reused, which sorted input hits for the rest of the bucket.
+fn date_trunc_coarse_with_spans<T: ArrowTimestampType>(
+    array: &PrimitiveArray<T>,
+    granularity: DatePart,
+    tz: Tz,
+    spans: &UtcOffsetSpans,
+) -> Result<PrimitiveArray<T>> {
+    let scale = match T::UNIT {
+        Second => NANOS_PER_SECOND,
+        Millisecond => NANOS_PER_MILLISECOND,
+        Microsecond => NANOS_PER_MICROSECOND,
+        Nanosecond => 1,
+    };
+    // Sorted input stays in one span for long runs, so look it up only on a 
change.
+    let span = Cell::new(UtcOffsetSpan::EMPTY);
+    let last_chrono_result = Cell::new(None::<(i32, i64, i64)>);
+    array.try_unary(|value| {
+        let Some(nanos) = value.checked_mul(scale) else {
+            return general_date_trunc(T::UNIT, value, Some(tz), granularity);
+        };
+        let seconds = nanos.div_euclid(NANOS_PER_SECOND);
+        let mut current = span.get();
+        if !current.contains(seconds) {
+            current = spans.span(seconds);
+            span.set(current);
+        }
+        let offset = i64::from(current.offset) * NANOS_PER_SECOND;
+        let Some(local) = nanos
+            .checked_add(offset)
+            .and_then(|local| _date_trunc_coarse_without_tz(granularity, 
local))
+        else {
+            return general_date_trunc(T::UNIT, value, Some(tz), granularity);
+        };
+        if let Some(truncated) = local.checked_sub(offset)
+            && current.start <= truncated.div_euclid(NANOS_PER_SECOND)
+        {
+            // `truncated` is a whole number of seconds, so dividing is exact.
+            return Ok(truncated / scale);
+        }
+        match last_chrono_result.get() {
+            Some((offset, truncated_local, result))
+                if offset == current.offset && truncated_local == local =>
+            {
+                Ok(result)
+            }
+            _ => {
+                let result = general_date_trunc(T::UNIT, value, Some(tz), 
granularity)?;
+                last_chrono_result.set(Some((current.offset, local, result)));
+                Ok(result)
+            }
+        }
+    })
+}
+
+/// The UTC offsets of a timezone over time: `offsets[i]` holds from
+/// `transitions[i - 1]` (inclusive) to `transitions[i]` (exclusive), both in
+/// epoch seconds, with the first and last spans unbounded.
+#[derive(Debug)]
+struct UtcOffsetSpans {
+    transitions: Vec<i64>,
+    offsets: Vec<i32>,
+}
+
+/// The epoch seconds `[start, end)` over which a timezone has `offset`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct UtcOffsetSpan {
+    start: i64,
+    end: i64,
+    offset: i32,
+}
+
+impl UtcOffsetSpan {
+    const EMPTY: Self = Self {
+        start: i64::MAX,
+        end: i64::MIN,
+        offset: 0,
+    };
+
+    fn contains(&self, seconds: i64) -> bool {
+        self.start <= seconds && seconds < self.end
+    }
+}
+
+impl UtcOffsetSpans {
+    /// Finds every UTC offset transition of `tz` between 1800 and 2200 by
+    /// stepping a day at a time and bisecting to the second. Steps of a day 
catch
+    /// every transition, since tz database transitions are days apart.
+    fn new(tz: &Tz) -> Option<Self> {
+        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 offsets = vec![offset_at(TRANSITION_SCAN_START)?];
+        let mut day = TRANSITION_SCAN_START;
+        let mut offset = offsets[0];
+        while day < TRANSITION_SCAN_END {
+            let next_day = day + SECONDS_PER_DAY;
+            if offset_at(next_day)? == offset {
+                day = next_day;
+                continue;
+            }
+            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;
+                }
+            }
+            // Continue from the transition, so a second one in the same day is
+            // found too.
+            offset = offset_at(after)?;
+            transitions.push(after);
+            offsets.push(offset);
+            day = after;
+        }
+        Some(Self {
+            transitions,
+            offsets,
+        })
+    }
+
+    /// The span that contains `seconds`.
+    fn span(&self, seconds: i64) -> UtcOffsetSpan {
+        let i = self.transitions.partition_point(|&t| t <= seconds);
+        UtcOffsetSpan {
+            start: i.checked_sub(1).map_or(i64::MIN, |i| self.transitions[i]),
+            end: self.transitions.get(i).copied().unwrap_or(i64::MAX),
+            offset: self.offsets[i],
+        }
+    }
+}
+
+/// [`UtcOffsetSpans`] of `tz`, computed once per timezone name.
+fn cached_utc_offset_spans(tz_name: &str, tz: Tz) -> 
Option<Arc<UtcOffsetSpans>> {

Review Comment:
   Another idea from the 🤖 during testing would be to special case UTC and 
fixed offset timezones (e.g. `+8:00` as now they have to go through this code 
to discover they have no transistions



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to