Repository navigation
fix: keep room for an integer's digits when it is wider than the decimal's variant - #27474
cool9850311 wants to merge 3 commits into
Conversation
|
Heads up: |
jayzhan211
left a comment
There was a problem hiding this comment.
@cool9850311 thanks for fixing both issues. The wrong rows from #27424 are gone in every place I tried (filter, join key, IN, CASE, COALESCE, UNION ALL, window, aggregate, dictionary input). One change is needed before merge, on the Decimal256 widening (inline).
Could the user-facing section also say that results change type for Decimal128 columns that already worked? COALESCE(d, 0), CASE and UNION ALL of a DECIMAL(38, 20) column with an integer now return Decimal256(40, 20) instead of Decimal128(38, 20), so a CREATE TABLE AS or a client reading the schema sees the new type. It happens for any scale of 19 or more against an Int64, which every integer literal is.
| integer_scale, | ||
| ); | ||
| let common_scale = scale.max(integer_scale); | ||
| if let Some(variant) = narrowest_decimal_variant(decimal_type, common_precision) { |
There was a problem hiding this comment.
A DECIMAL(p, s) column with s >= 19 compared with an integer literal now goes through Decimal256, and the cast stays on the column: WHERE d <> 5 on a DECIMAL(38, 24) column runs CAST(d AS Decimal256(44, 24)) != 5.0…, and its FilterExec takes 80–99 ms on 40M rows against 17–20 ms on main, where the plan is d != 5.0…. The literal fits the column's own type, so letting unwrap-cast accept a Decimal256 literal brings back the old plan and time (17–19 ms), while integer columns still get the wider type. With this change the expr-common and optimizer unit tests and the full sqllogictest suite pass:
--- a/datafusion/expr-common/src/casts.rs
+++ b/datafusion/expr-common/src/casts.rs
@@ fn is_decimal_type(dt: &DataType) -> bool {
matches!(
dt,
- DataType::Decimal128(_, _)
+ DataType::Decimal256(_, _)
+ | DataType::Decimal128(_, _)
| DataType::Decimal64(_, _)
| DataType::Decimal32(_, _)
)
@@ fn decimal_precision_scale(dt: &DataType) -> (u8, i8) {
match dt {
- DataType::Decimal128(p, s)
+ DataType::Decimal256(p, s)
+ | DataType::Decimal128(p, s)
| DataType::Decimal64(p, s)
| DataType::Decimal32(p, s) => (*p, *s),
@@ fn is_supported_numeric_type(data_type: &DataType) -> bool {
| DataType::Decimal128(_, _)
+ | DataType::Decimal256(_, _)
| DataType::Timestamp(_, _)
@@ fn try_cast_numeric_literal(
+ ScalarValue::Decimal256(Some(v), _, scale) => {
+ let v = v.to_i128()?;
+ let lit_scale_mul = 10_i128.checked_pow(u32::try_from(*scale).ok()?)?;
+ if mul >= lit_scale_mul {
+ v.checked_mul(mul / lit_scale_mul)
+ } else if v % (lit_scale_mul / mul) == 0 {
+ Some(v / (lit_scale_mul / mul))
+ } else {
+ None
+ }
+ }
ScalarValue::Decimal128(Some(v), _, scale) => {Unit test for casts.rs, and the queries behind the numbers
#[test]
fn test_cast_predicate_preimage_decimal256_literal() {
use arrow::datatypes::i256;
// `DECIMAL(38, 20) > 5` coerces both sides to `Decimal256(40, 20)`
let five = 5 * 10_i128.pow(20);
assert_preimage_exact(
&DataType::Decimal128(38, 20),
&DataType::Decimal256(40, 20),
Operator::Gt,
&ScalarValue::Decimal256(Some(i256::from_i128(five)), 40, 20),
ScalarValue::Decimal128(Some(five), 38, 20),
);
// 5 has no room in `Decimal128(38, 38)`, so the cast stays
let five = i256::from_i128(5).wrapping_mul(i256::from_i128(10).wrapping_pow(38));
assert_preimage_none(
&DataType::Decimal128(38, 38),
&DataType::Decimal256(58, 38),
Operator::Lt,
&ScalarValue::Decimal256(Some(five), 58, 38),
);
// 10^70 does not fit in i128, so the cast stays instead of overflowing
assert_preimage_none(
&DataType::Decimal128(38, 20),
&DataType::Decimal256(76, 70),
Operator::Gt,
&ScalarValue::Decimal256(Some(i256::ZERO), 76, 70),
);
}-- release-nonlto datafusion-cli
SET datafusion.execution.parquet.max_row_group_size = 1000000;
COPY (SELECT CAST(value AS DECIMAL(38, 20)) / 1000 AS d FROM generate_series(1, 10000000) ORDER BY value)
TO 'wide.parquet' STORED AS PARQUET;
SET datafusion.execution.target_partitions = 1;
CREATE EXTERNAL TABLE w STORED AS PARQUET LOCATION 'wide.parquet';
CREATE TABLE m AS SELECT d FROM w UNION ALL SELECT d FROM w UNION ALL SELECT d FROM w UNION ALL SELECT d FROM w;
EXPLAIN ANALYZE SELECT count(*) FROM m WHERE d <> 5; -- FilterExec 80-99 ms
EXPLAIN ANALYZE SELECT count(*) FROM m WHERE d <> CAST(5 AS DECIMAL(38, 24)); -- 17-20 ms, main's planThere was a problem hiding this comment.
Thank you -- this reproduces here, and your diff is the right place for it. My numbers, on
10M rows of DECIMAL(38, 24) unioned four times (40M), target_partitions = 1,
release-nonlto, with the same binary for both rows so the plan is the only difference:
| query | plan | FilterExec elapsed_compute |
|---|---|---|
d <> 5 |
CAST(d@0 AS Decimal256(44, 24)) != 5.0… |
112.95 ms |
d <> CAST(5 AS DECIMAL(38,24)) |
d@0 != 5.0… |
31.89 ms |
On the pushed commit d <> 5 plans as d@0 != 5.0… and takes 24-27 ms, against 23-25 ms
for that same plan on the base.
An IN list is the same rewrite and comes back with it: d IN (4, 5) kept the cast as
CAST(d@0 AS Decimal256(44, 24)) IN (SET) (…) and is an unwrapped OR chain again.
I took the diff as is, with one addition: the comment above the Decimal256 rejection in
test_decimal_scale_up_preimages said the scale-only rule rejects Decimal256, which
after this holds only for a Decimal256 target, so it says that.
Nothing pinned this, so your three cases are now
test_cast_predicate_preimage_decimal256_literal, plus a value beyond i128 for the
to_i128 guard and the integer side of the same comparison, which is a different arm of
the target match. simplify_expr.slt gets a decimal(38, 24) column in its
decimal-unwrap table whose <> 5 and IN (4, 5) plans must carry no cast. Without the
casts.rs change the unit test fails alone (1 of 251) and both explains fail with the
Decimal256 cast in the plan.
This is the second commit, 8d4db4cac, so the change since your review is those three
files. The branch is rebased onto main, so it also sits on top of #27148, which landed in
casts.rs meanwhile.
There was a problem hiding this comment.
Thanks for catching, done fix.
…mal's variant An integer compared with or added to a `Decimal32` or `Decimal64` value returned wrong rows rather than an error: a `Decimal32(9, 2)` holding `5.50` compared equal to `5`, and `5.50 + 1` returned `6` as an `Int64`. The helper that turned an integer into a decimal was bound to a single variant and had no arm for an integer too wide for it -- `Int32` or wider for `Decimal32`, `Int64` for `Decimal64` -- so both callers read that `None` as "not a decimal case" and fell through to the integer rules, which coerce the decimal to an integer and drop its fraction. How many digits an integer needs is known exactly, so its precision and scale are now computed independently of any variant, and the common type is the narrowest variant that holds them and is no narrower than the decimal's own. The same rule covers the case where the required precision passed the variant's maximum and was capped while the scale was kept, leaving a type with no room for the integer's digits at all (apache#27095, for which apache#27124 proposes a narrower fix). Where no variant holds the required precision, the capped type stands. A float keeps its previous behaviour. The scale it coerces to is an approximation of its own, and widening on that basis would move ordinary comparisons like `WHERE price = 4.00` onto a wider variant. Everything that asks for a common type follows: an `IN` list, `greatest`/`least`, a `UNION ALL`, an ASOF join key, interval containment and `gcd`/`lcm`. Each of those has a test here, as do a scale of 9 and a scale of -2 on a `Decimal32`. Closes apache#27424. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A `Decimal128` whose scale is 19 or more needs a `Decimal256` common type with an integer, and the cast-unwrap rewrite in `casts.rs` did not accept a `Decimal256` literal, so the cast stayed on the column: `WHERE d <> 5` on a `DECIMAL(38, 24)` column ran `CAST(d AS Decimal256(44, 24)) != 5.0…`, 113 ms of `FilterExec` over 40M rows against 24 ms without the cast. Found in review, with this diff. It accepts one whose value and scale fit `i128` now; one that does not, such as 5 against a `Decimal128(38, 38)` column, keeps its cast as before. An `IN` list is the same rewrite and comes back with it. Nothing pinned this, so the preimage has a unit test and `simplify_expr.slt` gets the column shape whose plan must carry no cast. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
fc77d22 to
8d4db4c
Compare
|
Rebased and pushed, with the "Are there any user-facing changes?" now covers the type change you asked about: a |
jayzhan211
left a comment
There was a problem hiding this comment.
@cool9850311 thanks for applying the unwrap change; the plain DECIMAL(38, 24) filters are back to the no-cast plan, and the full sqllogictest suite passes locally (your fork's Rust CI was skipped). Approving with one follow-up: dictionary-encoded columns still keep the cast (inline, fine to handle in a separate PR).
| 4.000000000000000000000000 | ||
|
|
||
| query TT | ||
| explain select price38_24 from decimal_prices where price38_24 <> 5; |
There was a problem hiding this comment.
@cool9850311 thanks for the quick turnaround; plain columns unwrap again. The same cast still stays on a dictionary-encoded column, though: with d as Dictionary(Int32, Decimal128(38, 24)), d = 5 plans as CAST(d AS Decimal256(44, 24)) = 5.0…, where main plans d = Dictionary(Int32, Decimal128(5.0…, 38, 24)), and the same goes for IN (4, 5). The cause is that try_cast_dictionary only wraps a literal whose type equals the dictionary's value type. This arm fixes it, and the full sqllogictest suite plus the expr-common, optimizer and physical-expr tests pass with it:
(_, DataType::Dictionary(index_type, inner_type))
if **inner_type == lit_value_type =>
{
ScalarValue::Dictionary(index_type.clone(), Box::new(lit_value.clone()))
}
+ (_, DataType::Dictionary(index_type, inner_type)) => ScalarValue::Dictionary(
+ index_type.clone(),
+ Box::new(try_cast_numeric_literal(lit_value, inner_type)?),
+ ),It changes what try_cast_literal_to_type documents for dictionaries of every value type, so it's fine to handle in a follow-up PR with its own tests.
Repro
create table td as select arrow_cast(column1, 'Dictionary(Int32, Decimal128(38, 24))') as d
from (values (cast(4 as decimal(38,24))), (cast(5 as decimal(38,24))), (NULL));
explain select d from td where d = 5;
explain select d from td where d in (4, 5);There was a problem hiding this comment.
Will open follow-up PR
| None | ||
| } | ||
| } | ||
| ScalarValue::Decimal256(Some(v), _, scale) => { |
There was a problem hiding this comment.
Optional cleanup: this arm is now the fourth copy of the rescale body. With one helper, each decimal arm becomes a single line (47 fewer lines). Using checked_pow in the helper also means a bad scale returns None in the older arms instead of overflowing:
+/// Rescales the unscaled decimal `v` at `scale` to the scale whose multiplier is
+/// `mul`, or `None` if that drops digits or overflows `i128`.
+fn rescale_decimal_literal(v: i128, scale: i8, mul: i128) -> Option<i128> {
+ let lit_scale_mul = 10_i128.checked_pow(u32::try_from(scale).ok()?)?;
+ if mul >= lit_scale_mul {
+ v.checked_mul(mul / lit_scale_mul)
+ } else if v % (lit_scale_mul / mul) == 0 {
+ Some(v / (lit_scale_mul / mul))
+ } else {
+ None
+ }
+} ScalarValue::Decimal32(Some(v), _, scale) => {
rescale_decimal_literal(*v as i128, *scale, mul)
}
ScalarValue::Decimal64(Some(v), _, scale) => {
rescale_decimal_literal(*v as i128, *scale, mul)
}
ScalarValue::Decimal128(Some(v), _, scale) => {
rescale_decimal_literal(*v, *scale, mul)
}
ScalarValue::Decimal256(Some(v), _, scale) => {
rescale_decimal_literal(v.to_i128()?, *scale, mul)
}`rescale_decimal_literal` replaces the body each decimal arm of `try_cast_numeric_literal` had its own copy of. Its `checked_pow` also rejects a negative literal scale, where `10_i128.pow(scale as u32)` overflowed: `try_cast_literal_to_type` panicked on a `Decimal32`, `Decimal64` or `Decimal128` literal of negative scale, which `test_try_decimal_cast_out_of_range` now pins. A negative scale on the target type still overflows, since its multiplier is computed before any arm runs. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
Thanks @cool9850311 ! |
Which issue does this PR close?
#27095 already has #27124 open against it, which fixes it with the same variant-selection
idea this takes (credit to @namanjain24-sudo). Whether this PR should close #27095, or whether
that issue should stay with #27124, is a call for the maintainers: say which you prefer and I
will edit the description. If #27124 lands first, I am happy to rebase this onto it and keep
only the part that removes the
?.Rationale for this change
An integer compared with or added to a
Decimal32orDecimal64value returns wrongrows instead of an error. A
Decimal32(9, 2)holding5.50compares equal to5, isnot greater than
5, and5.50 + 1returns6as anInt64. The same values asDecimal128give the right answers.How many digits an integer needs is known exactly, so the common type of an integer and
a decimal has to keep room for them. It did not, in two ways:
coerce_numeric_type_to_decimal32had no arm forInt32or wider andcoerce_numeric_type_to_decimal64none forInt64, since those integers do not fitthe variant. Both callers treated that
Noneas "not a decimal case" and fell throughto the integer rules, which coerce the decimal to an integer and drop its fraction.
scale was kept, leaving a type the integer could not be cast into at all
(
Failed to cast field 'a' from Int32 to Decimal128(38, 38), Comparison of an integer with a wide decimal fails: common decimal type caps precision but keeps scale #27095).Both are the same hole, so one rule closes both: an integer's precision and scale are
now computed independently of any variant, and the common type is the narrowest variant
that holds the required precision and is no narrower than the decimal's own.
Decimal32(9, 2)withInt64becomesDecimal128(22, 2);Decimal128(38, 38)withInt32becomesDecimal256(48, 38). Where no variant holds the required precision --only a
Decimal256whose scale is large in either direction can reach that -- theprecision is still capped, so the comparison stays in decimals.
A float keeps the previous behaviour. The scale a float coerces to is an approximation of
its own (
Float64becomesDecimal128(30, 15)), and widening on that basis would moveordinary comparisons like
WHERE price = 4.00onto a wider variant.What changes are included in this PR?
In
datafusion/expr-common/src/type_coercion/binary.rs:integer_decimal_precisiongives an integer's precision and scale without choosing avariant;
narrowest_decimal_variantpicks the narrowest variant that holds a precisionand is no narrower than a given one.
get_common_decimal_typeuses them for an integer, and the fourcoerce_numeric_type_to_decimal*helpers are now float-only(
coerce_float_type_to_decimal*), since an integer no longer goes through them.math_decimal_coercion's eight integer arms become two guarded onis_decimal() && is_integer(): both operands move to the variant that holds them, eachkeeping its own precision and scale, so the result keeps the precision arrow derives
from them.
decimal_precision_and_scalereplaces the two inline matches inget_wider_decimal_type_cross_variant.In
datafusion/expr-common/src/casts.rs, the cast-unwrap rewrite accepts aDecimal256literal, soCAST(d AS Decimal256(44, 24)) != 5.0…becomesd != 5.0…as it did before this coercion change. A literal whose value or scale isbeyond
i128is still rejected, which keeps the cast.What is the testing strategy for this PR?
Unit tests for the coerced types, and sqllogictest for what a query returns:
type_coercion/binary/tests/comparison.rs: the common type ofDecimal32/Decimal64against each integer width, of each integer width against a wide-scale
Decimal128, ascale of 9 and a scale of -2 on a
Decimal32, theDecimal256whose precision iscapped, the cases that already fitted (which must not move), and a float against both.
type_coercion/binary/tests/arithmetic.rs: the operand pair for each arithmetic case inboth operand orders, plus
integer_decimal_precisionitself;test_decimal_mathematics_op_typenow covers the float-only helpers.interval_arithmetic.rs:contains_valueof aDecimal32interval against an integer,whose bounds used to be coerced to the integer and lose their fraction, which put
1inside
[1.50, 2.50].decimal.slt: the five queries from Comparing or adding an integer to a Decimal32/Decimal64 value casts the decimal to Int64 and drops its fraction #27424 witharrow_typeofpinned, the Comparison of an integer with a wide decimal fails: common decimal type caps precision but keeps scale #27095queries, which return rows instead of failing, an
INlist,greatest/leastand aUNION ALL, and aDecimal256(76, 70)compared with integers.asof_join.slt: aDecimal32ASOF equality key against anInt64one, which used tomake
1.50and1the same key, and a match condition across the two types.casts.rs: theDecimal256literal preimage, the literal that has no room in thecolumn's type (5 against
Decimal128(38, 38)), and the value and the scale that arebeyond
i128.simplify_expr.slt: adecimal(38, 24)column in the existing decimal-unwrap table,whose
<> 5andIN (4, 5)plans must carry no cast. Without thecasts.rschangeboth explains fail with the
Decimal256cast in the plan, and the unit test abovefails alone.
Each of those tests was run against this branch and against its base: every one fails on
the base for the value it pins. The
To Reproducequeries of both issues were also run byhand on both builds, and on the base they reproduce the reported output word for word.
Are there any user-facing changes?
Comparing or combining an integer with a
Decimal32orDecimal64value now stays indecimal arithmetic instead of truncating the decimal, and comparing an integer with a
wide-scale decimal returns rows instead of failing. Everything that asks for a common type
sees this, not just a comparison in
WHERE:INlist:d32 IN (5, 6)withd32at5.50returnedtrue, now returnsfalse;greatest/least:greatest(d32, 5)returned5as anInt64, now5.50;UNION ALLof such a column with an integer: the fraction was dropped silently;1.50and1were the same key;gcd/lcm:gcd(<Decimal32>, 4)used to be a plan error.A
Decimal128column whose scale is 19 or more also changes the type it reports, whereit worked before.
DECIMAL(38, 20)with an integer -- anInt64, which every integerliteral is -- now has
Decimal256(40, 20)as its common type instead ofDecimal128(38, 20), soCOALESCE(d, 0), aCASEarm, aUNION ALLbranch, aCREATE TABLE ASand a client reading the schema all see the wider type. The values arethe same;
Decimal128(38, 20)is the type that had no room for anInt64's digits,which is the hole this closes. The threshold is exactly a scale of 19 against an
Int64:an
Int8at that scale still fitsDecimal128(38, 19).That wider common type also made the literal in
WHERE d <> 5aDecimal256, which leftthe cast on the column: 113 ms in
FilterExecover 40M rows ofDECIMAL(38, 24), wherethe plan without the cast takes 24 ms. With the
casts.rschange the plan isd != 5.0…again, and so is the time.
No API changes.
Notes for reviewers
Decimal32(9, 2) * Int32hasDecimal64operands and aDecimal64(18, 2)result. Thatis what every decimal pair already gets:
Decimal32 + Decimal32caps the same way, andDecimal128 * Int64caps at 38 rather than widening toDecimal256. Widening a variantto fit a result would be a change of policy for all decimal arithmetic, so it is not
here.
narrowest_decimal_variantchecks the precision only. A variant's maximum scale equalsits maximum precision and the required precision already leaves room for the scale, so a
scale check would never change the answer.
🤖 Generated with Claude Code