You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "theirix (via GitHub)" <gi...@apache.org> on 2026/08/26 22:23:23 UTC
[PR] feat: widen output decimal type for decimal ceil/floor [datafusion]
theirix opened a new pull request, #24703:
URL: https://github.com/apache/datafusion/pull/24703
## Which issue does this PR close?
- Closes #22511
- Closes #20640
## Rationale for this change
In edge cases, an extra decimal point is required to accommodate a result. Currently, ceil/floor just fail with an overflow.
For example, `ceil(-999)` is `-1000`, and it cannot fit into `Decimal(4,1)` with 3 digits, but only into a decimal type with a lower scale and/or different precision (e.g. `Decimal(4,0)`).
The proposed experimental fix is to widen the input decimal type to zero scale.
How it's done in other engines:
1. It matches Spark ceil/floor behaviour (limited support in the Spark UDF), when the scale drops to zero, precision is recalculated via `p-s+1`.
2. DuckDB performs slightly differently, just dropping the scale to zero and keeping precision as input:
`select floor('-999.9'::DECIMAL(4,1));` -> `-1000::DECIMAL(4,0)`
`select ceil(9.9::DECIMAL(2,1));` -> `10::DECIMAL(2,0)`
3. ClickHouse surprisingly keeps the resulting type as is
`SELECT floor(CAST('-999.9', 'DECIMAL(4, 1)'))` -> `-1000::DECIMAL(4,1)`
4. Postgres has its own big integer types, not applicable
From three possible behaviours, we can go with either Spark's or DuckDB's behaviour.
I didn't investigate ClickHouse behaviour yet. Since we already have existing Spark logic in place and it uses precision sparingly, I lean towards it.
## What changes are included in this PR?
- Change output type of floor/ceil to `Decimal(p-s+1, 0)` - could be a breaking change
- Change the logic to match Spark's floor/ceil
- Extend `apply_decimal_op` to specify output scale (could be different from input scale)
- Change preimage logic to consider both argument and literal precision and scale
## Are these changes tested?
- Added examples from two linked issues
- A few more SLTs to cover clamping
## Are there any user-facing changes?
--
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] feat: widen output decimal type for decimal ceil/floor [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #24703:
URL: https://github.com/apache/datafusion/pull/24703#issuecomment-5433469565
ill try find time to take a look at this, but cc @kumarUjjawal i think you worked on something similar for round?
--
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] feat: widen output decimal type for decimal ceil/floor [datafusion]
Posted by "theirix (via GitHub)" <gi...@apache.org>.
theirix commented on PR #24703:
URL: https://github.com/apache/datafusion/pull/24703#issuecomment-5431835199
@neilconway, @Jefffrey I'd appreciate your thoughts on this experimental PR
The mentioned Spark UDF PR is #21933 - that logic could be unified into the core UDF later if we choose the Spark behaviour (1).
--
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] feat: widen output decimal type for decimal ceil/floor [datafusion]
Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan merged PR #24703:
URL: https://github.com/apache/datafusion/pull/24703
--
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] feat: widen output decimal type for decimal ceil/floor [datafusion]
Posted by "theirix (via GitHub)" <gi...@apache.org>.
theirix commented on code in PR #24703:
URL: https://github.com/apache/datafusion/pull/24703#discussion_r3883341589
##########
datafusion/functions/src/math/floor.rs:
##########
@@ -123,10 +133,7 @@ impl ScalarUDFImpl for FloorFunc {
}
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
- match &arg_types[0] {
- DataType::Null => Ok(DataType::Float64),
- other => Ok(other.clone()),
- }
+ Ok(decimal_floor_ceil_return_type(&arg_types[0]))
Review Comment:
Thank you for the review! I've fixed edge cases for the preimage.
Regarding the change - I agree, even if it's a different decimal point type in the decimal domain, it is still a different type. Updated the user-facing changes PR section. If this approach is fine, I'll also add a change to the upgrading notes doc for 56.
--
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] feat: widen output decimal type for decimal ceil/floor [datafusion]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #24703:
URL: https://github.com/apache/datafusion/pull/24703#issuecomment-5431984161
## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/24703?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `89.22156%` with `18 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 81.44%. Comparing base ([`1064661`](https://app.codecov.io/gh/apache/datafusion/commit/1064661e82ba4c8deb0e73f74fb789fa89386ac7?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`4c5029b`](https://app.codecov.io/gh/apache/datafusion/commit/4c5029bde5e39baff78d1735e02d3b23830b8bc3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 19 commits behind head on main.
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/24703?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [datafusion/functions/src/math/decimal.rs](https://app.codecov.io/gh/apache/datafusion/pull/24703?src=pr&el=tree&filepath=datafusion%2Ffunctions%2Fsrc%2Fmath%2Fdecimal.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9mdW5jdGlvbnMvc3JjL21hdGgvZGVjaW1hbC5ycw==) | 77.77% | [9 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24703?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [datafusion/functions/src/math/floor.rs](https://app.codecov.io/gh/apache/datafusion/pull/24703?src=pr&el=tree&filepath=datafusion%2Ffunctions%2Fsrc%2Fmath%2Ffloor.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9mdW5jdGlvbnMvc3JjL21hdGgvZmxvb3IucnM=) | 92.59% | [3 Missing and 5 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24703?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #24703 +/- ##
========================================
Coverage 81.44% 81.44%
========================================
Files 1118 1119 +1
Lines 399602 400525 +923
Branches 399602 400525 +923
========================================
+ Hits 325458 326227 +769
- Misses 55146 55208 +62
- Partials 18998 19090 +92
```
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/24703?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</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] feat: widen output decimal type for decimal ceil/floor [datafusion]
Posted by "theirix (via GitHub)" <gi...@apache.org>.
theirix commented on code in PR #24703:
URL: https://github.com/apache/datafusion/pull/24703#discussion_r3881575651
##########
datafusion/functions/src/math/decimal.rs:
##########
@@ -74,38 +82,66 @@ where
})
}
+/// Compute the return precision for floor/ceil result to accommodate the result
+pub(super) fn decimal_floor_ceil_precision(
Review Comment:
Unfortunately, no. Based on the code, it will provide the same precision as the input one if places = 0. We need to widen it.
--
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] feat: widen output decimal type for decimal ceil/floor [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on code in PR #24703:
URL: https://github.com/apache/datafusion/pull/24703#discussion_r3877781312
##########
datafusion/functions/src/math/floor.rs:
##########
@@ -123,10 +133,7 @@ impl ScalarUDFImpl for FloorFunc {
}
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
- match &arg_types[0] {
- DataType::Null => Ok(DataType::Float64),
- other => Ok(other.clone()),
- }
+ Ok(decimal_floor_ceil_return_type(&arg_types[0]))
Review Comment:
This changes the output type of a public SQL function. Any query that stores `floor(decimal_col)` into a fixed schema, or reads `arrow_typeof`, sees a different type. We should mention in upgrade guide
##########
datafusion/functions/src/math/floor.rs:
##########
@@ -280,17 +307,40 @@ impl ScalarUDFImpl for FloorFunc {
// DECIMAL(precision, scale) where precision ≤ 38 -> Decimal128(precision, scale)
// DECIMAL(precision, scale) where precision > 38 -> Decimal256(precision, scale)
// Decimal32 and Decimal64 are unreachable from SQL/SLT.
- ScalarValue::Decimal32(Some(n), precision, scale) => {
- preimage_bounds!(decimal: Decimal32, Decimal32Type, *n, *precision, *scale)
+ //
+ // Simce floor()/ceil() do not preserve argument's scale, the preimage bounds
+ // must be expressed in `arg`'s own (precision, scale), not the literal's
+ ScalarValue::Decimal32(Some(n), lit_precision, lit_scale) => {
+ let DataType::Decimal32(arg_precision, arg_scale) =
+ info.get_data_type(&arg)?
+ else {
+ return Ok(PreimageResult::None);
+ };
+ preimage_bounds!(decimal: Decimal32, Decimal32Type, *n, *lit_precision, *lit_scale, arg_precision, arg_scale)
}
- ScalarValue::Decimal64(Some(n), precision, scale) => {
- preimage_bounds!(decimal: Decimal64, Decimal64Type, *n, *precision, *scale)
+ ScalarValue::Decimal64(Some(n), lit_precision, lit_scale) => {
+ let DataType::Decimal64(arg_precision, arg_scale) =
+ info.get_data_type(&arg)?
+ else {
+ return Ok(PreimageResult::None);
+ };
+ preimage_bounds!(decimal: Decimal64, Decimal64Type, *n, *lit_precision, *lit_scale, arg_precision, arg_scale)
}
- ScalarValue::Decimal128(Some(n), precision, scale) => {
- preimage_bounds!(decimal: Decimal128, Decimal128Type, *n, *precision, *scale)
+ ScalarValue::Decimal128(Some(n), lit_precision, lit_scale) => {
+ let DataType::Decimal128(arg_precision, arg_scale) =
+ info.get_data_type(&arg)?
Review Comment:
we could match on the `Ok` case and return `PreimageResult::None` otherwise?
##########
datafusion/functions/src/math/floor.rs:
##########
@@ -343,61 +393,90 @@ fn int_preimage_bounds<I: CheckedAdd + One + Copy>(n: I) -> Option<(I, I)> {
Some((n, upper))
}
-/// Compute preimage bounds for floor function on decimal types.
-/// For floor(x) = n, the preimage is [n, n+1).
+/// Compute preimage bounds for floor/ceil functions on decimal types.
+/// Argument and literal have different precision and scales.
+///
+/// For floor(x) = n, the preimage is [n, n+1) in the argument's own scale.
/// Returns None if:
-/// - The value has a fractional part (floor always returns integers)
-/// - Adding 1 would overflow
+/// - The literal has a fractional part at its own scale
+/// - Rescaling to the argument's scale, or adding 1, would overflow
fn decimal_preimage_bounds<D: DecimalType>(
- value: D::Native,
- precision: u8,
- scale: i8,
+ lit_value: D::Native,
+ lit_precision: u8,
+ lit_scale: i8,
+ arg_precision: u8,
+ arg_scale: i8,
) -> Option<(D::Native, D::Native)>
where
D::Native: DecimalCast + ArrowNativeTypeOp + std::ops::Rem<Output = D::Native>,
{
- // Use rescale_decimal to compute "1" at target scale (avoids manual pow)
- // Convert integer 1 (scale=0) to the target scale
+ if lit_scale > 0 {
+ let lit_factor: D::Native =
+ rescale_decimal::<D, D>(D::Native::ONE, 1, 0, lit_precision, lit_scale)?;
+ if lit_value % lit_factor != D::Native::ZERO {
+ // The literal has a fractional part at its own scale
+ return None;
+ }
+ }
+
+ // Rescale the literal's (integer) value into the argument's own scale.
+ let base: D::Native = rescale_decimal::<D, D>(
+ lit_value,
+ lit_precision,
+ lit_scale,
+ arg_precision,
+ arg_scale,
+ )?;
+
+ // Use rescale_decimal to compute "1" at the argument's scale (avoids manual pow)
let one_scaled: D::Native = rescale_decimal::<D, D>(
Review Comment:
this might be already there before the pr but would a guard that returns `None` when `one_scaled` is zero be worth adding?
##########
datafusion/functions/src/math/decimal.rs:
##########
@@ -74,38 +82,66 @@ where
})
}
+/// Compute the return precision for floor/ceil result to accommodate the result
+pub(super) fn decimal_floor_ceil_precision(
Review Comment:
can we reuse `calculate_new_precision_scale` with 0 decimal places?
--
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] feat: widen output decimal type for decimal ceil/floor [datafusion]
Posted by "theirix (via GitHub)" <gi...@apache.org>.
theirix commented on PR #24703:
URL: https://github.com/apache/datafusion/pull/24703#issuecomment-5469153122
> ive skimmed this but makes sense to me; if we're going to enable this behaviour (of changing scale) we might as well go all the way like spark, unlike duckdb which doesnt tighten it as much as spark does
Yes, this makes sense. I'll try to refactor Spark's UDF implementation to reuse more from the core.
> the clickhouse one seems surprising, is that a bug? 😅
It is usually complicated with ClickHouse - the behaviour is documented, but still contradictory. Turns out, all operations on the decimal type are done on a backing type (int32 if precision is 4, as in the example with `Decimal(4,1)`) regardless of precision: "Internally data is represented as normal signed integers with respective bit width. Real value ranges that can be stored in memory are a bit larger than specified above, which are checked only on conversion from a string.". We do perform precision checks for most operations. So if the result fits int32, ClickHouse won't complain.
ClickHouse is [pretty relaxed on overflow checks](https://clickhouse.com/docs/reference/data-types/decimal#overflow-checks) (works only for 32- and 64-bit decimals but not for wider). Also, it is not universal - you can easily construct an overflown decimal even when it's enabled, so there is a function `isDecimalOverflow`, that tells you if you have overflown a calculation.
For example, `-99999999.9999` is the smallest number that can fit into `DECIMAL32(1)` aka `DECIMAL(9,1)`, and `-100000000` cannot fit and cannot be constructed - expected behaviour. However, overflowing a value via `floor` on a valid input silently produces an overflowed value, while `isDecimalOverflow` shows it is bad.
```sql
select version() \G
version(): 26.3.17.4
SET decimal_check_overflow = 1;
SELECT floor(CAST('-99999999.9999', 'DECIMAL32(1)')), toTypeName(floor(CAST('-99999999.9999', 'DECIMAL32(1)')))
-100000000 │ Decimal(9, 1)
select isDecimalOverflow(floor(CAST('-99999999.9999', 'DECIMAL32(1)')));
1
SELECT CAST('-100000000', 'DECIMAL32(1)')
DB::Exception: Decimal value is too big
```
> adding a upgrade notice would be good 👍
Done, thank you!
--
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