You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "mhilton (via GitHub)" <gi...@apache.org> on 2025/10/29 15:51:13 UTC

[PR] fix: correct date_trunc for times before the epoch [datafusion]

mhilton opened a new pull request, #18356:
URL: https://github.com/apache/datafusion/pull/18356

   ## Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   - Closes #18334.
   
   ## Rationale for this change
   
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   ## What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   The array-based implementation of date_trunc can produce incorrect results for negative timestamps (i.e. dates before 1970-01-01). Check for any such incorrect values and compensate accordingly.
   
   Running the date_trunc benchmark suggests this fix introduces an ~9% performance cost.
   
   ```
   date_trunc_minute_1000  time:   [1.7424 µs 1.7495 µs 1.7583 µs]
                           change: [+7.9289% +8.5950% +9.1955%] (p = 0.00 < 0.05)
                           Performance has regressed.
   Found 4 outliers among 100 measurements (4.00%)
     1 (1.00%) low mild
     1 (1.00%) high mild
     2 (2.00%) high severe
   ```
   
   ## Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   Yes, an SLT is added based on the issue.
   
   ## Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3466608728

   🤖 `./gh_compare_branch_bench.sh` [Benchmark Script](https://github.com/alamb/datafusion-benchmarking/blob/main/gh_compare_branch_bench.sh) Running
   Linux aal-dev 6.14.0-1017-gcp #18~24.04.1-Ubuntu SMP Tue Sep 23 17:51:44 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing issue-18334 (f70abf14f80414687087f3753290328d9b667c59) to 6cc73fa24d0d4d4006375e3bc20d6c267fc55c44 [diff](https://github.com/apache/datafusion/compare/6cc73fa24d0d4d4006375e3bc20d6c267fc55c44..f70abf14f80414687087f3753290328d9b667c59)
   BENCH_NAME=date_trunc
   BENCH_COMMAND=cargo bench --bench date_trunc
   BENCH_FILTER=
   BENCH_BRANCH_NAME=issue-18334
   Results will be posted here when complete
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "waynexia (via GitHub)" <gi...@apache.org>.
waynexia commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2477652217


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -456,37 +457,40 @@ fn general_date_trunc_array_fine_granularity<T: ArrowTimestampType>(
     granularity: &str,
 ) -> Result<ArrayRef> {
     let unit = match (tu, granularity) {
-        (Second, "minute") => Some(Int64Array::new_scalar(60)),
-        (Second, "hour") => Some(Int64Array::new_scalar(3600)),
-        (Second, "day") => Some(Int64Array::new_scalar(86400)),
-
-        (Millisecond, "second") => Some(Int64Array::new_scalar(1_000)),
-        (Millisecond, "minute") => Some(Int64Array::new_scalar(60_000)),
-        (Millisecond, "hour") => Some(Int64Array::new_scalar(3_600_000)),
-        (Millisecond, "day") => Some(Int64Array::new_scalar(86_400_000)),
-
-        (Microsecond, "millisecond") => Some(Int64Array::new_scalar(1_000)),
-        (Microsecond, "second") => Some(Int64Array::new_scalar(1_000_000)),
-        (Microsecond, "minute") => Some(Int64Array::new_scalar(60_000_000)),
-        (Microsecond, "hour") => Some(Int64Array::new_scalar(3_600_000_000)),
-        (Microsecond, "day") => Some(Int64Array::new_scalar(86_400_000_000)),
-
-        (Nanosecond, "microsecond") => Some(Int64Array::new_scalar(1_000)),
-        (Nanosecond, "millisecond") => Some(Int64Array::new_scalar(1_000_000)),
-        (Nanosecond, "second") => Some(Int64Array::new_scalar(1_000_000_000)),
-        (Nanosecond, "minute") => Some(Int64Array::new_scalar(60_000_000_000)),
-        (Nanosecond, "hour") => Some(Int64Array::new_scalar(3_600_000_000_000)),
-        (Nanosecond, "day") => Some(Int64Array::new_scalar(86_400_000_000_000)),
+        (Second, "minute") => NonZeroI64::new(60),
+        (Second, "hour") => NonZeroI64::new(3600),
+        (Second, "day") => NonZeroI64::new(86400),
+
+        (Millisecond, "second") => NonZeroI64::new(1_000),
+        (Millisecond, "minute") => NonZeroI64::new(60_000),
+        (Millisecond, "hour") => NonZeroI64::new(3_600_000),
+        (Millisecond, "day") => NonZeroI64::new(86_400_000),
+
+        (Microsecond, "millisecond") => NonZeroI64::new(1_000),
+        (Microsecond, "second") => NonZeroI64::new(1_000_000),
+        (Microsecond, "minute") => NonZeroI64::new(60_000_000),
+        (Microsecond, "hour") => NonZeroI64::new(3_600_000_000),
+        (Microsecond, "day") => NonZeroI64::new(86_400_000_000),
+
+        (Nanosecond, "microsecond") => NonZeroI64::new(1_000),
+        (Nanosecond, "millisecond") => NonZeroI64::new(1_000_000),
+        (Nanosecond, "second") => NonZeroI64::new(1_000_000_000),
+        (Nanosecond, "minute") => NonZeroI64::new(60_000_000_000),
+        (Nanosecond, "hour") => NonZeroI64::new(3_600_000_000_000),
+        (Nanosecond, "day") => NonZeroI64::new(86_400_000_000_000),
         _ => None,
     };
 
     if let Some(unit) = unit {
-        let original_type = array.data_type();
-        let array = arrow::compute::cast(array, &DataType::Int64)?;
-        let array = arrow::compute::kernels::numeric::div(&array, &unit)?;
-        let array = arrow::compute::kernels::numeric::mul(&array, &unit)?;
-        let array = arrow::compute::cast(&array, original_type)?;
-        Ok(array)
+        let unit = unit.get();
+        let array = PrimitiveArray::<T>::from_iter_values_with_nulls(
+            array
+                .values()
+                .iter()
+                .map(|v| *v - i64::rem_euclid(*v, unit)),

Review Comment:
   Interesting. Another example for LLVM understand SIMD better than developers 🙂‍↕️



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #18356:
URL: https://github.com/apache/datafusion/pull/18356


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3463121029

   I have also created a PR to try and get the performance back
   - https://github.com/apache/datafusion/pull/18360


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3467528518

   🤖 `./gh_compare_branch_bench.sh` [Benchmark Script](https://github.com/alamb/datafusion-benchmarking/blob/main/gh_compare_branch_bench.sh) Running
   Linux aal-dev 6.14.0-1017-gcp #18~24.04.1-Ubuntu SMP Tue Sep 23 17:51:44 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing issue-18334 (587856d282c6e5fadc1cbffc16577c5ec2c357a4) to 6cc73fa24d0d4d4006375e3bc20d6c267fc55c44 [diff](https://github.com/apache/datafusion/compare/6cc73fa24d0d4d4006375e3bc20d6c267fc55c44..587856d282c6e5fadc1cbffc16577c5ec2c357a4)
   BENCH_NAME=date_trunc
   BENCH_COMMAND=cargo bench --bench date_trunc
   BENCH_FILTER=
   BENCH_BRANCH_NAME=issue-18334
   Results will be posted here when complete
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3467549196

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   group                     issue-18334                            main
   -----                     -----------                            ----
   date_trunc_minute_1000    1.00      2.9±0.01µs        ? ?/sec    1.66      4.8±0.01µs        ? ?/sec
   ```
   
   
   </p>
   </details>
   
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3462644534

   @mhilton  notes this is very similar to the fix in 
   - https://github.com/apache/datafusion/pull/13204


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "findepi (via GitHub)" <gi...@apache.org>.
findepi commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2475328906


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -482,9 +482,20 @@ fn general_date_trunc_array_fine_granularity<T: ArrowTimestampType>(
 
     if let Some(unit) = unit {
         let original_type = array.data_type();
-        let array = arrow::compute::cast(array, &DataType::Int64)?;
-        let array = arrow::compute::kernels::numeric::div(&array, &unit)?;
+        let input = arrow::compute::cast(array, &DataType::Int64)?;
+        let array = arrow::compute::kernels::numeric::div(&input, &unit)?;
         let array = arrow::compute::kernels::numeric::mul(&array, &unit)?;
+        // For timestamps before 1970-01-01T00:00:00Z (negative values)
+        // it is possible that the truncated value is actually later
+        // than the original value. Correct any such cases by
+        // subtracting `unit`.
+        let too_late = arrow::compute::kernels::cmp::gt(&array, &input)?;
+        let array = if too_late.true_count() > 0 {
+            let earlier = arrow::compute::kernels::numeric::sub(&array, &unit)?;
+            arrow::compute::kernels::zip::zip(&too_late, &earlier, &array)?
+        } else {
+            array
+        };

Review Comment:
   in scalar terms, what we're computing it
   
   ```
   value - (value floor mod unit)
   ```
   
   can we maybe express this logic directly?
   



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3467312015

   > Running a totally unscientific benchmark on my laptop suggests that the newer version based on review suggestions is significantly faster than main.
   
   Sweet! I have queued up a benchmark to test


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2477489831


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -456,37 +457,40 @@ fn general_date_trunc_array_fine_granularity<T: ArrowTimestampType>(
     granularity: &str,
 ) -> Result<ArrayRef> {
     let unit = match (tu, granularity) {
-        (Second, "minute") => Some(Int64Array::new_scalar(60)),
-        (Second, "hour") => Some(Int64Array::new_scalar(3600)),
-        (Second, "day") => Some(Int64Array::new_scalar(86400)),
-
-        (Millisecond, "second") => Some(Int64Array::new_scalar(1_000)),
-        (Millisecond, "minute") => Some(Int64Array::new_scalar(60_000)),
-        (Millisecond, "hour") => Some(Int64Array::new_scalar(3_600_000)),
-        (Millisecond, "day") => Some(Int64Array::new_scalar(86_400_000)),
-
-        (Microsecond, "millisecond") => Some(Int64Array::new_scalar(1_000)),
-        (Microsecond, "second") => Some(Int64Array::new_scalar(1_000_000)),
-        (Microsecond, "minute") => Some(Int64Array::new_scalar(60_000_000)),
-        (Microsecond, "hour") => Some(Int64Array::new_scalar(3_600_000_000)),
-        (Microsecond, "day") => Some(Int64Array::new_scalar(86_400_000_000)),
-
-        (Nanosecond, "microsecond") => Some(Int64Array::new_scalar(1_000)),
-        (Nanosecond, "millisecond") => Some(Int64Array::new_scalar(1_000_000)),
-        (Nanosecond, "second") => Some(Int64Array::new_scalar(1_000_000_000)),
-        (Nanosecond, "minute") => Some(Int64Array::new_scalar(60_000_000_000)),
-        (Nanosecond, "hour") => Some(Int64Array::new_scalar(3_600_000_000_000)),
-        (Nanosecond, "day") => Some(Int64Array::new_scalar(86_400_000_000_000)),
+        (Second, "minute") => NonZeroI64::new(60),
+        (Second, "hour") => NonZeroI64::new(3600),
+        (Second, "day") => NonZeroI64::new(86400),
+
+        (Millisecond, "second") => NonZeroI64::new(1_000),
+        (Millisecond, "minute") => NonZeroI64::new(60_000),
+        (Millisecond, "hour") => NonZeroI64::new(3_600_000),
+        (Millisecond, "day") => NonZeroI64::new(86_400_000),
+
+        (Microsecond, "millisecond") => NonZeroI64::new(1_000),
+        (Microsecond, "second") => NonZeroI64::new(1_000_000),
+        (Microsecond, "minute") => NonZeroI64::new(60_000_000),
+        (Microsecond, "hour") => NonZeroI64::new(3_600_000_000),
+        (Microsecond, "day") => NonZeroI64::new(86_400_000_000),
+
+        (Nanosecond, "microsecond") => NonZeroI64::new(1_000),
+        (Nanosecond, "millisecond") => NonZeroI64::new(1_000_000),
+        (Nanosecond, "second") => NonZeroI64::new(1_000_000_000),
+        (Nanosecond, "minute") => NonZeroI64::new(60_000_000_000),
+        (Nanosecond, "hour") => NonZeroI64::new(3_600_000_000_000),
+        (Nanosecond, "day") => NonZeroI64::new(86_400_000_000_000),
         _ => None,
     };
 
     if let Some(unit) = unit {
-        let original_type = array.data_type();
-        let array = arrow::compute::cast(array, &DataType::Int64)?;
-        let array = arrow::compute::kernels::numeric::div(&array, &unit)?;
-        let array = arrow::compute::kernels::numeric::mul(&array, &unit)?;
-        let array = arrow::compute::cast(&array, original_type)?;
-        Ok(array)
+        let unit = unit.get();
+        let array = PrimitiveArray::<T>::from_iter_values_with_nulls(
+            array
+                .values()
+                .iter()
+                .map(|v| *v - i64::rem_euclid(*v, unit)),

Review Comment:
   this is pretty fancy



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "sadboy (via GitHub)" <gi...@apache.org>.
sadboy commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2476027904


##########
datafusion/sqllogictest/test_files/timestamps.slt:
##########
@@ -1687,6 +1687,13 @@ SELECT DATE_TRUNC('second', '2022-08-03 14:38:50Z');
 ----
 2022-08-03T14:38:50
 
+# DATE_TRUNC handling of times before the unix epoch (issue 18334)
+query PPP
+SELECT d, DATE_TRUNC('hour', d), DATE_TRUNC('hour', TIMESTAMP '1900-06-15 07:09:00')
+FROM (VALUES (TIMESTAMP '1900-06-15 07:09:00')) AS t(d);

Review Comment:
   Let's test the whole lot:
   ```suggestion
   select d as datetime,
          DATE_TRUNC('year', d) as year,
          DATE_TRUNC('quarter', d) as quarter,
          DATE_TRUNC('month', d) as month,
          DATE_TRUNC('week', d) as week,
          DATE_TRUNC('day', d) as day,
          DATE_TRUNC('hour', d) as hour,
          DATE_TRUNC('minute', d) as minute,
          DATE_TRUNC('second', d) as second
          DATE_TRUNC('microsecond', d) as microsecond
          DATE_TRUNC('millisecond', d) as millisecond
   from (values (timestamp '1900-06-15 07:31:23'),
                (timestamp '1970-01-01 00:00:00'),
                (timestamp '2024-12-31 23:39:01')) as T(d)
   ```



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "sadboy (via GitHub)" <gi...@apache.org>.
sadboy commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2476027904


##########
datafusion/sqllogictest/test_files/timestamps.slt:
##########
@@ -1687,6 +1687,13 @@ SELECT DATE_TRUNC('second', '2022-08-03 14:38:50Z');
 ----
 2022-08-03T14:38:50
 
+# DATE_TRUNC handling of times before the unix epoch (issue 18334)
+query PPP
+SELECT d, DATE_TRUNC('hour', d), DATE_TRUNC('hour', TIMESTAMP '1900-06-15 07:09:00')
+FROM (VALUES (TIMESTAMP '1900-06-15 07:09:00')) AS t(d);

Review Comment:
   Let's test the whole lot:
   ```suggestion
   select d as datetime,
          DATE_TRUNC('year', d) as year,
          DATE_TRUNC('quarter', d) as quarter,
          DATE_TRUNC('month', d) as month,
          DATE_TRUNC('week', d) as week,
          DATE_TRUNC('day', d) as day,
          DATE_TRUNC('hour', d) as hour,
          DATE_TRUNC('minute', d) as minute,
          DATE_TRUNC('second', d) as second
          DATE_TRUNC('microsecond', d) as microsecond
          DATE_TRUNC('millisecond', d) as millisecond
   from (values (timestamp '1900-06-15 07:31:23'),
                (timestamp '1970-07-14 03:10:59'),
                (timestamp '2024-12-31 23:39:01')) as T(d)
   ```



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3466625673

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   group                     issue-18334                            main
   -----                     -----------                            ----
   date_trunc_minute_1000    1.20      5.8±0.02µs        ? ?/sec    1.00      4.8±0.01µs        ? ?/sec
   ```
   
   
   </p>
   </details>
   
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "findepi (via GitHub)" <gi...@apache.org>.
findepi commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2475543904


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -482,9 +482,20 @@ fn general_date_trunc_array_fine_granularity<T: ArrowTimestampType>(
 
     if let Some(unit) = unit {
         let original_type = array.data_type();
-        let array = arrow::compute::cast(array, &DataType::Int64)?;
-        let array = arrow::compute::kernels::numeric::div(&array, &unit)?;
+        let input = arrow::compute::cast(array, &DataType::Int64)?;
+        let array = arrow::compute::kernels::numeric::div(&input, &unit)?;
         let array = arrow::compute::kernels::numeric::mul(&array, &unit)?;
+        // For timestamps before 1970-01-01T00:00:00Z (negative values)
+        // it is possible that the truncated value is actually later
+        // than the original value. Correct any such cases by
+        // subtracting `unit`.
+        let too_late = arrow::compute::kernels::cmp::gt(&array, &input)?;
+        let array = if too_late.true_count() > 0 {
+            let earlier = arrow::compute::kernels::numeric::sub(&array, &unit)?;
+            arrow::compute::kernels::zip::zip(&too_late, &earlier, &array)?
+        } else {
+            array
+        };

Review Comment:
   #18360 turns `unit` into a primitive, which really helps write the logic `value - (value floor mod unit)`. it can become a one-step vectorized operation. that's the part of that PR we should copy over here.
   
   #18360 goes further with `try_unary_mut_or_clone`. that's the part orthogonal to semantic fix and can be a follow-up



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2475359272


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -482,9 +482,20 @@ fn general_date_trunc_array_fine_granularity<T: ArrowTimestampType>(
 
     if let Some(unit) = unit {
         let original_type = array.data_type();
-        let array = arrow::compute::cast(array, &DataType::Int64)?;
-        let array = arrow::compute::kernels::numeric::div(&array, &unit)?;
+        let input = arrow::compute::cast(array, &DataType::Int64)?;
+        let array = arrow::compute::kernels::numeric::div(&input, &unit)?;
         let array = arrow::compute::kernels::numeric::mul(&array, &unit)?;
+        // For timestamps before 1970-01-01T00:00:00Z (negative values)
+        // it is possible that the truncated value is actually later
+        // than the original value. Correct any such cases by
+        // subtracting `unit`.
+        let too_late = arrow::compute::kernels::cmp::gt(&array, &input)?;
+        let array = if too_late.true_count() > 0 {
+            let earlier = arrow::compute::kernels::numeric::sub(&array, &unit)?;
+            arrow::compute::kernels::zip::zip(&too_late, &earlier, &array)?
+        } else {
+            array
+        };

Review Comment:
   > can we maybe express this logic directly
   
   That is an excellent point -- I think we could use the code in https://github.com/apache/datafusion/pull/18360 to do so directly



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "mhilton (via GitHub)" <gi...@apache.org>.
mhilton commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3467296676

   Running a totally unscientific benchmark on my laptop suggests that the newer version based on review suggestions is significantly faster than main.
   
   ```
   date_trunc_minute_1000  time:   [643.37 ns 644.49 ns 645.64 ns]
                           change: [-59.158% -59.017% -58.870%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 3 outliers among 100 measurements (3.00%)
     1 (1.00%) high mild
     2 (2.00%) high severe
   ```


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3462648577

   > Running the date_trunc benchmark suggests this fix introduces an ~9% performance cost.
   
   I think we need to have correctness before performance. I'll run the benchmarks on this PR to be sure


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "findepi (via GitHub)" <gi...@apache.org>.
findepi commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2475339512


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -482,9 +482,20 @@ fn general_date_trunc_array_fine_granularity<T: ArrowTimestampType>(
 
     if let Some(unit) = unit {
         let original_type = array.data_type();
-        let array = arrow::compute::cast(array, &DataType::Int64)?;
-        let array = arrow::compute::kernels::numeric::div(&array, &unit)?;
+        let input = arrow::compute::cast(array, &DataType::Int64)?;
+        let array = arrow::compute::kernels::numeric::div(&input, &unit)?;
         let array = arrow::compute::kernels::numeric::mul(&array, &unit)?;
+        // For timestamps before 1970-01-01T00:00:00Z (negative values)
+        // it is possible that the truncated value is actually later
+        // than the original value. Correct any such cases by
+        // subtracting `unit`.
+        let too_late = arrow::compute::kernels::cmp::gt(&array, &input)?;
+        let array = if too_late.true_count() > 0 {
+            let earlier = arrow::compute::kernels::numeric::sub(&array, &unit)?;
+            arrow::compute::kernels::zip::zip(&too_late, &earlier, &array)?
+        } else {
+            array
+        };

Review Comment:
   in rust terms "floor mod" is probably `rem_euclid`
   
   https://doc.rust-lang.org/std/primitive.i64.html#method.rem_euclid



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3467952023

   Fixing bug and making it 60% faster. Great team effort. Thank you @mhilton @findepi @waynexia 


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2477517973


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -482,9 +482,20 @@ fn general_date_trunc_array_fine_granularity<T: ArrowTimestampType>(
 
     if let Some(unit) = unit {
         let original_type = array.data_type();
-        let array = arrow::compute::cast(array, &DataType::Int64)?;
-        let array = arrow::compute::kernels::numeric::div(&array, &unit)?;
+        let input = arrow::compute::cast(array, &DataType::Int64)?;
+        let array = arrow::compute::kernels::numeric::div(&input, &unit)?;
         let array = arrow::compute::kernels::numeric::mul(&array, &unit)?;
+        // For timestamps before 1970-01-01T00:00:00Z (negative values)
+        // it is possible that the truncated value is actually later
+        // than the original value. Correct any such cases by
+        // subtracting `unit`.
+        let too_late = arrow::compute::kernels::cmp::gt(&array, &input)?;
+        let array = if too_late.true_count() > 0 {
+            let earlier = arrow::compute::kernels::numeric::sub(&array, &unit)?;
+            arrow::compute::kernels::zip::zip(&too_late, &earlier, &array)?
+        } else {
+            array
+        };

Review Comment:
   > https://github.com/apache/datafusion/pull/18360 goes further with try_unary_mut_or_clone. that's the part orthogonal to semantic fix and can be a follow-up 
   
   Agreed -- I will work on that as a follow up



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "findepi (via GitHub)" <gi...@apache.org>.
findepi commented on code in PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#discussion_r2475411205


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -482,9 +482,20 @@ fn general_date_trunc_array_fine_granularity<T: ArrowTimestampType>(
 
     if let Some(unit) = unit {
         let original_type = array.data_type();
-        let array = arrow::compute::cast(array, &DataType::Int64)?;
-        let array = arrow::compute::kernels::numeric::div(&array, &unit)?;
+        let input = arrow::compute::cast(array, &DataType::Int64)?;
+        let array = arrow::compute::kernels::numeric::div(&input, &unit)?;
         let array = arrow::compute::kernels::numeric::mul(&array, &unit)?;
+        // For timestamps before 1970-01-01T00:00:00Z (negative values)
+        // it is possible that the truncated value is actually later
+        // than the original value. Correct any such cases by
+        // subtracting `unit`.
+        let too_late = arrow::compute::kernels::cmp::gt(&array, &input)?;
+        let array = if too_late.true_count() > 0 {
+            let earlier = arrow::compute::kernels::numeric::sub(&array, &unit)?;
+            arrow::compute::kernels::zip::zip(&too_late, &earlier, &array)?
+        } else {
+            array
+        };

Review Comment:
   https://github.com/apache/datafusion/pull/18360 looks more complicated to me.
   We can fix semantics fix without that, or with that. Either way works.
   



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct date_trunc for times before the epoch [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18356:
URL: https://github.com/apache/datafusion/pull/18356#issuecomment-3463119308

   cc @waynexia @sadboy 


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org